I have the following in the compose file
volumes:
- "/etc/timezone:/etc/timezone:ro"
- "/etc/localtime:/etc/localtime:ro"
Then all good in Gerrit docker with its replication_log set with correct timestamp.
In addition to [string]::IsNullOrEmpty
in order to check for null or empty you can cast a string to a Boolean explicitly or in Boolean expressions:
$string = $null
[bool]$string
if (!$string) { "string is null or empty" }
$string = ''
[bool]$string
if (!$string) { "string is null or empty" }
$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }
Output:
False
string is null or empty
False
string is null or empty
True
string is not null or empty
To search the commit log (across all branches) for the given text:
git log --all --grep='Build 0051'
To search the actual content of commits through a repo's history, use:
git grep 'Build 0051' $(git rev-list --all)
to show all instances of the given text, the containing file name, and the commit sha1.
Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g
flag (short for --walk-reflogs
:
git log -g --grep='Build 0051'
EDIT: if you seem to have lost your history, check the reflog
as your safety net. Look for Build 0051 in one of the commits listed by
git reflog
You may have simply set your HEAD
to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.
To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)
git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip
Using Flexbox:
<style>
.container {
display: flex;
align-items: center; /* Vertical align */
justify-content: center; /* Horizontal align */
}
</style>
<div class="container">
<div class="block"></div>
</div>
Centers block
inside container
vertically (and horizontally).
Browser support: http://caniuse.com/flexbox
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
After installing ez_setup, you should have easy_install
available. To install pip
just do:
easy_install pip
I had this same error showing. When I replaced jQuery selector with normal JavaScript, the error was fixed.
var this_id = $(this).attr('id');
Replace:
getComputedStyle( $('#'+this_id)[0], "")
With:
getComputedStyle( document.getElementById(this_id), "")
You have indented part of your code in settings.py:
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'tinymce',
'sorl.thumbnail',
'south',
'django_facebook',
'djcelery',
'devserver',
'main',
Therefore, it is giving you an error.
Give the parent z-index: -1, or opacity: 0.99
Swift 3
let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.setTitle("Button", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
self.view.addSubview(btn)
func clickMe(sender:UIButton!) {
print("Button Clicked")
}
Output
You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.
Button kapatButon = (Button) findViewById(R.id.islemButonKapat);
Button hesaplaButon = (Button) findViewById(R.id.islemButonHesapla);
Button ayarlarButon = (Button) findViewById(R.id.islemButonAyarlar);
final EditText ders1Vize = (EditText) findViewById(R.id.ders1Vize);
final EditText ders1Final = (EditText) findViewById(R.id.ders1Final);
final EditText ders1Ortalama = (EditText) findViewById(R.id.ders1Ortalama);
//
final EditText ders2Vize = (EditText) findViewById(R.id.ders2Vize);
final EditText ders2Final = (EditText) findViewById(R.id.ders2Final);
final EditText ders2Ortalama = (EditText) findViewById(R.id.ders2Ortalama);
//
final EditText ders3Vize = (EditText) findViewById(R.id.ders3Vize);
final EditText ders3Final = (EditText) findViewById(R.id.ders3Final);
final EditText ders3Ortalama = (EditText) findViewById(R.id.ders3Ortalama);
//
final EditText ders4Vize = (EditText) findViewById(R.id.ders4Vize);
final EditText ders4Final = (EditText) findViewById(R.id.ders4Final);
final EditText ders4Ortalama = (EditText) findViewById(R.id.ders4Ortalama);
//
final EditText ders5Vize = (EditText) findViewById(R.id.ders5Vize);
final EditText ders5Final = (EditText) findViewById(R.id.ders5Final);
final EditText ders5Ortalama = (EditText) findViewById(R.id.ders5Ortalama);
//
final EditText ders6Vize = (EditText) findViewById(R.id.ders6Vize);
final EditText ders6Final = (EditText) findViewById(R.id.ders6Final);
final EditText ders6Ortalama = (EditText) findViewById(R.id.ders6Ortalama);
//
final EditText ders7Vize = (EditText) findViewById(R.id.ders7Vize);
final EditText ders7Final = (EditText) findViewById(R.id.ders7Final);
final EditText ders7Ortalama = (EditText) findViewById(R.id.ders7Ortalama);
//
/*
*
*
* */
kapatButon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// kapatma islemi
Toast.makeText(getApplicationContext(), "kapat",
Toast.LENGTH_LONG).show();
}
});
/*
*
*
* */
hesaplaButon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// hesap islemi
int d1v = Integer.parseInt(ders1Vize.getText().toString());
int d1f = Integer.parseInt(ders1Final.getText().toString());
int ort1 = (int) (d1v * 0.4 + d1f * 0.6);
ders1Ortalama.setText("" + ort1);
//
int d2v = Integer.parseInt(ders2Vize.getText().toString());
int d2f = Integer.parseInt(ders2Final.getText().toString());
int ort2 = (int) (d2v * 0.4 + d2f * 0.6);
ders2Ortalama.setText("" + ort2);
//
int d3v = Integer.parseInt(ders3Vize.getText().toString());
int d3f = Integer.parseInt(ders3Final.getText().toString());
int ort3 = (int) (d3v * 0.4 + d3f * 0.6);
ders3Ortalama.setText("" + ort3);
//
int d4v = Integer.parseInt(ders4Vize.getText().toString());
int d4f = Integer.parseInt(ders4Final.getText().toString());
int ort4 = (int) (d4v * 0.4 + d4f * 0.6);
ders4Ortalama.setText("" + ort4);
//
int d5v = Integer.parseInt(ders5Vize.getText().toString());
int d5f = Integer.parseInt(ders5Final.getText().toString());
int ort5 = (int) (d5v * 0.4 + d5f * 0.6);
ders5Ortalama.setText("" + ort5);
//
int d6v = Integer.parseInt(ders6Vize.getText().toString());
int d6f = Integer.parseInt(ders6Final.getText().toString());
int ort6 = (int) (d6v * 0.4 + d6f * 0.6);
ders6Ortalama.setText("" + ort6);
//
int d7v = Integer.parseInt(ders7Vize.getText().toString());
int d7f = Integer.parseInt(ders7Final.getText().toString());
int ort7 = (int) (d7v * 0.4 + d7f * 0.6);
ders7Ortalama.setText("" + ort7);
//
Toast.makeText(getApplicationContext(), "hesapla",
Toast.LENGTH_LONG).show();
}
});
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")
Sometimes I don't want to add items to a list when I instantiate it.
Instantiate a blank list
Dim blankList As List(Of String) = New List(Of String)
Add to the list
blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift
Loop through the list
For Each item in blankList
' write code here, for example:
Console.WriteLine(item)
Next
If you're targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy.
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
And in the Java class, use these below lines of code:
class MyActivity extends Activity {
public void myClickHandler(View target) {
// Do stuff
}
}
Another way could be to import the module in a function. This way when the function completes the module gets garbage collected.
Mutable objects can have their fields changed after construction. Immutable objects cannot.
public class MutableClass {
private int value;
public MutableClass(int aValue) {
value = aValue;
}
public void setValue(int aValue) {
value = aValue;
}
public getValue() {
return value;
}
}
public class ImmutableClass {
private final int value;
// changed the constructor to say Immutable instead of mutable
public ImmutableClass (final int aValue) {
//The value is set. Now, and forever.
value = aValue;
}
public final getValue() {
return value;
}
}
Use subset
(for interactive use)
subset(expr, cell_type == "hesc")
subset(expr, cell_type %in% c("bj fibroblast", "hesc"))
or better dplyr::filter()
filter(expr, cell_type %in% c("bj fibroblast", "hesc"))
Consider a simple function that adds the first N natural numbers. (e.g. sum(5) = 1 + 2 + 3 + 4 + 5 = 15
).
Here is a simple JavaScript implementation that uses recursion:
function recsum(x) {
if (x === 1) {
return x;
} else {
return x + recsum(x - 1);
}
}
If you called recsum(5)
, this is what the JavaScript interpreter would evaluate:
recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + 1)))
15
Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.
Here's a tail-recursive version of the same function:
function tailrecsum(x, running_total = 0) {
if (x === 0) {
return running_total;
} else {
return tailrecsum(x - 1, running_total + x);
}
}
Here's the sequence of events that would occur if you called tailrecsum(5)
, (which would effectively be tailrecsum(5, 0)
, because of the default second argument).
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15
In the tail-recursive case, with each evaluation of the recursive call, the running_total
is updated.
Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support tail call optimization. However, while tail call optimization is part of the ECMAScript 2015 spec, most JavaScript interpreters don't support it.
When you use an ORDER BY
clause inside of a sub query used in conjunction with a UNION
mysql will optimise away the ORDER BY
clause.
This is because by default a UNION
returns an unordered list so therefore an ORDER BY
would do nothing.
The optimisation is mentioned in the docs and says:
To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.
The last sentence of this is a bit misleading because it should have an effect. This optimisation causes a problem when you are in a situation where you need to order within the subquery.
To force MySQL to not do this optimisation you can add a LIMIT clause like so:
(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999)
UNION ALL
(SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999)
UNION ALL
(SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)
A high LIMIT
means that you could add an OFFSET
on the overall query if you want to do something such as pagination.
This also gives you the added benefit of being able to ORDER BY
different columns for each union.
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
You can't get value when calling getJSON
, only after response.
var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
myjson = json;
});
Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:
static String intToString(int num, int digits) {
assert digits > 0 : "Invalid number of digits";
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
I think an example of the case that has caught me by surprise is relevant:
var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
document.writeln( propertyName + " : " + myObject[propertyName] );
}
But to my surprise, the output is
name : Cody
status : Surprised
forEach : function (obj, callback) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
callback(prop);
}
}
}
Why? Another script on the page has extended the Object prototype:
Object.prototype.forEach = function (obj, callback) {
for ( prop in obj ) {
if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
callback( prop );
}
}
};
If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.
For example, given a file with the following contents, (called asdf.txt)
xxx yyy zzz
to only print the second column if it matches the pattern "yyy", you could do something like this:
awk '$2 ~ /yyy/ {print $2}' asdf.txt
Note that this will also match basically any line where the second column has a "yyy" in it, like these:
xxx yyyz zzz
xxx zyyyz
If your requirement is really
.ToString() would result in a string containing digits and +,-,.
and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.
For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:
NumberStyles style =
NumberStyles.AllowLeadingSign |
NumberStyles.AllowDecimalPoint |
double.TryParse(input, style, CultureInfo.InvariantCulture, out result);
This is a very simple solution to print out a tree. It is not that pretty, but it is really simple:
enum { kWidth = 6 };
void PrintSpace(int n)
{
for (int i = 0; i < n; ++i)
printf(" ");
}
void PrintTree(struct Node * root, int level)
{
if (!root) return;
PrintTree(root->right, level + 1);
PrintSpace(level * kWidth);
printf("%d", root->data);
PrintTree(root->left, level + 1);
}
Sample output:
106 105 104 103 102 101 100
I believe what the interviewer was trying to get at was probably the difference between interface and implementation.
The interface - not a Java interface, but "interface" in more general terms - to a code module is, basically, the contract made with client code that uses the interface.
The implementation of a code module is the internal code that makes the module work. Often you can implement a particular interface in more than one different way, and even change the implementation without client code even being aware of the change.
A Java interface should only be used as an interface in the above generic sense, to define how the class behaves for the benefit of client code using the class, without specifying any implementation. Thus, an interface includes method signatures - the names, return types, and argument lists - for methods expected to be called by client code, and in principle should have plenty of Javadoc for each method describing what that method does. The most compelling reason for using an interface is if you plan to have multiple different implementations of the interface, perhaps selecting an implementation depending on deployment configuration.
A Java abstract class, in contrast, provides a partial implementation of the class, rather than having a primary purpose of specifying an interface. It should be used when multiple classes share code, but when the subclasses are also expected to provide part of the implementation. This permits the shared code to appear in only one place - the abstract class - while making it clear that parts of the implementation are not present in the abstract class and are expected to be provided by subclasses.
If you don't feel like importing another module, this function works like the classNames
module.
function classNames(rules) {
var classes = ''
Object.keys(rules).forEach(item => {
if (rules[item])
classes += (classes.length ? ' ' : '') + item
})
return classes
}
You can use it like this:
render() {
var classes = classNames({
'storeInfoDiv': true,
'hover': this.state.isHovered == this.props.store.store_id
})
return (
<SomeComponent style={classes} />
)
}
Here is the implementation of LinkedList<T>#toArray(T[])
:
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
In short, you could only create generic arrays through Array.newInstance(Class, int)
where int
is the size of the array.
If you are generating Notification from a Service that is started in the foreground using
startForeground(NOTIFICATION_ID, notificationBuilder.build());
Then issuing
notificationManager.cancel(NOTIFICATION_ID);
does not end up canceling the Notification, and the notification still appears in the status bar. In this particular case, you will need to issue
stopForeground( true );
from within the service to put it back into background mode and to simultaneously cancel the notifications. Alternately, you can push it into the background without having it cancel the notification and then cancel the notification.
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
Thanks to both sipwiz and MrEvil. We developed a PHP script that will parse the URL that the user enters and paste www
to the top of it. (e.g. if the customer enters kiragiannis.com, then it will redirect to www.kiragiannis.com). So our customer point their root (e.g. customer1.com
to A
record where our web redirector is) and then www
CNAME
to the real A
record managed by us.
Below the code in case you are interested for future us.
<?php
$url = strtolower($_SERVER["HTTP_HOST"]);
if(strpos($url, "//") !== false) { // remove http://
$url = substr($url, strpos($url, "//") + 2);
}
$urlPagePath = "";
if(strpos($url, "/") !== false) { // store post-domain page path to append later
$urlPagePath = substr($url, strpos($url, "/"));
$url = substr($url, 0, strpos($url,"/"));
}
$urlLast = substr($url, strrpos($url, "."));
$url = substr($url, 0, strrpos($url, "."));
if(strpos($url, ".") !== false) { // get rid of subdomain(s)
$url = substr($url, strrpos($url, ".") + 1);
}
$url = "http://www." . $url . $urlLast . $urlPagePath;
header( "Location:{$url}");
?>
Java implementation (if any one requires)
Reading : Client to Server
int len = 0;
byte[] b = new byte[buffLenth];
//rawIn is a Socket.getInputStream();
while(true){
len = rawIn.read(b);
if(len!=-1){
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
//b[0] is always text in my case so no need to check;
byte data = b[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if(rLength==(byte)126) rMaskIndex=4;
if(rLength==(byte)127) rMaskIndex=10;
byte[] masks = new byte[4];
int j=0;
int i=0;
for(i=rMaskIndex;i<(rMaskIndex+4);i++){
masks[j] = b[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = len - rDataStart;
byte[] message = new byte[messLen];
for(i=rDataStart, j=0; i<len; i++, j++){
message[j] = (byte) (b[i] ^ masks[j % 4]);
}
parseMessage(new String(message));
//parseMessage(new String(b));
b = new byte[buffLenth];
}
}
Writing : Server to Client
public void brodcast(String mess) throws IOException{
byte[] rawData = mess.getBytes();
int frameCount = 0;
byte[] frame = new byte[10];
frame[0] = (byte) 129;
if(rawData.length <= 125){
frame[1] = (byte) rawData.length;
frameCount = 2;
}else if(rawData.length >= 126 && rawData.length <= 65535){
frame[1] = (byte) 126;
int len = rawData.length;
frame[2] = (byte)((len >> 8 ) & (byte)255);
frame[3] = (byte)(len & (byte)255);
frameCount = 4;
}else{
frame[1] = (byte) 127;
int len = rawData.length;
frame[2] = (byte)((len >> 56 ) & (byte)255);
frame[3] = (byte)((len >> 48 ) & (byte)255);
frame[4] = (byte)((len >> 40 ) & (byte)255);
frame[5] = (byte)((len >> 32 ) & (byte)255);
frame[6] = (byte)((len >> 24 ) & (byte)255);
frame[7] = (byte)((len >> 16 ) & (byte)255);
frame[8] = (byte)((len >> 8 ) & (byte)255);
frame[9] = (byte)(len & (byte)255);
frameCount = 10;
}
int bLength = frameCount + rawData.length;
byte[] reply = new byte[bLength];
int bLim = 0;
for(int i=0; i<frameCount;i++){
reply[bLim] = frame[i];
bLim++;
}
for(int i=0; i<rawData.length;i++){
reply[bLim] = rawData[i];
bLim++;
}
out.write(reply);
out.flush();
}
At the time of writing, here's the best pure CSS implementation for color manipulation I found:
Use CSS variables to define your colors in HSL instead of HEX/RGB format, then use calc()
to manipulate them.
Here's a basic example:
:root {_x000D_
--link-color-h: 211;_x000D_
--link-color-s: 100%;_x000D_
--link-color-l: 50%;_x000D_
--link-color-hsl: var(--link-color-h), var(--link-color-s), var(--link-color-l);_x000D_
_x000D_
--link-color: hsl(var(--link-color-hsl));_x000D_
--link-color-10: hsla(var(--link-color-hsl), .1);_x000D_
--link-color-20: hsla(var(--link-color-hsl), .2);_x000D_
--link-color-30: hsla(var(--link-color-hsl), .3);_x000D_
--link-color-40: hsla(var(--link-color-hsl), .4);_x000D_
--link-color-50: hsla(var(--link-color-hsl), .5);_x000D_
--link-color-60: hsla(var(--link-color-hsl), .6);_x000D_
--link-color-70: hsla(var(--link-color-hsl), .7);_x000D_
--link-color-80: hsla(var(--link-color-hsl), .8);_x000D_
--link-color-90: hsla(var(--link-color-hsl), .9);_x000D_
_x000D_
--link-color-warm: hsl(calc(var(--link-color-h) + 80), var(--link-color-s), var(--link-color-l));_x000D_
--link-color-cold: hsl(calc(var(--link-color-h) - 80), var(--link-color-s), var(--link-color-l));_x000D_
_x000D_
--link-color-low: hsl(var(--link-color-h), calc(var(--link-color-s) / 2), var(--link-color-l));_x000D_
--link-color-lowest: hsl(var(--link-color-h), calc(var(--link-color-s) / 4), var(--link-color-l));_x000D_
_x000D_
--link-color-light: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) / .9));_x000D_
--link-color-dark: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) * .9));_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.flex > div {_x000D_
flex: 1;_x000D_
height: calc(100vw / 10);_x000D_
}
_x000D_
<h3>Color Manipulation (alpha)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-10)"></div>_x000D_
<div style="background-color: var(--link-color-20)"></div>_x000D_
<div style="background-color: var(--link-color-30)"></div>_x000D_
<div style="background-color: var(--link-color-40)"></div>_x000D_
<div style="background-color: var(--link-color-50)"></div>_x000D_
<div style="background-color: var(--link-color-60)"></div>_x000D_
<div style="background-color: var(--link-color-70)"></div>_x000D_
<div style="background-color: var(--link-color-80)"></div>_x000D_
<div style="background-color: var(--link-color-90)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Hue)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-warm)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-cold)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Saturation)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-low)"></div>_x000D_
<div style="background-color: var(--link-color-lowest)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Lightness)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
<div style="background-color: var(--link-color-light)"></div>_x000D_
<div style="background-color: var(--link-color)"></div>_x000D_
<div style="background-color: var(--link-color-dark)"></div>_x000D_
</div>
_x000D_
I also created a CSS framework (still in early stage) to provide basic CSS variables support called root-variables.
public int this[int index]
{
get => values[index];
}
This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:
int[] x = {1,2,3,4};
String y = {"a","b","c"};
If you're not on the RHS of a variable declaration, use an array constructor instead:
int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};
These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.
In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:
double[][] m = new double[4][4];
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
m[i][j] = i*j;
}
}
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
If you pushed the changes, you can undo
it and move the files back to stage without using another branch.
git show HEAD > patch
git revert HEAD
git apply patch
It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.
I don't see any problem, unless you are not managing them using a connection pool.
If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.
To solve the problem, double-click the "MIME Types" configuration option while having IIS root node selected in the left panel and click "Add..." link in the Actions panel on the right. This will bring up the following dialog. Add .woff file extension and specify "application/x-font-woff" as the corresponding MIME type:
Follow same for woff2 with application/x-font-woff2
This probably because of your gzip version incompatibility.
Check these points first:
which gzip
/usr/bin/gzip or /bin/gzip
It should be either /bin/gzip or /usr/bin/gzip. If your gzip points to some other gzip application please try by removing that path from your PATH env variable.
Next is
gzip -V
gzip 1.3.5 (2002-09-30)
Your problem can be resolve with these check points.
I had the same error message. But the cause and solution are slightly different. When I ran "ng -v" it showed different versions for angular-cli (1.0.0-beta.28.3) and @angular/cli (1.0.0-beta.31). I re-ran:
npm install -g @angular/cli
Now both show a version of 1.0.0-beta.31. The error message is gone and "ng serve" now works. (Yes - it was @angular/cli that I re-installed and the angular-cli version was updated.)
This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.
=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))
You can also substitute TIME
with DATE
to add or subtract a date or time.
Power has more precedence than multiply, so:
2**2*3 = (2^2)*3
2*2*3 = 2*2*3
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
for fstr in strlist:
if line.find(fstr) != -1:
print('found')
res = True
if res:
print('res true')
else:
print('res false')
The following bash script extracts all zip files in the current directory into new dirs with the filename of the zip file, i.e.:
The following files:
myfile1.zip
myfile2.zip
Will be extracted to:
./myfile1/files...
./myfile2/files...
Shell script:
#!/bin/sh
for zip in *.zip
do
dirname=`echo $zip | sed 's/\.zip$//'`
if mkdir "$dirname"
then
if cd "$dirname"
then
unzip ../"$zip"
cd ..
# rm -f $zip # Uncomment to delete the original zip file
else
echo "Could not unpack $zip - cd failed"
fi
else
echo "Could not unpack $zip - mkdir failed"
fi
done
This is how you can create a beautiful button with a bezel and rounded edges:
loginButton = UIButton(frame: CGRectMake(self.view.bounds.origin.x + (self.view.bounds.width * 0.325), self.view.bounds.origin.y + (self.view.bounds.height * 0.8), self.view.bounds.origin.x + (self.view.bounds.width * 0.35), self.view.bounds.origin.y + (self.view.bounds.height * 0.05)))
loginButton.layer.cornerRadius = 18.0
loginButton.layer.borderWidth = 2.0
loginButton.backgroundColor = UIColor.whiteColor()
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor(red: 24.0/100, green: 116.0/255, blue: 205.0/205, alpha: 1.0), forState: UIControlState.Normal)
In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.
For example:
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
browserHistory,
Switch
} from 'react-router-dom';
import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';
const Root = () => (
<Router history={browserHistory}>
<Switch>
<Route exact path="/" component={App}/>
<Route path="/welcome" component={Welcome}/>
<Route component={NotFound}/>
</Switch>
</Router>
);
ReactDOM.render(
<Root/>,
document.getElementById('root')
);
Hi @Hayden Stites I faced the same issue, but after some tries I found it was happening because I was trying to create build in git bash , instead of CMD with admin access. If you create build with Command prompt run as administrator build will get create.
Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.
Using %s
>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797
Using .format
>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869
Using f
>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
String jsonText = readAll(inputofyourjsonstream);
JSONObject json = new JSONObject(jsonText);
JSONArray arr = json.getJSONArray("Compemployes");
Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:
arr.getJSONObject(index)
to get the objects inside of the array.
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
result.class.table_name.singularize
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
Simple like a piece of CAKE!
You can define a new column type like (L
in this case) while maintaining the current alignment (c
, r
or l
):
\documentclass{article}
\usepackage{array}
\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}
\begin{document}
\begin{table}
\begin{tabular}{|c|L|L|}
\hline
Title 1 & Title 2 & Title 3 \\
\hline
one-liner & multi-line and centered & \multicolumn{1}{m{3cm}|}{multi-line piece of text to show case a multi-line and justified cell} \\
\hline
apple & orange & banana \\
\hline
apple & orange & banana \\
\hline
\end{tabular}
\end{table}
\end{document}
As the original question does not state which NuGet frontend should be used, I would like to mention that NuGet 3.5 adds support for updating to a specific version via the command line client (which works for downgrades, too):
NuGet.exe update Common.Logging -Version 1.2.0
You can add a .env
file in all your projects containing COMPOSE_PROJECT_NAME=somename
.
COMPOSE_PROJECT_NAME overrides the prefix used to name resources, as such all your projects will use somename_default
as their network, making it possible for services to communicate with each other as they were in the same project.
NB: You'll get warnings for "orphaned" containers created from other projects.
this could works, if you are receiving a json or an xml from the service and i think this can give you an idea about how the headers and the T type works too, if you use the function MakeXmlRequest(put results in xmldocumnet) and MakeJsonRequest(put the json in the class you wish that have the same structure that the json response) in the next way
/*-------------------------example of use-------------*/
MakeXmlRequest<XmlDocument>("your_uri",result=>your_xmlDocument_variable = result,error=>your_exception_Var = error);
MakeJsonRequest<classwhateveryouwant>("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
/*-------------------------------------------------------------------------------*/
public class RestService
{
public void MakeXmlRequest<T>(string uri, Action<XmlDocument> successAction, Action<Exception> errorAction)
{
XmlDocument XMLResponse = new XmlDocument();
string wufooAPIKey = ""; /*or username as well*/
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
string documento = "";
MakeRequest(request,response=> documento = response,
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
XMLResponse.LoadXml(documento);
successAction(XMLResponse);
}
public void MakeJsonRequest<T>(string uri, Action<T> successAction, Action<Exception> errorAction)
{
string wufooAPIKey = "";
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
// request.Accept = "application/json";
// request.Method = "GET";
MakeRequest(
request,
(response) =>
{
if (successAction != null)
{
T toReturn;
try
{
toReturn = Deserialize<T>(response);
}
catch (Exception ex)
{
errorAction(ex);
return;
}
successAction(toReturn);
}
},
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
}
private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
{
try{
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var objText = reader.ReadToEnd();
successAction(objText);
}
}
}catch(HttpException ex){
errorAction(ex);
}
}
private T Deserialize<T>(string responseBody)
{
try
{
var toReturns = JsonConvert.DeserializeObject<T>(responseBody);
return toReturns;
}
catch (Exception ex)
{
string errores;
errores = ex.Message;
}
var toReturn = JsonConvert.DeserializeObject<T>(responseBody);
return toReturn;
}
}
}
If you just have the xml
file of the color scheme you can:
Go to Preferences
-> Editor
-> Color and Fonts
and use the Import
button.
You can add hibernate validator dependency, to provide a Validator
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>
This is a mistake:
m.check(side);
That code has to go inside a function. Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m;
means that an Orderbook
will contain Message
called m
, if you later create an Orderbook
.
both that just need using vanilla javascript
live demo
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
// log(`e.target`, e.target);_x000D_
const select = e.target;_x000D_
const value = select.value;_x000D_
const desc = select.selectedOptions[0].text;_x000D_
log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
<label for="area">Area</label>_x000D_
<select id="area">_x000D_
<option value="101">A1</option>_x000D_
<option value="102">B2</option>_x000D_
<option value="103">C3</option>_x000D_
</select>_x000D_
</div>
_x000D_
live demo
const log = console.log;_x000D_
const areaSelect = document.querySelector(`[id="area"]`);_x000D_
_x000D_
areaSelect.addEventListener(`change`, (e) => {_x000D_
// log(`e.target`, e.target);_x000D_
const select = e.target;_x000D_
const value = select.value;_x000D_
const desc = select.options[select.selectedIndex].text;_x000D_
log(`option desc`, desc);_x000D_
});
_x000D_
<div class="select-box clearfix">_x000D_
<label for="area">Area</label>_x000D_
<select id="area">_x000D_
<option value="101">A1</option>_x000D_
<option value="102">B2</option>_x000D_
<option value="103">C3</option>_x000D_
</select>_x000D_
</div>
_x000D_
Yes, I agreed with the above comments. And indeed, it does seem like the right (or at least the easiest?) thing to do is to specify (in XML) an initial layout height of "0px" -- and then you can pass in another argument for "toHeight" (i.e. the "final height") to the constructor of your custom Animation sub-class, e.g. in the example above, it would look something like so:
public DropDownAnim( View v, int toHeight ) { ... }
Anyways, hope that helps! :)
When you say you increased MAVEN_OPTS
, what values did you increase? Did you increase the MaxPermSize
, as in example:
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"
(or on Windows:)
set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m
You can also specify these JVM options in each maven project separately.
Note: This code is untested
Define a record for your refCursor return type, call it rec. For example:
TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...); --define the record
rec MyRec; -- instantiate the record
Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:
LOOP
FETCH refCursor INTO rec;
EXIT WHEN refCursor%NOTFOUND;
dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;
Disclaimer: this fix works with Alpha44
I had the same issue and solved it by implementing the HashLocationStrategy listed in the Angular.io API Preview.
https://angular.io/docs/ts/latest/api/common/index/HashLocationStrategy-class.html
Start by importing the necessary directives
import {provide} from 'angular2/angular2';
import {
ROUTER_PROVIDERS,
LocationStrategy,
HashLocationStrategy
} from 'angular2/router';
And finally, bootstrap it all together like so
bootstrap(AppCmp, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy})
]);
Your route will appear as http://localhost/#/route and when you refresh, it will reload at it's proper place.
Hope that helps!
Use <code>
for inline code that can wrap and <pre><code>
for block code that must not wrap. <samp>
is for sample output, so I would avoid using it to represent sample code (which the reader is to input). This is what Stack Overflow does.
(Better yet, if you want easy to maintain, let the users edit the articles as Markdown, then they don’t have to remember to use <pre><code>
.)
HTML5 agrees with this in “the pre
element”:
The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.
Some examples of cases where the pre element could be used:
- Including fragments of computer code, with structure indicated according to the conventions of that language.
[…]
To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter.
In the following snippet, a sample of computer code is presented.
<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
this.element = element;
this.canClose = canClose;
this.closeHandler = function () { if (closeHandler) closeHandler() };
}</code></pre>
_x000D_
go to the master branch our-team
pull all the new changes from our-team
branch
go to your branch featurex
featurex
merge the changes of our-team
branch into featurex
branch
our-team
{commit-hash}
if you want to merge specific commitspush your changes with the changes of our-team
branch
Note: probably you will have to fix conflicts after merging our-team
branch into featurex
branch before pushing
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
I found the Chrome option to be OK but there are quite a few steps to go through to get to the font files. Once you're there, the downloading is super easy. I usually use the dev tools in Safari as there are fewer steps. Just go to the page you want, click on "Show page source" or "show page resources" in the Developer menu (both work for this) and the page resources are listed in folders on the left hand side. Click the font folder and the fonts are listed. Right click and save file. If you are downloading a lot of font files from one site it may be quicker to work your way through Chrome's pathway as the "open in tab" does download the fonts quicker. If you're taking one or two fonts from a lot of different sites, Safari will be quicker overall.
You could have is_hammer
in terms of row["Open"]
etc. as follows
def is_hammer(rOpen,rLow,rClose,rHigh):
return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
and closed_in_top_half_of_range(rHigh,rLow,rClose)
Then you can use map:
df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])
The sizzle selector engine (what powers JQuery) is perfectly geared up for this:
var elements = $('input[type=text]');
Or
var elements = $('input:text');
Whilst there is no portable #define or something to rely upon, platforms do provide standard functions for converting to and from your 'host' endian.
Generally, you do storage - to disk, or network - using 'network endian', which is BIG endian, and local computation using host endian (which on x86 is LITTLE endian). You use htons()
and ntohs()
and friends to convert between the two.
#wrapper
{
min-width:960px;
margin-left:auto;
margin-right:auto;
position-relative;
}
#left
{
width:200px;
position: absolute;
background-color:antiquewhite;
margin-left:10px;
z-index: 2;
}
#content
{
padding-left:210px;
width:100%;
background-color:AppWorkspace;
position: relative;
z-index: 1;
}
If you need the whitespace on the right of #left
, then add a border-right: 10px solid #FFF;
to #left
and add 10px
to the padding-left
in #content
Another way: you can use RedisWorks
library.
pip install redisworks
>>> from redisworks import Root
>>> root = Root()
>>> root.something = {1:"a", "b": {2: 2}} # saves it as Hash type in Redis
...
>>> print(root.something) # loads it from Redis
{'b': {2: 2}, 1: 'a'}
>>> root.something['b'][2]
2
It converts python types to Redis types and vice-versa.
>>> root.sides = [10, [1, 2]] # saves it as list in Redis.
>>> print(root.sides) # loads it from Redis
[10, [1, 2]]
>>> type(root.sides[1])
<class 'list'>
Disclaimer: I wrote the library. Here is the code: https://github.com/seperman/redisworks
Another easy way:
SELECT Date, User, Status, Notes
FROM Test_Most_Recent
WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)
You are trying to copy the war
file to a directory below webapps
. The war file should be copied into the webapps
directory.
Remove the mkdir command, and copy the war
file like this:
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war
Tomcat will extract the war if autodeploy
is turned on.
I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:
Correct:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="android.permission.access_fine_location" />
Though this may seem trivial, its easy to overlook.
If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!
You've probably tried this to but why not just use the mb_convert_encoding function? It will attempt to auto-detect char set of the text provided or you can pass it a list.
Also, I tried to run:
$text = "fiancée";
echo mb_convert_encoding($text, "UTF-8");
echo "<br/><br/>";
echo iconv(mb_detect_encoding($text), "UTF-8", $text);
and the results are the same for both. How do you see that your text is truncated to 'fianc'? is it in the DB or in a browser?
Here's a good example. I use it to rename the variable because the JSON is coming from a .Net
environment where properties start with an upper-case letter.
public class Parameter {
@JsonProperty("Name")
public String name;
@JsonProperty("Value")
public String value;
}
This correctly parses to/from the JSON:
"Parameter":{
"Name":"Parameter-Name",
"Value":"Parameter-Value"
}
I use this
for dir in $(find . -name ".git")
do cd ${dir%/*}
echo $PWD
git pull
echo ""
cd - > /dev/null
done
hash.store(key, value) - Stores a key-value pair in hash.
Example:
hash #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.
The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.
decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.
For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999
You can get all checked checkboxes like this:
var boxes = $(":checkbox:checked");
And all non-checked like this:
var nboxes = $(":checkbox:not(:checked)");
You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array()
request to know whether or not any particular box should be checked at a later date.
jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:
single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2
This will enable you to keep the information for which elements were checked as well.
In order to solve the problem set:
Make sure you have the Lombok plugin for IntelliJ installed!
->
PluginsImmediately after your execute statement you can have an if statement. For example
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
For reference, I had this error message and the solution was that when you specify the library you miss the 'lib' off the front and the '.so' from the end.
So, if you have a file libmyfablib.so, you need to call:
System.loadLibrary("myfablib"); // this loads the file 'libmyfablib.so'
Having looked in the apk, installed/uninstalled and tried all kinds of complex solutions I couldn't see the simple problem that was right in front of my face!
When people are suggesting "use a list or tuple or other data structure", what they're saying is that, when you have a lot of different values that you care about, naming them all separately as local variables may not be the best way to do things.
Instead, you may want to gather them together into a larger data structure that can be stored in a single local variable.
intuited showed how you might use a dictionary for this, and Chris Lutz showed how to use a tuple for temporary storage before unpacking into separate variables, but another option to consider is to use collections.namedtuple
to bundle the values more permanently.
So you might do something like:
# Define the attributes of our named tuple
from collections import namedtuple
DataHolder = namedtuple("DataHolder", "a b c d e f g")
# Store our data
data = DataHolder(True, True, True, True, True, False, True)
# Retrieve our data
print(data)
print(data.a, data.f)
Real code would hopefully use more meaningful names than "DataHolder" and the letters of the alphabet, of course.
Inspired by an answer of @walid2mi:
(Get-Item 'c:\temp\myfile.txt').Basename
Please note: this only works if the given file really exists.
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:
// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());
You can find the answer to your question on the following page:
https://stackoverflow.com/a/17633941/2359161
Here is the JSFiddle that was given:
Note the scrolling section at the end of the CSS, specifically:
/*_x000D_
*Styling_x000D_
*/_x000D_
_x000D_
html,body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
*Scrolling_x000D_
*/_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
<ul>_x000D_
<li><a href="#servicios"> Servicios </a> </li>_x000D_
<li><a href="#galeria"> Galeria </a> </li>_x000D_
<li><a href="#contacto">Contacta nos </a> </li>_x000D_
</ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
<h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
<h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
<h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
If you want to replace a "full nested dictionary with arrays" you can use this snippet :
It will replace any "old_value" by "new_value". It's roughly doing a depth-first rebuilding of the dictionary. It can even work with List or Str/int given as input parameter of first level.
def update_values_dict(original_dict, future_dict, old_value, new_value):
# Recursively updates values of a nested dict by performing recursive calls
if isinstance(original_dict, Dict):
# It's a dict
tmp_dict = {}
for key, value in original_dict.items():
tmp_dict[key] = update_values_dict(value, future_dict, old_value, new_value)
return tmp_dict
elif isinstance(original_dict, List):
# It's a List
tmp_list = []
for i in original_dict:
tmp_list.append(update_values_dict(i, future_dict, old_value, new_value))
return tmp_list
else:
# It's not a dict, maybe a int, a string, etc.
return original_dict if original_dict != old_value else new_value
If Publishing in Visual Studio 2012 when erroring try unchecking the "Procompile during publishing" option in the Publish wizard.
You could also use the !important feature of css to make qualities you do not want to override in the original class. I am using this on my site to keep some of the essential characteristics of the original class while overriding others:
<div class="foo bar">
.foo {
color: blue;
width: 200px !important;
}
.bar {
color: red;
width: 400px;
}
This will generate a class "foo bar" element that is red and 200px. This is great if you are using the other two classes individually and just want a piece from each class.
I've found Tomcat to be rather finicky in that a running process or an open port doesn't necessarily mean it's actually handling requests. I usually try to grab a known page and compare its contents with a precomputed expected value.
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
You have to do the following:
if "%1" == "" (
echo The variable is empty
) ELSE (
echo The variable contains %1
)
I wish AngularJS had a built in confirmation dialog. Often, it is nicer to have a customized dialog than using the built in browser one.
I briefly used the twitter bootstrap until it was discontinued with version 6. I looked around for alternatives, but the ones I found were complicated. I decided to try the JQuery UI one.
Here is my sample that I call when I am about to remove something from ng-grid;
// Define the Dialog and its properties.
$("<div>Are you sure?</div>").dialog({
resizable: false,
modal: true,
title: "Modal",
height: 150,
width: 400,
buttons: {
"Yes": function () {
$(this).dialog('close');
//proceed with delete...
/*commented out but left in to show how I am using it in angular
var index = $scope.myData.indexOf(row.entity);
$http['delete']('/EPContacts.svc/json/' + $scope.myData[row.rowIndex].RecordID).success(function () { console.log("groovy baby"); });
$scope.gridOptions.selectItem(index, false);
$scope.myData.splice(index, 1);
*/
},
"No": function () {
$(this).dialog('close');
return;
}
}
});
I hope this helps someone. I was pulling my hair out when I needed to upgrade ui-bootstrap-tpls.js but it broke my existing dialog. I came into work this morning, tried a few things and then realized I was over complicating.
You are not getting the answer you are looking for, are you.
Two ways to do what you want:
You could do something like this
String[] myStrings = { "One", "Two", "Three" };
or in expression
functionCall(new String[] { "One", "Two", "Three" });
or
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
simplified to one function:
function removeWhiteSpace($text)
{
$text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
$text = preg_replace('/([\s])\1+/', ' ', $text);
$text = trim($text);
return $text;
}
based on Danuel O'Neal answer.
This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct
)
drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]
Where x
is a dataframe and pct
is the threshold of NA
-filled data you want to get rid of.
pct = 1
means remove rows that have 100% of its values NA
.
pct = .5
means remome rows that have at least half its values NA
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
A clean if/else conditional shell script:
if ./somecommand | grep -q 'some_string'; then
echo "exists"
else
echo "doesn't exist"
fi
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
try the following command:
which gcc-arm-linux-gnueabi
Its very likely the command is installed in /usr/bin
.
Arrays in Java are of fixed size that is specified when they are declared. To increase the size of the array you have to create a new array with a larger size and copy all of the old values into the new array.
ex:
char[] copyFrom = { 'a', 'b', 'c', 'd', 'e' };
char[] copyTo = new char[7];
System.out.println(Arrays.toString(copyFrom));
System.arraycopy(copyFrom, 0, copyTo, 0, copyFrom.length);
System.out.println(Arrays.toString(copyTo));
Alternatively you could use a dynamic data structure like a List.
The solution is to NOT use height and width at all! Attach the inner box using top, left, right, bottom and then add margin.
.box {margin:8px; position:absolute; top:0; left:0; right:0; bottom:0}
_x000D_
<div class="box" style="background:black">_x000D_
<div class="box" style="background:green">_x000D_
<div class="box" style="background:lightblue">_x000D_
This will show three nested boxes. Try resizing browser to see they remain nested properly._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Here's my proposition:
for i in range(len(rserver.keys())):
salt = uuid.uuid4().hex
print(salt)
mdp_hash = rserver.get(rserver.keys()[i])
rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
rsalt.set(rserver.keys()[i], salt)
There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.
This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine()
, Console.Read()
) with the console window if you do not show the windows forms; output to Console - Console.WriteLine()
- works in both modes.
This is provided as is; no guarantees this won't do something horrible later on, but it does work.
Start from a standard Console Application.
Mark the Main
method as [STAThread]
Add a reference in your project to System.Windows.Forms
Add a Windows Form to your project.
Add the standard Windows start code to your Main
method:
You will have an application that shows the Console and optionally windows forms.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0 && args[0] == "console") {
Console.WriteLine("Hello world!");
Console.ReadLine();
}
else {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Click(object sender, EventArgs e) {
Console.WriteLine("Clicked");
}
}
}
Use the group collection of the Match object, indexing it with the capturing group name, e.g.
foreach (Match m in mc){
MessageBox.Show(m.Groups["link"].Value);
}
For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.
Using the BaseName in Get-ChildItem displays the name of the file and and using Name displays the file name with the extension.
$filepath = Get-ChildItem "E:\Test\Basic-English-Grammar-1.pdf"
$filepath.BaseName
Basic-English-Grammar-1
$filepath.Name
Basic-English-Grammar-1.pdf
The query can be written slightly simpler, like this:
DECLARE @T INT = 2
SELECT CASE
WHEN @T < 1 THEN 'less than one'
WHEN @T = 1 THEN 'one'
ELSE 'greater than one'
END T
In most cases, it is enough just to hide the element, for example in this way:
export default class ErrorBoxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isHidden: false
}
}
dismiss() {
this.setState({
isHidden: true
})
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
Or you may render/rerender/not render via parent component like this
export default class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isErrorShown: true
}
}
dismiss() {
this.setState({
isErrorShown: false
})
}
showError() {
if (this.state.isErrorShown) {
return <ErrorBox
error={ this.state.error }
dismiss={ this.dismiss.bind(this) }
/>
}
return null;
}
render() {
return (
<div>
{ this.showError() }
</div>
);
}
}
export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.props.dismiss();
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className="alert-box error-box">
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.
export default class ErrorBoxComponent extends React.Component {
dismiss() {
this.el.remove();
}
render() {
if (!this.props.error) {
return null;
}
return (
<div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
{ this.props.error }
<a href="#" className="close" onClick={ this.dismiss.bind(this) }>×</a>
</div>
);
}
}
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
Declare @month as char(2)
Declare @date as char(2)
Declare @year as char(4)
declare @time as char(8)
declare @customdate as varchar(20)
set @month = MONTH(GetDate());
set @date = Day(GetDate());
set @year = year(GetDate());
set @customdate= @month+'/'+@date+'/'+@year+' '+ CONVERT(varchar(8), GETDATE(),108);
print(@customdate)
How about:
void rmdup(int *array, int length)
{
int *current , *end = array + length - 1;
for ( current = array + 1; array < end; array++, current = array + 1 )
{
while ( current <= end )
{
if ( *current == *array )
{
*current = *end--;
}
else
{
current++;
}
}
}
}
Should be O(n^2) or less.
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
This will get what you want in plain JS.
var el = document.getElementById('*spaM4');
text = (el.innerText || el.textContent);
To find it from Windows OS,
catalina.bat version
It should print jre version details along with other informative details.
Using CATALINA_BASE: "C:\User\software\enterprise-server-tome...
Using CATALINA_HOME: "C:\User\software\enterprise-server-tome...
Using CATALINA_TMPDIR: "C:\User\software\enterprise-server-tome...
Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_25"
Using CLASSPATH: "C:\User\software\enterprise-server-tome...
Server version: Apache Tomcat/8.5.11
Server built: Jan 10 2017 21:02:52 UTC
Server number: 8.5.11.0
OS Name: Windows 7
OS Version: 6.1
Architecture: amd64
JVM Version: 1.8.0_25-b18
JVM Vendor: Oracle Corporation
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
I always create 7 functions, to work with date in JS:
addSeconds
, addMinutes
, addHours
, addDays
, addWeeks
, addMonths
, addYears
.
You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/
How to use:
var now = new Date();
console.log(now.addMinutes(30));
console.log(now.addWeeks(3));
These are the functions:
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
return this;
};
Date.prototype.addMinutes = function(minutes) {
this.setMinutes(this.getMinutes() + minutes);
return this;
};
Date.prototype.addHours = function(hours) {
this.setHours(this.getHours() + hours);
return this;
};
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addWeeks = function(weeks) {
this.addDays(weeks*7);
return this;
};
Date.prototype.addMonths = function (months) {
var dt = this.getDate();
this.setMonth(this.getMonth() + months);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Date.prototype.addYears = function(years) {
var dt = this.getDate();
this.setFullYear(this.getFullYear() + years);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
I've checked your JSON data
{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
in http://jsonlint.com/ and the results were:
Error: Parse error on line 1:
{ 'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'
modifying it to the following string solve the JSON error:
{
"http://example.org/about": {
"http://purl.org/dc/terms/title": [{
"type": "literal",
"value": "Anna's Homepage"
}]
}
}
On my linux machine I use a script like this:
export IDEA_JDK=/opt/jdk14
/idea-IC/bin/idea.sh
I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.
Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
No data in plot
gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'
gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
String.split()
can also accept a regular expression:
input.split(/[ ,]+/);
This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.
The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:
...
...
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
android:id="@+id/icon_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</TabHost>
in Java:
final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;
FrameLayout frameLayout = (FrameLayout) materialDialog
.findViewById(R.id.icon_frame_container);
frameLayout.setOnTouchListener(
new OnSwipeTouchListener(ShowCardActivity.this) {
Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question
As I have noticed this error occurs under two circumstances,
so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)
Hope this helps.
You could use input type image.
<input type="image" src="http://example.com/path/to/image.png" />
It works as a button and can have the event handlers attached to it.
Alternatively, you can use css to style your button with a background image, and set the borders, margins and the like appropriately.
<button style="background: url(myimage.png)" ... />
You can use escape sequences, if your terminal supports it. For example:
echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
You can use // instead of single /. That converts to int
directly.
This is one of the most easily found question on the topic, so I wanted to give a modern answer to the it (both for my reference and to help others out). By using first_value
and over
you can make short work of the above query:
Select distinct DocumentID
, first_value(status) over (partition by DocumentID order by DateCreated Desc) as Status
, first_value(DateCreated) over (partition by DocumentID order by DateCreated Desc) as DateCreated
From DocumentStatusLogs
This should work in Sql Server 2008 and up. First_value
can be thought of as a way to accomplish Select Top 1
when using an over
clause. Over
allows grouping in the select list so instead of writing nested subqueries (like many of the existing answers do), this does it in a more readable fashion. Hope this helps.
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesThe equals() method on your List implementation should do elementwise comparison, so
assertEquals(argumentComponents, returnedComponents);
is a lot easier.
In the mixins of the Bootstrap sources Sass files, remove all $border
references (not in the outline variant).
@mixin button-variant($color, $background, $border){
$active-background: darken($background, 10%);
//$active-border: darken($border, 12%);
color: $color;
background-color: $background;
//border-color: $border;
@include box-shadow($btn-box-shadow);
[...]
}
Or simply code you own _customButton.scss mixin.
For Visual Studio 2013/2015/2017 there is an extension that does exactly what you want: ResolveUR. What this basically does is:
I second that.
Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.
However, JDGUI generates .java files which have ,more often than not, errors.
It has got something to do with code obfuscation I guess.
Metrics and Svens answer deals with the usual situation but for us who work in non-english enviroments if you have exotic characters (å,ä,ö) in your character variable you will get the same result, even if you have multiple factor levels.
Levels <- c("Pri", "För")
gives the contrast error, while Levels <- c("Pri", "For")
doesn't
This is probably a bug.
Use the PHP built-in functionality of the appending the array operand to the desired variable name.
If we add values to a Javascript array as follows:
acitivies.push('Location Zero');
acitivies.push('Location One');
acitivies.push('Location Two');
It can be sent to the server as follows:
$.ajax({
type: 'POST',
url: 'tourFinderFunctions.php',
'activities[]': activities
success: function() {
$('#lengthQuestion').fadeOut('slow');
}
});
Notice the quotes around activities[]. The values will be available as follows:
$_POST['activities'][0] == 'Location Zero';
$_POST['activities'][1] == 'Location One';
$_POST['activities'][2] == 'Location Two';
$sql="DELETE FROM basic_tbl
,education_tbl
,
personal_tbl
,address_tbl
,department_tbl
USING
basic_tbl
,education_tbl
,
personal_tbl
,address_tbl
,department_tbl
WHERE
b_id
=e_id
=p_id
=a_id
=d_id
='".$id."'
";
$rs=mysqli_query($con,$sql);
In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.
<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding ColorSet}"/>
</Style>
</DataGrid.RowStyle>
And in my Employee Class
public class Employee {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string ColorSet { get; set; }
public Employee() { }
public Employee(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
if (Age > 50)
{
ColorSet = "Green";
}
else if (Age > 100)
{
ColorSet = "Red";
}
else
{
ColorSet = "White";
}
}
}
This way every Row of the DataGrid has the BackGround Color of the ColorSet
Property of my Object.
If this is for a Windows Runtime application, then you have to add the self-signed certificate to the project and reference it in the appxmanifest.
The docs are here: http://msdn.microsoft.com/en-us/library/windows/apps/hh465031.aspx
Same thing if it's from a CA that's not trusted (like a private CA that the machine itself doesn't trust) -- you need to get the CA's public cert, add it as content to the app then add it to the manifest.
Once that's done, the app will see it as a correctly signed cert.
use like this.....
Create file
#import <Foundation/Foundation.h>`
#import "SharedManager.h"
#import "Constant.h"
#import "UserDetails.h"
@interface APISession : NSURLSession<NSURLSessionDelegate>
@property (nonatomic, retain) NSMutableData *responseData;
+(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString*
)strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
@end
****************.m*************************
#import "APISession.h"
#import <UIKit/UIKit.h>
@implementation APISession
+(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString
*)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
{
NSURL *url=[NSURL URLWithString:strAPIURL];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *err = nil;
NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
[request setHTTPBody:data];
NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"API URL: %@ \t Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
// NSLog(@"Request data===%@",objDic);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
// NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (error==nil) {
NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
NSLog(@"Response Data=============%@",dicData);
if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
{
NSLog(@"hello");
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
}
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(dicData,(error == nil));
});
NSLog(@"%@",dicData);
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(error.localizedDescription,NO);
});
}
}];
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[task resume];
// });
}
@end
*****************************in .your view controller***********
#import "file"
txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
{
[SVProgressHUD showWithStatus:@"Loading..."];
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
[objLoginDic setValue:txtEmail.text forKey:@"email"];
[objLoginDic setValue:@0 forKey:kDeviceType];
[objLoginDic setValue:txtPassword.text forKey:kPassword];
[objLoginDic setValue:@"376545432" forKey:kDeviceTokan];
[objLoginDic setValue:@"" forKey:kcountryId];
[objLoginDic setValue:@"" forKey:kfbAccessToken];
[objLoginDic setValue:@0 forKey:kloginType];
[APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) {
[SVProgressHUD dismiss];
NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
NSString *strMessage=[result valueForKey:KMessage];
if (status) {
if (statusResponse == 1)
{
UserDetails *objLoginUserDetail=[[UserDetails alloc]
initWithObject:[result valueForKey:@"userDetails"]];
[[NSUserDefaults standardUserDefaults]
setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self clearTextfeilds];
HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
[self.navigationController pushViewController:obj animated:YES];
}
else{
[strMessage showAsAlert:self];
}
}
}];
}
**********use model class for represnt data*************
#import <Foundation/Foundation.h>
#import "Constant.h"
#import <objc/runtime.h>
@interface UserDetails : NSObject
@property(strong,nonatomic) NSString *emailId,
*deviceToken,
*countryId,
*fbAccessToken,
*accessToken,
*countryName,
*isProfileSetup,
*profilePic,
*firstName,
*lastName,
*password;
@property (assign) NSInteger userId,deviceType,loginType;
-(id)initWithObject :(NSDictionary *)dicUserData;
-(void)saveLoginUserDetail;
+(UserDetails *)getLoginUserDetail;
-(UserDetails *)getEmptyModel;
- (NSArray *)allPropertyNames;
-(void)printDescription;
-(NSMutableDictionary *)getDictionary;
@end
******************model.m*************
#import "UserDetails.h"
#import "SharedManager.h"
@implementation UserDetails
-(id)initWithObject :(NSDictionary *)dicUserData
{
self = [[UserDetails alloc] init];
if (self)
{
@try {
[self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])?
[dicUserData valueForKey:@"firstName"]:@""];
[self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])?
[[dicUserData valueForKey:kUserId] integerValue]:0];
}
@catch (NSException *exception) {
NSLog(@"Exception: %@",exception.description);
}
@finally {
}
}
return self;
}
-(UserDetails *)getEmptyModel{
[self setFirstName:@""];
[self setLastName:@""];
[self setDeviceType:0];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
// Encode properties, other class variables, etc
[encoder encodeObject:_firstName forKey:kFirstName];
[encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
_firstName = [decoder decodeObjectForKey:kEmailId];
_deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];
}
return self;
}
- (NSArray *)allPropertyNames
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
-(void)printDescription{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(NSString *key in [self allPropertyNames])
{
[dic setValue:[self valueForKey:key] forKey:key];
}
NSLog(@"\n========================= User Detail ==============================\n");
NSLog(@"%@",[dic description]);
NSLog(@"\n=============================================================\n");
}
-(NSMutableDictionary *)getDictionary{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(NSString *key in [self allPropertyNames])
{
[dic setValue:[self valueForKey:key] forKey:key];
}
return dic;
}
#pragma mark
#pragma mark - Save and get User details
-(void)saveLoginUserDetail{
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
[Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
[Shared_UserDefault synchronize];
}
+(UserDetails *)getLoginUserDetail{
NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
************************usefull code while add data into model and get data********
NSLog(@"Response %@",result);
NSString *strMessg = [result objectForKey:kMessage];
NSString *status = [NSString stringWithFormat:@"%@",[result
objectForKey:kStatus]];
if([status isEqualToString:@"1"])
{
arryBankList =[[NSMutableArray alloc]init];
NSMutableArray *arrEvents=[result valueForKey:kbankList];
ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
if ([arrEvents count]>0)
{
for (NSMutableArray *dic in arrEvents)
{
BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic
mutableCopy]];
[arryBankList addObject:objBankListDetail];
}
//display data using model...
BankList *objBankListing =[arryBankList objectAtIndex:indexPath.row];
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
Here is another example, for compiling a java file in a nested directory.
I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.
Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'
% mkdir -p temp/classes
% curl --get \
http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
--output commons-collections-3.2.2.jar
% javac -g -classpath commons-collections-3.2.2.jar \
-sourcepath src/main/java -d temp/classes \
src/main/java/org/gradle/Person.java
% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class
z-index only works within a particular context i.e. relative
, fixed
or absolute
position.
z-index for a relative div has nothing to do with the z-index
of an absolutely or fixed div.
EDIT This is an incomplete answer. This answer provides false information. Please review @Dansingerman's comment and example below.
I'm doing it with NERDTree plugin:
:NERDTreeFind
then press m
To rename you can choose (m)ove the current node
and change file name. Also there are options like delete, copy, move, etc...
Late to the party, but I was trying to get this done in TypeScript and came up with this:
<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}
This prints the exact key pressed to the screen. So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").
I stumbled upon an interesting reason for a gigantic .xlsx file. Original workbook had 20 sheets or so, was 20 MB I made a new workbook with 1 of the sheets, so it would be more manageable: still 11.5 MB Imagine my surprise to find that the single sheet in the new workbook had 1,041,776 (count 'em!) blank rows. Now it's 13.5 KB
As a summary
import sys
import re
f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
s=myfile.read()
ret = re.sub(find,replace, s) # <<< This is where the magic happens
print ret
You can encode it in PHP :)
<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>">
Or display in our dynamic CSS.php file:
background: url("data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>");
1 That’s sort of a “quick-n-dirty” technique but it works. Here is another encoding method using fopen() instead of file_get_contents():
<?php // convert image to dataURL
$img_source = "feed-icon.gif"; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
?>
su - root
Goto /etc/ssh/sshd_config
vi sshd_config
PermitRootLogin yes
PermitEmptyPasswords no
PasswordAuthentication yes
:x!
Then restart ssh service
root@cloudera2:/etc/ssh# service ssh restart
ssh stop/waiting
ssh start/running, process 10978
Now goto sudoers files (/etc/sudoers).
root ALL=(ALL)NOPASSWD:ALL
yourinstanceuser ALL=(ALL)NOPASSWD:ALL / This is the user by which you are launching instance.
How about using csplit?
man csplit
csplit -k file 1 '{1}'
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
It is this line button2.Enabled == true
, it should be button2.Enabled = true
. You are doing comparison when you should be doing assignment.
Use PHP_EOL
which outputs \r\n
or \n
depending on the OS.
@thebluefox has summarized the most of all. You're only also forced to use JavaScript to make that button to work anyway. Here's an SSCCE, you can copy'n'paste'n'run it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').click(function() {
$(this).prev('input').val('').trigger('change').focus();
}));
});
</script>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="text" class="deletable">
</body>
</html>
_x000D_
jQuery is by the way not necessary, it just nicely separates the logic needed for progressive enhancement from the source, you can of course also go ahead with plain HTML/CSS/JS:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2803532, with "plain" HTML/CSS/JS</title>
<style>
span.deleteicon {
position: relative;
}
span.deleteicon span {
position: absolute;
display: block;
top: 5px;
right: 0px;
width: 16px;
height: 16px;
background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
cursor: pointer;
}
span.deleteicon input {
padding-right: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<span class="deleteicon">
<input type="text">
<span onclick="var input = this.previousSibling; input.value = ''; input.focus();"></span>
</span>
</body>
</html>
_x000D_
You only ends up with uglier HTML (and non-crossbrowser compatible JS ;) ).
Note that when the UI look'n'feel isn't your biggest concern, but the functionality is, then just use <input type="search">
instead of <input type="text">
. It'll show the (browser-specific) clear button on HTML5 capable browsers.
The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.
There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:
C:\Documents and Settings\LocalService\Local Settings\Application Data\
folder.I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.
None of this answers was working for me (Nuget 2.8.6) because of missing some tips, will try to add them here as it might be useful for others.
After reading the following sources:
https://docs.nuget.org/consume/NuGet-Config-Settings
https://github.com/NuGet/Home/issues/1346
It appears that
E.g.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<config>
<add key="repositorypath" value="$/../../../Common/packages" />
</config>
</configuration>
You can also use NuGet command to ensure that syntax will be correct like this:
NuGet.exe config -Set repositoryPath=$/../../../Common/packages -ConfigFile NuGet.Config
You can achieve this with the following code:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
public class MainClass {
public static void main(String args[]) {
System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
System.out.printf("Default floating-point format: %f\n", 1234567.123);
System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);
System.out.printf("Line-up positive and negative values:\n");
System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
}
}
And print out:
3 (3) +3 00003
Default floating-point format: 1234567,123000
Floating-point with commas: 1.234.567,123000
Negative floating-point default: -1.234.567,123000
Negative floating-point option: (1.234.567,123000)Line-up positive and negative values:
1.234.567,12
-1.234.567,12
The code helped me to fulfill my requirement.
I have made some modifications and using a form I completed this. Here is my code-
Need a 'target' attribute for 'form' -- that's it!
Form
<form id="view_form" name="view_form" method="post" action="view_report.php" target="Map" >
<input type="text" value="<?php echo $sale->myvalue1; ?>" name="my_value1"/>
<input type="text" value="<?php echo $sale->myvalue2; ?>" name="my_value2"/>
<input type="button" id="download" name="download" value="View report" onclick="view_my_report();" />
</form>
JavaScript
function view_my_report() {
var mapForm = document.getElementById("view_form");
map=window.open("","Map","status=0,title=0,height=600,width=800,scrollbars=1");
if (map) {
mapForm.submit();
} else {
alert('You must allow popups for this map to work.');
}
}
Full code is explained showing normal form and form elements.
I use
patch -p1 --merge < patchfile
This way, conflicts may be resolved as usual.
The best practice is to check the Identity.IsAuthenticated
Property first and then get the usr.UserName
like this:
string userName = string.Empty;
if (System.Web.HttpContext.Current != null &&
System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
System.Web.Security.MembershipUser usr = Membership.GetUser();
if (usr != null)
{
userName = usr.UserName;
}
}
Rather simple:
Key = i.ToString("D2");
D
stands for "decimal number", 2
for the number of digits to print.
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
The new
operator is allocating space for a block of n
integers and assigning the memory address of that block to the int*
variable array
.
The general form of new as it applies to one-dimensional arrays appears as follows:
array_var = new Type[desired_size];
You should use input type="button" instead of input type="submit".
<form>
<input type="button" value="Remove DUMMY" onclick="removeDummy(); "/>
</form>
Checkout Mozilla Developer Center for basic html and javascript resources
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I know angular has hierarchical injectors like Thierry said.
But I have another option here in case you find a use-case where you don't really want to inject it at the parent.
We can achieve that by creating an instance of the service, and on provide always return that.
import { provide, Injectable } from '@angular/core';
import { Http } from '@angular/core'; //Dummy example of dependencies
@Injectable()
export class YourService {
private static instance: YourService = null;
// Return the instance of the service
public static getInstance(http: Http): YourService {
if (YourService.instance === null) {
YourService.instance = new YourService(http);
}
return YourService.instance;
}
constructor(private http: Http) {}
}
export const YOUR_SERVICE_PROVIDER = [
provide(YourService, {
deps: [Http],
useFactory: (http: Http): YourService => {
return YourService.getInstance(http);
}
})
];
And then on your component you use your custom provide method.
@Component({
providers: [YOUR_SERVICE_PROVIDER]
})
And you should have a singleton service without depending on the hierarchical injectors.
I'm not saying this is a better way, is just in case someone has a problem where hierarchical injectors aren't possible.
To print the struct as JSON:
fmt.Printf("%#v\n", yourProject)
Also possible with (as it was mentioned above):
fmt.Printf("%+v\n", yourProject)
But the second option prints string values without "" so it is harder to read.
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
Add the repository and update apt-get:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
Install Java8 and set it as default:
sudo apt-get install oracle-java8-set-default
Check version:
java -version
Single quotes are denoting a char, double denote a string.
In Java, it is also the same.
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.
For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.
Here is something practical: Yahoo JSON
If you're just doing this in either SQL Server Management Studio or sqlcmd.exe
, you can use the fact that the batch separator allows you to repeat the batch:
CREATE TABLE Number (N INT IDENTITY(1,1) PRIMARY KEY NOT NULL);
GO
INSERT INTO Number DEFAULT VALUES;
GO 100000
This will insert 100000 records into the Numbers
table using the default value of the next identity.
It's slow. It compares to METHOD 1 in @KM.'s answer, which is the slowest of the examples. However, it's about as code light as it gets. You could speed it up somewhat by adding the primary key constraint after the insert batch.
It seems that Facebook Page Plugin doesn't change at all in past 5-7 years :) It wasn't responsive from the begining and still not now, even new param Adapt to plugin container width
doesn't work or I don't understand how it works.
I'm searching for the most posible simple way to do PLUGIN SIZE 100% WIDTH
, and it seems it is not posible. Nonsense at it's best. How designers solve this problem?
I found the best decision for this time 2017 Oct:
.fb-page, .fb-page iframe[style], .fb-page span {
width: 100% !important;
}
.fb-comments, .fb-comments iframe[style], .fb-comments span {
width: 100% !important;
}
This lets do not broke screen size width for responsive screens, but still looks ugly, because cuted in some time and doesn't stretch... Facebook doesn't care about plugins design at all. That's the truth.
You can't use findViewById()
on menu items in onCreate()
because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu()
and then use it in your onClick()
.
private Menu menu;
In your onCreateOptionsMenu()
this.menu = menu;
In your button's onClick()
method
menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
Look at the jQuery unload function. It handles all the things.
https://api.jquery.com/unload/
The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
$(window).unload(
function(event) {
alert("navigating");
}
);
The HTML code:
<input type="radio" name="theName" value="1" id="option-1">
<input type="radio" name="theName" value="2">
<input type="radio" name="theName" value="3">
The Javascript code:
$(document).ready(function(){
$('input[name="theName"]').change(function(){
if($('#option-1').prop('checked')){
alert('Option 1 is checked!');
}else{
alert('Option 1 is unchecked!');
}
});
});
In multiple radio with name "theName", detect when option 1 is checked or unchecked. Works in all situations: on click control, use the keyboard, use joystick, automatic change the values from other dinamicaly function, etc.
use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.
ecatmur's solution will work fine. This will be better performance on large datasets, though:
data.groupby(data['date'].map(lambda x: x.year))
Consider a solution that will neatly handle arbitrarily many tables.
//ASSUMPTION: All tables must have the same columns
var tables = new List<DataTable>();
tables.Add(oneTableToRuleThemAll);
tables.Add(oneTableToFindThem);
tables.Add(oneTableToBringThemAll);
tables.Add(andInTheDarknessBindThem);
//Or in the real world, you might be getting a collection of tables from some abstracted data source.
//behold, a table too great and terrible to imagine
var theOneTable = tables.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
Encapsulated into a helper for future reuse:
public static DataTable CombineDataTables(params DataTable[] args)
{
return args.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
}
Just have a few tables declared in code?
var combined = CombineDataTables(dt1,dt2,dt3);
Want to combine into one of the existing tables instead of creating a new one?
dt1 = CombineDataTables(dt1,dt2,dt3);
Already have a collection of tables, instead of declared one by one?
//Pretend variable tables already exists
var tables = new[] { dt1, dt2, dt3 };
var combined = CombineDataTables(tables);
Based on Lance Larsen answer - here's an extension method with the recommended string.Compare instead of string.Equals
It is highly recommended that you use an overload of String.Compare that takes a StringComparison parameter. Not only do these overloads allow you to define the exact comparison behavior you intended, using them will also make your code more readable for other developers. [Josh Free @ BCL Team Blog]
public static bool Contains(this List<string> source, string toCheck, StringComparison comp)
{
return
source != null &&
!string.IsNullOrEmpty(toCheck) &&
source.Any(x => string.Compare(x, toCheck, comp) == 0);
}
Not since Lollipop. Starting with Android 5.0, the guidelines say:
Notification icons must be entirely white.
Even if they're not, the system will only consider the alpha channel of your icon, rendering them white
The only way to have a coloured icon on Lollipop is to lower your targetSdkVersion
to values <21
, but I think you would do better to follow the guidelines and use white icons only.
If you still however decide you want colored icons, you could use the DrawableCompat.setTint method from the new v4 support library.
The reason why the StaleElementReferenceException
occurs has been laid out already: updates to the DOM between finding and doing something with the element.
For the click-Problem I've recently used a solution like this:
public void clickOn(By locator, WebDriver driver, int timeout)
{
final WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(locator)));
driver.findElement(locator).click();
}
The crucial part is the "chaining" of Selenium's own ExpectedConditions
via the ExpectedConditions.refreshed()
. This actually waits and checks if the element in question has been refreshed during the specified timeout and additionally waits for the element to become clickable.
Have a look at the documentation for the refreshed method.
Use the 'And' keyword for a logical and. Like this:
If Not ((filename = testFileName) And (fileName <> "")) Then
Just remove gesture recognizer from NavigationController. Work in iOS 8.
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
[self.navigationController.view removeGestureRecognizer:self.navigationController.interactivePopGestureRecognizer];
Does the form you are trying to emulate have two fields, username and password?
If so, this line:
postData.Add("username", "password");
is not correct.
you would need two lines like:
postData.Add("username", "Moose");
postData.Add("password", "NotMoosespasswordreally");
Edit:
Okay, since that is not the problem, one way to tackle this is to use something like Fiddler or Wireshark to watch what is being sent to the web server from the browser successfully, then compare that to what is being sent from your code. If you are going to a normal port 80 from .Net, Fiddler will still capture this traffic.
There is probably some other hidden field on the form that the web server is expecting that you are not sending.
If your web-server correctly redirects you to a new page after you made a post, the regular "back" button on the browser will work. Or the "history.go(-1)" in javascript. This will produce a filled out form.
However, if the server just returns new content without redirecting - then history.go(-1) is not going to help you. At that point you have lost your form.
If you just want to simply go back to the previous url - just link to it with an A HREF tag. That will show you an empty form.
An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).
A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.
Some reasons you might want to use a setup.exe: