This can also happen (for cross-origin requests only) because of a new feature called site isolation
This page details the issue and a work-around. Which is to go to chrome://flags/#site-isolation-trial-opt-out
in chrome and change that setting to "Opt-out" and reload chrome.
It's a known issue. However that page says it's fixed in chrome 68, but I'm running chrome 68 and I still have the issue.
List<int> first_list = new List<int>() {
1,
12,
12,
5
};
List<int> second_list = new List<int>() {
12,
5,
7,
9,
1
};
var result = first_list.Union(second_list);
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143
Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html
You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j
I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/
Regards,
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
I second Jon Skeet's answer and want to add the following links for everyone who want to know more about "volatile" and Interlocked:
Atomicity, volatility and immutability are different, part two
Atomicity, volatility and immutability are different, part three
Sayonara Volatile - (Wayback Machine snapshot of Joe Duffy's Weblog as it appeared in 2012)
With regard to Peter Lawrey's note that you don't need instanceof for final classes and can just use a reference equality, be careful! Even though the final classes cannot be extended, they are not guaranteed to be loaded by the same classloader. Only use x.getClass() == SomeFinal.class or its ilk if you are absolutely positive that there is only one classloader in play for that section of code.
I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:
begin
merge into some_table st
using (select 'some' name, 'values' value from dual) v
on (st.name=v.name)
when matched then update set st.value=v.value
when not matched then insert (name, value) values (v.name, v.value);
end;
(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).
The answers to your two questions are related. I'll start with the second:
Once you have staged a file (often with git add
, though some other commands implicitly stage the changes as well, like git rm
) you can back out that change with git reset -- <file>
.
In your case you must have used git rm
to remove the file, which is equivalent to simply removing it with rm
and then staging that change. If you first unstage it with git reset -- <file>
you can then recover it with git checkout -- <file>
.
#include?
should work, it works for general objects, not only strings. Your problem in example code is this test:
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
(even assuming using #include?
). You try to search for specific object, not for id. So it should be like this:
unless @suggested_horses.include?(horse)
@suggested_horses << horse
end
ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id
Just make sure it is executable, using chmod +x
. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh
- or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh
, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh
.
You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:
alias script.sh='sh script.sh'
Which would allow you to use just simply script.sh
(literally - this won't work for any other *.sh
file) instead of sh script.sh
.
That means you must install simplejson
. On newer versions of python, it was included by default into python's distribution, and renamed to json
. So if you are on python 2.6+ you should change all instances of simplejson
to json
.
For a quick fix you could also edit the file and change the line:
import simplejson
to:
import json as simplejson
and hopefully things will work.
The answer is good, but for the people that want this with range()
, the form to do is:
range(end)
:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start,end)
:
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(start,end, step)
:
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
These are applicable to MacOS Sierra 10.12.5 (16F73) and probably some other recent and upcoming versions of MacOS.
chsh
is not enough to change the default shell. Make sure you press Command+, while your terminal is open and change the 'Shells open with' option to 'Default login shell.'
In case of bash, make sure that you execute echo $BASH_VERSION
to confirm you are running the intended version of bash. bash --version
does not give you correct information.
I was trying to publish my own package and then include it in another project. I had that issue because of how I've built the first module. Im using ES2015 export to create the module, e.g lets say the module looks like that:
export default function(who = 'world'){
return `Hello ${who}`;
}
After compiled with Babel and before been published:
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
var who = arguments.length <= 0 || arguments[0] === undefined ? 'world' : arguments[0];
return 'Hello ' + who;
};
So after npm install module-name
in another project (none ES2015) i had to do
var hello = require('module-name').default;
To actually got the package imported.
Hope that helps!
find location -ctime time_period
Examples of time_period:
More than 30 days ago: -ctime +30
Less than 30 days ago: -ctime -30
Exactly 30 days ago: -ctime 30
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/
It is worth noting that sometimes you do want non-configurable "hard-coded" numbers in your code. There are a number of famous ones including 0x5F3759DF which is used in the optimized inverse square root algorithm.
In the rare cases where I find the need to use such Magic Numbers, I set them as a const in my code, and document why they are used, how they work, and where they came from.
I am looking for this kind of solution for my self as well. I found reference in terms aggregation.
So, according to that following is the proper solution.
{
"aggs" : {
"langs" : {
"terms" : { "field" : "language",
"size" : 500 }
}
}}
But if you ran into following error:
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
}
]}
In that case, you have to add "KEYWORD" in the request, like following:
{
"aggs" : {
"langs" : {
"terms" : { "field" : "language.keyword",
"size" : 500 }
}
}}
For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
you can also add below code in AndroidManifest.xml.
android:icon="@android:color/transparent"
It will work fine.
But I found that this gives a problem as the launcher icon also become transparent.
So I used:
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
and it worked fine.
But if you are having more than one activity and want to make the icon on an activity transparent then the previous approach will work.
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Maybe a fixed height
and overflow-y: scroll;
Srsly guys... Why so many lines of code for a simple method like this? Here's my solution:
def isPrime(a):
div = a - 1
res = True
while(div > 1):
if a % div == 0:
res = False
div = div - 1
return res
Simple solution on my server: After migrating to a new Debian 7 server with my MySQL databases, the second local IP address, 127.0.1.1
, was missing in my hosts file. Adding this resolved the warnings:
echo -e "\n127.0.1.1 $(hostname)" >> /etc/hosts
You would have to open a new window(or navigate to a new page) containing just the information you wish the user to be able to print
Javscript:
function printInfo(ele) {
var openWindow = window.open("", "title", "attributes");
openWindow.document.write(ele.previousSibling.innerHTML);
openWindow.document.close();
openWindow.focus();
openWindow.print();
openWindow.close();
}
HTML:
<div id="....">
<div>
content to print
</div><a href="#" onclick="printInfo(this)">Print</a>
</div>
A few notes here: the anchor must NOT have whitespace between it and the div containing the content to print
select this_.code from true.employee this_ where this_.code=?
is what will be sent to your database.
this_
is an alias for that instance of the employee
table.
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
You can try cactoos for that.
final InputStream input = new InputStreamOf("example");
The object is created with new
and not a static method for a reason.
Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
single/double quotes
and backslash
everywhere:
$ python -c 'exec("import sys\nfor i in range(10): print \"bob\"")'
Much better:
$ python -c '
> import sys
> for i in range(10):
> print "bob"
> '
@System.Configuration.ConfigurationManager.AppSettings["myKey"]
Facebook seemingly randomly disables the ability to set localhost as a domain on your facebook app. I found the easiest work around was to tunnel my localhost to the web. This can be done for free using http://progrium.com/localtunnel/ or with a custom url (easier since you don't have to change url everytime in facebook) https://showoff.io
If possible - use visibility
instead of display
For instance:
.child {
visibility: hidden;
opacity: 0;
transition: opacity 0.3s, visibility 0.3s;
}
.parent:hover .child {
visibility: visible;
opacity: 1;
transition: opacity 0.3s, visibility 0.3s;
}
If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".
You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output
Another solution, you can solve your problem using replaceAll
with some regex ^.{1}
(regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
You can create a character array which includes all the letters and numbers, and then you can randomly select from this character array and create your own string password.
char[] chars = new char[62]; // Sum of letters and numbers
int i = 0;
for(char c = 'a'; c <= 'z'; c++) { // For letters
chars[i++] = c;
}
for(char c = '0'; c <= '9';c++) { // For numbers
chars[i++] = c;
}
for(char c = 'A'; c <= 'Z';c++) { // For capital letters
chars[i++] = c;
}
int numberOfCodes = 0;
String code = "";
while (numberOfCodes < 1) { // Enter how much you want to generate at one time
int numChars = 8; // Enter how many digits you want in your password
for(i = 0; i < numChars; i++) {
char c = chars[(int)(Math.random() * chars.length)];
code = code + c;
}
System.out.println("Code is:" + code);
}
for the sake of completeness, you could use:
(DT_STR,8, 1252) (YEAR(GetDate()) * 10000 + MONTH(GetDate()) * 100 + DAY(GetDate()))
for YYYYMMDD or
RIGHT("000000" + (DT_STR,8, 1252) (DAY(GetDate()) * 1000000 + MONTH(GetDate()) * 10000 + YEAR(GetDate())), 8)
for DDMMYYYY (without hyphens). If you want / need the date as integer (e.g. for _key-columns in DWHs), just remove the DT_STR / RIGTH function and do just the math.
The problem with iPhone camera is that the first models (of which there are tons in use) have a fixed-focus camera that cannot take picture in-focus for distances under 2ft. The images are blurry and distorted and if taken from greater distance there is not enough detail/information from the barcode.
A few companies have developed iPhone apps that can accomodate for that by using advanced de-blurring technologies. Those applications you can find on Apple app store: pic2shop, RedLaser and ShopSavvy. All of the companies have announced that they have also SDKs available - some for free or very preferential terms, check that one out.
I have noticed that no answer display an image with a single legend referencing many curves in different subplots, so I have to show you one... to make you curious...
Now, you want to look at the code, don't you?
from numpy import linspace
import matplotlib.pyplot as plt
# Calling the axes.prop_cycle returns an itertoools.cycle
color_cycle = plt.rcParams['axes.prop_cycle']()
# I need some curves to plot
x = linspace(0, 1, 51)
f1 = x*(1-x) ; lab1 = 'x - x x'
f2 = 0.25-f1 ; lab2 = '1/4 - x + x x'
f3 = x*x*(1-x) ; lab3 = 'x x - x x x'
f4 = 0.25-f3 ; lab4 = '1/4 - x x + x x x'
# let's plot our curves (note the use of color cycle, otherwise the curves colors in
# the two subplots will be repeated and a single legend becomes difficult to read)
fig, (a13, a24) = plt.subplots(2)
a13.plot(x, f1, label=lab1, **next(color_cycle))
a13.plot(x, f3, label=lab3, **next(color_cycle))
a24.plot(x, f2, label=lab2, **next(color_cycle))
a24.plot(x, f4, label=lab4, **next(color_cycle))
# so far so good, now the trick
lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
# finally we invoke the legend (that you probably would like to customize...)
fig.legend(lines, labels)
plt.show()
The two lines
lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
deserve an explanation — to this aim I have encapsulated the tricky part in a function, just 4 lines of code but heavily commented
def fig_legend(fig, **kwdargs):
# generate a sequence of tuples, each contains
# - a list of handles (lohand) and
# - a list of labels (lolbl)
tuples_lohand_lolbl = (ax.get_legend_handles_labels() for ax in fig.axes)
# e.g. a figure with two axes, ax0 with two curves, ax1 with one curve
# yields: ([ax0h0, ax0h1], [ax0l0, ax0l1]) and ([ax1h0], [ax1l0])
# legend needs a list of handles and a list of labels,
# so our first step is to transpose our data,
# generating two tuples of lists of homogeneous stuff(tolohs), i.e
# we yield ([ax0h0, ax0h1], [ax1h0]) and ([ax0l0, ax0l1], [ax1l0])
tolohs = zip(*tuples_lohand_lolbl)
# finally we need to concatenate the individual lists in the two
# lists of lists: [ax0h0, ax0h1, ax1h0] and [ax0l0, ax0l1, ax1l0]
# a possible solution is to sum the sublists - we use unpacking
handles, labels = (sum(list_of_lists, []) for list_of_lists in tolohs)
# call fig.legend with the keyword arguments, return the legend object
return fig.legend(handles, labels, **kwdargs)
PS I recognize that sum(list_of_lists, [])
is a really inefficient method to flatten a list of lists but ? I love its compactness, ? usually is a few curves in a few subplots and ? Matplotlib and efficiency? ;-)
If you want to stick with the official Matplotlib API my answer above is perfect, really.
On the other hand, if you don't mind using a private method of the matplotlib.legend
module ... it's really much much much easier
from matplotlib.legend import _get_legend_handles_labels
...
fig.legend(*_get_legend_handles_and_labels(fig.axes), ...)
A complete explanation can be found in the source code of Axes.get_legend_handles_labels
in .../matplotlib/axes/_axes.py
Iam confused a lot from morning whether it should be less than or greater than`
this can accept value less than "99999"
I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:
}elseif($("#seats").val() < 99999){
alert("Not a valid Number");
}else{
You are saying if it's less than 99999, then it's not valid. You want to do the opposite:
}elseif($("#seats").val() >= 99999){
alert("Not a valid Number");
}else{
Also, since you have $("#seats")
twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:
var seats = $("#seats").val();
var error = null;
if (seats == "") {
error = "Number is required";
} else {
var seatsNum = parseInt(seats);
if (isNaN(seatsNum)) {
error = "Not a valid number";
} else if (seatsNum >= 99999) {
error = "Number must be less than 99999";
}
}
if (error != null) {
alert(error);
} else {
alert("Valid number");
}
// If you really need setflag:
var setflag = error != null;
Here's a working sample: http://jsfiddle.net/LUY8q/
I wouldn't recommend doing this, but you can override the ngClick
directive to do what you are looking for. That's not saying, you should.
With the original implementation in mind:
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
We can do this to override it:
// Go into your config block and inject $provide.
app.config(function ($provide) {
// Decorate the ngClick directive.
$provide.decorator('ngClickDirective', function ($delegate) {
// Grab the actual directive from the returned $delegate array.
var directive = $delegate[0];
// Stow away the original compile function of the ngClick directive.
var origCompile = directive.compile;
// Overwrite the original compile function.
directive.compile = function (el, attrs) {
// Apply the original compile function.
origCompile.apply(this, arguments);
// Return a new link function with our custom behaviour.
return function (scope, el, attrs) {
// Get the name of the passed in function.
var fn = attrs.ngClick;
el.on('click', function (event) {
scope.$apply(function () {
// If no property on scope matches the passed in fn, return.
if (!scope[fn]) {
return;
}
// Throw an error if we misused the new ngClick directive.
if (typeof scope[fn] !== 'function') {
throw new Error('Property ' + fn + ' is not a function on ' + scope);
}
// Call the passed in function with the event.
scope[fn].call(null, event);
});
});
};
};
return $delegate;
});
});
Then you'd pass in your functions like this:
<div ng-click="func"></div>
as opposed to:
<div ng-click="func()"></div>
jsBin: http://jsbin.com/piwafeke/3/edit
Like I said, I would not recommend doing this but it's a proof of concept showing you that, yes - you can in fact overwrite/extend/augment the builtin angular behaviour to fit your needs. Without having to dig all that deep into the original implementation.
Do please use it with care, if you were to decide on going down this path (it's a lot of fun though).
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL()
method has been removed from the MediaStream
interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject
. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL()
to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
If you install using bundler as suggested by gryzzly and the gem creates a binary then make sure you run it with bundle exec mygembinary
as the gem is stored in a bundler directory which is not visible on the normal gem path.
For commenting blocks of code, I like the NERD Commenter plugin.
Select some text:
Shift-V
...select the lines of text you want to comment....
Comment:
,cc
Uncomment:
,cu
Or just toggle the comment state of a line or block:
,c<space>
$address = str_replace(" ", "+", $address);
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=$region");
$json = json_decode($json);
$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:
https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/
I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:
https://www.postgresql.org/docs/current/tsm-system-rows.html
CREATE EXTENSION tsm_system_rows;
Then you can grab whatever number of rows you want:
select * from playtime tablesample system_rows (15);
Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.
This will get you into the worksheet you want to work on.
If you just want to get your HDFS back to normal state and don't worry much about the data, then
This will list the corrupt HDFS blocks:
hdfs fsck -list-corruptfileblocks
This will delete the corrupted HDFS blocks:
hdfs fsck / -delete
Note that, you might have to use sudo -u hdfs
if you are not the sudo user (assuming "hdfs" is name of the sudo user)
If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.
var merge = _.merge(arr1, arr2);
Which is the short version of:
var merge = _.chain(arr1).zip(arr2).map(function(item) {
return _.merge.apply(null, item);
}).value();
Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.
var merge = _.map(arr1, function(item) {
return _.merge(item, _.find(arr2, { 'member' : item.member }));
});
You can easily convert this to a mixin. See the example below:
_.mixin({_x000D_
'mergeByKey' : function(arr1, arr2, key) {_x000D_
var criteria = {};_x000D_
criteria[key] = null;_x000D_
return _.map(arr1, function(item) {_x000D_
criteria[key] = item[key];_x000D_
return _.merge(item, _.find(arr2, criteria));_x000D_
});_x000D_
}_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"name": 'yyyyyyyyyy',_x000D_
"age": 26_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"name": 'xxxxxx',_x000D_
"age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
For one-dimensional sorted arrays, it would be much more simpler and efficient O(log(n)) to use numpy.searchsorted which returns a NumPy integer (position). For example,
arr = np.array([1, 1, 1, 2, 3, 3, 4])
i = np.searchsorted(arr, 3)
Just make sure the array is already sorted
Also check if returned index i actually contains the searched element, since searchsorted's main objective is to find indices where elements should be inserted to maintain order.
if arr[i] == 3:
print("present")
else:
print("not present")
You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "[email protected]";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("[email protected]", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
What suited my purpose was to create a div that was always bounded within the overall browser window by a fixed amount.
What worked, at least on firefox, was this
<div style="position: absolute; top: 127px; left: 75px;right: 75px; bottom: 50px;">
Insofar as the actual window is not forced into scrolling, the div preserves its boundaries to the window edge during all re-sizing.
Hope this saves someone some time.
Here is a concise summary of what most answers are talking about.
Let's say we have two variables and $1 is set to 'one':
set one two
a=hello
b=world
The table below explains the different contexts where we can combine the values of a
and b
to create a new variable, c
.
Context | Expression | Result (value of c)
--------------------------------------+-----------------------+---------------------
Two variables | c=$a$b | helloworld
A variable and a literal | c=${a}_world | hello_world
A variable and a literal | c=$1world | oneworld
A variable and a literal | c=$a/world | hello/world
A variable, a literal, with a space | c=${a}" world" | hello world
A more complex expression | c="${a}_one|${b}_2" | hello_one|world_2
Using += operator (Bash 3.1 or later) | c=$a; c+=$b | helloworld
Append literal with += | c=$a; c+=" world" | hello world
A few notes:
+=
is better from a performance standpoint if a big string is being constructed in small increments, especially in a loop{}
around variable names to disambiguate their expansion (as in row 2 in the table above). As seen on rows 3 and 4, there is no need for {}
unless a variable is being concatenated with a string that starts with a character that is a valid first character in shell variable name, that is alphabet or underscore.See also:
You can not specify the password from the command line but you can do either using ssh keys or using sshpass
as suggested by John C. or using a expect
script.
To use sshpass, you need to install it first. Then
sshpass -f <(printf '%s\n' your_password) ssh user@hostname
instead of using sshpass -p your_password
. As mentioned by Charles Duffy
in the comments, it is safer to supply the password from a file or from a variable instead of from command line.
BTW, a little explanation for the <(command)
syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe
simple add and div atribute to each meta tag example
<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />
now like normal div change for ex. n click
<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>
function change tags with jQuery
function changeTags(){
$("#mtlink").attr("content","http://albup.com");
$("#mtdesc").attr("content","music all the time");
$("#mtkwrds").attr("content","mp3, download music, ");
}
The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.
I got this error too even I ran cmd as an Administrator.
The root cause is: The file is from VCS(subversion, perforce, etc.), and when I checked the properties of this file, its' Attributes is Read-only.
So the solution is:
Perhaps a use might be:
#debug = []
def debuglog(text, obj=None):
" Simple little logger. "
try:
debug # does global exist?
except NameError:
pass # if not, don't even bother displaying
except:
print('Unknown cause. Debug debuglog().')
else:
# debug does exist.
# Now test if you want to log this debug message
# from caller "obj"
try:
if obj in debug:
print(text) # stdout
except TypeError:
print('The global "debug" flag should be an iterable.')
except:
print('Unknown cause. Debug debuglog().')
def myfunc():
debuglog('Made it to myfunc()', myfunc)
debug = [myfunc,]
myfunc()
Maybe this will lead you too a use.
Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x
isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError
exception.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
Here is assembly code:
7f0b024734be: 48 8d 14 f5 00 00 00 lea rdx,[rsi*8]
7f0b024734c5: 00
7f0b024734c6: 48 03 13 add rdx,QWORD PTR [rbx]
7f0b024734c9: 48 8d 7a 10 lea rdi,[rdx+16]
7f0b024734cd: 8b 5f 08 mov ebx,DWORD PTR [rdi+8]
7f0b024734d0: 89 d8 mov eax,ebx
7f0b024734d2: c1 f8 03 sar eax,0x3
7f0b024734d5: 85 db test ebx,ebx
7f0b024734d7: 0f 8e cb 05 00 00 jle 0x7f0b02473aa8
And what it does is:
rdx = 0x00007f0a808d4ed2 * 8; // equals 0x0003F854046A7690. WTF???
rdx = rdx + something from old gen heap; // results 0x000600007f090486
rdi = rdx + 16; // results 0x000600007f090496
ebx = something from edi address (0x000600007f090496) + 8
Well I've had a look at the address map and there is nothing mapped to 0x000600007f090496 which is why you are getting a SEGV. Are you getting the same error with 1.6.0_26 JVM? Can you try it on a 32bit JVM? Looks like a JVM issue to me. Why would it do the first rdx=0x0... * 8 thing?
You must use ToList()
method first to take rows from database and then select items as a class.
Try this:
public partial class Dog {
public string BreedName { get; set; }}
List<Dog> GetDogsWithBreedNames(){
var db = new DogDataContext(ConnectString);
var result = (from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
}).ToList()
.Select(x=>
new Dog{
Name = x.Name,
BreedName = x.BreedName,
}).ToList();
return result;}
So, the trick is first ToList()
. It is immediately makes the query and gets the data from database. Second trick is Selecting items and using object initializer to generate new objects with items loaded.
Hope this helps.
If your Object contains Objects then check if they are null, if it have primitives check for their default values.
for Instance:
Person Object
name Property with getter and setter
to check if name is not initialized.
Person p = new Person();
if(p.getName()!=null)
This is one way of doing it:
document.getElementById("mytext").value = "My value";
In his book, "Secrets of Javascript Ninja", John Resig (creator of jQuery) has a really simple code which will handle cross-browser console.log issues. He explains that he would like to have a log message which works with all browsers and here is how he coded it:
function log() {
try {
console.log.apply(console, arguments);
} catch(e) {
try {
opera.postError.apply(opera, arguments);
}
catch(e) {
alert(Array.prototype.join.call( arguments, " "));
}
}
NSString *message = @"Some message...";
UIAlertView *toast = [[UIAlertView alloc] initWithTitle:nil
message:message
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil, nil];
[toast show];
int duration = 1; // duration in seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[toast dismissWithClickedButtonIndex:0 animated:YES];
});
Using UIAlertViewController for iOS 9 or later
NSString *message = @"Some message...";
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
message:message
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
int duration = 1; // duration in seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[alert dismissViewControllerAnimated:YES completion:nil];
});
Swift 3.2
let message = "Some message..."
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
self.present(alert, animated: true)
// duration in seconds
let duration: Double = 5
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
alert.dismiss(animated: true)
}
Before apply .setBounds(..) try to convert current Drawable into ScaleDrawable
drawable = new ScaleDrawable(drawable, 0, width, height).getDrawable();
after that
drawable.setBounds(0, 0, width, height);
will work
There have been a lot of good answers around the use of crontab, but no mention of a simpler method, such as using cron
.
Using cron
would take advantage of system files and directories located at /etc/crontab
, /etc/cron.daily,weekly,hourly
or /etc/cron.d/
:
cat > /etc/cron.d/<job> << EOF
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root HOME=/
01 * * * * <user> <command>
EOF
In this above example, we created a file in /etc/cron.d/
, provided the environment variables for the command to execute successfully, and provided the user
for the command, and the command
itself. This file should not be executable and the name should only contain alpha-numeric and hyphens (more details below).
To give a thorough answer though, let's look at the differences between crontab
vs cron/crond
:
crontab -- maintain tables for driving cron for individual users
For those who want to run the job in the context of their user on the system, using crontab
may make perfect sense.
cron -- daemon to execute scheduled commands
For those who use configuration management or want to manage jobs for other users, in which case we should use cron
.
A quick excerpt from the manpages gives you a few examples of what to and not to do:
/etc/crontab and the files in /etc/cron.d must be owned by root, and must not be group- or other-writable. In contrast to the spool area, the files under /etc/cron.d or the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly may also be symlinks, provided that both the symlink and the file it points to are owned by root. The files under /etc/cron.d do not need to be executable, while the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly do, as they are run by run-parts (see run-parts(8) for more information).
Source: http://manpages.ubuntu.com/manpages/trusty/man8/cron.8.html
Managing crons in this manner is easier and more scalable from a system perspective, but will not always be the best solution.
Remember to add MatTableModule
in your app.module's imports
i.e.
import { MatTableModule } from '@angular/material/table'
@NgModule({
imports: [
// ...
MatTableModule
// ...
]
})
import { MatTableModule } from '@angular/material'
@NgModule({
imports: [
// ...
MatTableModule
// ...
]
})
Have you tried adding lines below to your web.xml
?
<context-param>
<param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
<param-value>true</param-value>
</context-param>
I found this to be very effective when I encountered this issue.
In my case, I was missing something really trivial.
<input value={state.myObject.inputValue} />
My state was the following when I was getting the warning:
state = {
myObject: undefined
}
By alternating my state to reference the input of my value, my issue was solved:
state = {
myObject: {
inputValue: ''
}
}
The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.
Example:
<div class="editor-field">
<%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
<%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>
Here's a more specific example:
I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).
I made the following model:
namespace DeleteMeQuestion.Models
{
public class QuizModel
{
public int ParentQuestionId { get; set; }
public int QuestionId { get; set; }
public string QuestionDisplayText { get; set; }
public List<Response> Responses { get; set; }
[Range(1,999, ErrorMessage = "Please choose a response.")]
public int SelectedResponse { get; set; }
}
public class Response
{
public int ResponseId { get; set; }
public int ChildQuestionId { get; set; }
public string ResponseDisplayText { get; set; }
}
}
There's a simple range validator in the model, just for fun. Next up, I made the following controller:
namespace DeleteMeQuestion.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
// TODO: get question to show based on method parameter
var model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(int? id, QuizModel model)
{
if (!ModelState.IsValid)
{
var freshModel = GetModel(id);
return View(freshModel);
}
// TODO: save selected answer in database
// TODO: get next question based on selected answer (hard coded to 999 for now)
var nextQuestionId = 999;
return RedirectToAction("Index", "Home", new {id = nextQuestionId});
}
private QuizModel GetModel(int? questionId)
{
// just a stub, in lieu of a database
var model = new QuizModel
{
QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
QuestionId = 1,
Responses = new List<Response>
{
new Response
{
ChildQuestionId = 2,
ResponseId = 1,
ResponseDisplayText = "Red"
},
new Response
{
ChildQuestionId = 3,
ResponseId = 2,
ResponseDisplayText = "Blue"
},
new Response
{
ChildQuestionId = 4,
ResponseId = 3,
ResponseDisplayText = "Green"
},
}
};
return model;
}
}
}
Finally, I made the following view that makes use of the model:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<h1><%: Model.QuestionDisplayText %></h1>
<div>
<ul>
<% foreach (var item in Model.Responses) { %>
<li>
<%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
<label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
</li>
<% } %>
</ul>
<%= Html.ValidationMessageFor(m => m.SelectedResponse) %>
</div>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.
This gives you the radio buttons with the same name attribute, but different ID attributes.
If you not want include other function like 'ReDimPreserve' could use temporal matrix for resizing. On based to your code:
Dim n As Integer, m As Integer, i as Long, j as Long
Dim arrTemporal() as Variant
n = 1
m = 0
Dim arrCity() As String
ReDim arrCity(n, m)
n = n + 1
m = m + 1
'VBA automatically adapts the size of the receiving matrix.
arrTemporal = arrCity
ReDim arrCity(n, m)
'Loop for assign values to arrCity
For i = 1 To UBound(arrTemporal , 1)
For j = 1 To UBound(arrTemporal , 2)
arrCity(i, j) = arrTemporal (i, j)
Next
Next
If you not declare of type VBA assume that is Variant.
Dim n as Integer, m As Integer
You can use
TF_FORCE_GPU_ALLOW_GROWTH=true
in your environment variables.
In tensorflow code:
bool GPUBFCAllocator::GetAllowGrowthValue(const GPUOptions& gpu_options) {
const char* force_allow_growth_string =
std::getenv("TF_FORCE_GPU_ALLOW_GROWTH");
if (force_allow_growth_string == nullptr) {
return gpu_options.allow_growth();
}
One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.
Assuming you can load your data directly into pandas
with pandas.read_csv
then the following code might be helpful for you.
import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"
As mentioned in the comments, you can also do the assignment to both columns in one shot:
df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'
Note that you'll need pandas
version 0.11 or newer to make use of loc
for overwrite assignment operations.
Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:
import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"
OpenSSH has been added to Windows as of autumn 2018, and is included in Windows 10 and Windows Server 2019.
So you can use it in command prompt or power shell like bellow.
C:\Users\Parsa>scp [email protected]:/etc/cassandra/cassandra.yaml F:\Temporary
[email protected]'s password:
cassandra.yaml 100% 66KB 71.3KB/s 00:00
C:\Users\Parsa>
(I know this question is pretty old now but this can be helpful for newcomers to this question)
break x if ((int)strcmp(y, "hello")) == 0
On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!
From my experience in React Native, you can also restart your CLI and this error goes away.
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...
Have your tried using the 'return' keyword?
def rps():
return True
From http://hc.apache.org/httpclient-3.x/sslguide.html:
Protocol.registerProtocol("https",
new Protocol("https", new MySSLSocketFactory(), 443));
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.whatever.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
Where MySSLSocketFactory example can be found here. It references a TrustManager
, which you can modify to trust everything (although you must consider this!)
use
$imageString = file_get_contents("http://example.com/image.jpg");
$save = file_put_contents('Image/saveto/image.jpg',$imageString);
You will always get warnings of blocked content in most browsers when trying to display non secure content on an https page. This is tricky if you want to embed stuff from other sites that aren't behind ssl. You can turn off the warnings or remove the blocking in your own browser but for other visitors it's a problem.
One way to do it is to load the content server side and save the images and other things to your server and display them from https.
You can also try using a service like embed.ly and get the content through them. They have support for getting the content behind https.
Script its left
and top
properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
Or do it as a function so you can attach it to an event like onmousedown
function placeDiv(x_pos, y_pos) {
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
}
Give a class for eg: scroll
to the textarea tag. And in the css add this property -
.scroll::-webkit-scrollbar {
display: none;
}
_x000D_
<textarea class='scroll'></textarea>
_x000D_
It worked for without missing the scroll part
I had this issue while 'watching' tests. When the tests were edited, the watch re-ran the tests, but they failed due to this very reason.
I fixed it by checking if the model exists then use it, else create it.
import mongoose from 'mongoose';
import user from './schemas/user';
export const User = mongoose.models.User || mongoose.model('User', user);
This can be done easily through Java8 using forEach and removeIf method.
Take two lists. Iterate from listA and compare elements inside listB
Write any condition inside removeIf method.
Hope this will help
listToCompareFrom.forEach(entity -> listToRemoveFrom.removeIf(x -> x.contains(entity)));
A question mark is a signifier for 'any type'. ?
alone means
Any type extending
Object
(includingObject
)
while your example above means
Any type extending or implementing
HasWord
(includingHasWord
ifHasWord
is a non-abstract class)
I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"
here is the sample
<connectionStrings>
<add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
</connectionStrings>
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
This way work for me with Eclipse in Android developer tool from Google -righ click - property - java build path - add external JAR
point to: android-support-v7-appcompat.jar in /sdk/extras/android/support/v7/appcompat/libs
Then
import android.support.v7.app.ActionBarActivity;
As others have pointed out, string is always nullable in C#. I suspect you are asking the question because you are not able to leave the middle name as null or blank? I suspect the problem is with your validation attributes, most likely the RegEx. I'm not able to fully parse RegEx in my head but I think your RegEx insists on the first character being present. I could be wrong - RegEx is hard. In any case, try commenting out your validation attributes and see if it works, then add them back in one at a time.
let mergeArray = arrA.filter(aItem => !arrB.find(bItem => aItem.name === bItem.name))
It's as simple as that:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
You can do funny things then like:
var isMac = isMacintosh();
var isPC = !isMacintosh();
Maybe a syntax error in your case, you may change the line to:
directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')
which give you the right following output:
C:\\Users\\Josh\\Desktop\\20130216
Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.
window.open('https://play.google.com/store/apps/details?id=com.drishya');
Collections.sort( new ArrayList( coll ) );
When CPU/math computing power is limited:
There are times (such as in my work) when computing power is scarce (e.g. no floating point processor, working with small microcontrollers) where some trig functions can take an exorbitant amount of CPU time (e.g. 3000+ clock cycles), so when I only need an approximation, especially if if the CPU must not be tied up for a long time, I use this to minimize CPU overhead:
/**------------------------------------------------------------------------
* \brief Great Circle distance approximation in km over short distances.
*
* Can be off by as much as 10%.
*
* approx_distance_in_mi = sqrt(x * x + y * y)
*
* where x = 69.1 * (lat2 - lat1)
* and y = 69.1 * (lon2 - lon1) * cos(lat1/57.3)
*//*----------------------------------------------------------------------*/
double ApproximateDisatanceBetweenTwoLatLonsInKm(
double lat1, double lon1,
double lat2, double lon2
) {
double ldRadians, ldCosR, x, y;
ldRadians = (lat1 / 57.3) * 0.017453292519943295769236907684886;
ldCosR = cos(ldRadians);
x = 69.1 * (lat2 - lat1);
y = 69.1 * (lon2 - lon1) * ldCosR;
return sqrt(x * x + y * y) * 1.609344; /* Converts mi to km. */
}
Credit goes to https://github.com/kristianmandrup/geo_vectors/blob/master/Distance%20calc%20notes.txt.
In addition to @dawg's great answer, the equivalent solution using walrus operator (Python >= 3.8):
with open(filename, 'rb') as f:
while buf := f.read(max_size):
process(buf)
One way to compare your local version before pushing it on the remote repo (kind of push in dry-run):
Use TortoiseGit:
Right click on the root folder project > TortoiseGit > Diff with previous version >
for Version 2 choose refs/remotes/origin/master
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
use
statusCode: {
404: function() {
alert('page not found');
}
}
-
$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},
400: function() {
alert('bad request');
}
}
});
Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView
method.
This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).
http://www.refulz.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
host www.refulz.com:8082
hostname www.refulz.com
port 8082
protocol http:
pathname index.php
href http://www.refulz.com:8082/index.php#tab2
hash #tab2
search ?foo=789
var x = $(location).attr('<property>');
This will work only if you have jQuery. For example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
$(location).attr('href'); // http://www.refulz.com:8082/index.php#tab2
$(location).attr('pathname'); // index.php
</script>
</html>
there's also an interesting tool called CUFON. There's a demonstration of how to use it in this blog It's really simple and interesting. Also, it doesn't allow people to ctrl+c/ctrl+v the generated content.
I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra \n at the end.
private static IPAddress GetExternalIp () {
using (WebClient client = new WebClient()) {
List<String> hosts = new List<String>();
hosts.Add("https://icanhazip.com");
hosts.Add("https://api.ipify.org");
hosts.Add("https://ipinfo.io/ip");
hosts.Add("https://wtfismyip.com/text");
hosts.Add("https://checkip.amazonaws.com/");
hosts.Add("https://bot.whatismyipaddress.com/");
hosts.Add("https://ipecho.net/plain");
foreach (String host in hosts) {
try {
String ipAdressString = client.DownloadString(host);
ipAdressString = ipAdressString.Replace("\n", "");
return IPAddress.Parse(ipAdressString);
} catch {
}
}
}
return null;
}
hasOwnProperty() is a nice property to validate object keys. Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true
As with all technologies, it has its ups and downs. If you are using an iframe to get around a properly developed site, then of course it is bad practice. However sometimes an iframe is acceptable.
One of the main problems with an iframe has to do with bookmarks and navigation. If you are using it to simply embed a page inside your content, I think that is fine. That is what an iframe is for.
However I've seen iframes abused as well. It should never be used as an integral part of your site, but as a piece of content within a site.
Usually, if you can do it without an iframe, that is a better option. I'm sure others here may have more information or more specific examples, it all comes down to the problem you are trying to solve.
With that said, if you are limited to HTML and have no access to a backend like PHP or ASP.NET etc, sometimes an iframe is your only option.
In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:
$item->day = 0;
I had to do;
$item->day = (string) 0;
It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:
$factory->define(App\Schedule::class, function (Faker $faker) {
return [
'day' => (string) $faker->numberBetween(0, 6),
//
];
});
Just remove the (
and the )
on your SELECT statement:
insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;
If git was to rename detached HEAD
I would have it named as a HEAD that isn’t identified by a branch and will soon be forgotten.
We as people can easily remember branch names. We do git checkout new-button-feature
/ git checkout main
. main
and new-button-feature
are easy to remember. And we can just do git branch
and get a list of all branches. But to do the same with just commits you'd have to do git reflog
which is very tedious. Because you have thousands of commits but only very few branches.
A detached commit’s identifier is just its SHA. So suppose you checked out a commit (not a branch) i.e. you did git checkout d747dd10e450871928a56c9cb7c6577cf61fdf31
you'll get:
Note: checking out 'd747dd10e450871928a56c9cb7c6577cf61fdf31'.
You are in 'detached HEAD' state.
...
Then if you made some changes and made a commit, you're still NOT on a branch.
Do you think you'd remember the commit SHA? You won't!
git doesn't want this to happen. Hence it's informing your HEAD is not associated to a branch so you're more inclined to checkout a new branch. As a result below that message it also says:
If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:
git checkout -b
To go a bit deeper a branch is built in a way that it's smart. It will update its HEAD as you make commits. Tags on the other hand are not meant to be like that. If you checkout a tag, then you're again on a detached HEAD. The main reason is that if you make a new commit from that tag then given that that commit is not referenced by anything (not any branch or tag) then still its considered a detached HEAD.
Attached HEADs can only happen when you're on a branch.
For more see here
HEAD is a pointer, and it points — directly or indirectly — to a particular commit:
Attached HEAD means that it is attached to some branch (i.e. it points to a branch).
Detached HEAD means that it is not attached to any branch, i.e. it points directly to some commit.
To look at from another angle, if you're on a branch and do cat .git/HEAD
you'd get:
ref: refs/heads/Your-current-branch-name
Then if you do cat refs/heads/Your-current-branch-name
then you'd also see the commit that your branch is pointing/referencing to.
However if you were on a detached HEAD you and cat .git/HEAD
you'd just get the SHA of the commit and nothing more:
639ce5dd952a645b7c3fcbe89e88e3dd081a9912
By nothing more I mean the head isn't pointing to any branch. It's just directly pointing to a commit.
As a result of all this, anytime you checkout a commit, even if that commit was the latest commit of your main branch, you're still in a detached HEAD because your HEAD is not pointing to any branches. Hence even checking out a tag is will put you in a detached HEAD
Special thanks to Josh Caswell & Saagar Jha in helping me figure this out.
One thing to note, if you have a log4j.properties file on your classpath you do not need to call BasicConfigurator. A description of how to configure the properties file is here.
You could pinpoint whether your IDE is causing the issue by trying to run this class from the command line with log4j.jar and log4j.properties on your classpath.
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
I had to do the following because, if the properties were not declared in the correct order, it would randomly break words at the wrong place and without adding a hyphen.
-moz-white-space: pre-wrap;
white-space: pre-wrap;
hyphens: auto;
-ms-word-break: break-all;
-ms-word-wrap: break-all;
-webkit-word-break: break-word;
-webkit-word-wrap: break-word;
word-break: break-word;
word-wrap: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
Originally posted by Enigmo: https://stackoverflow.com/a/14191114
Another way of viewing the full content of the cells in a pandas dataframe is to use IPython's display functions:
from IPython.display import HTML
HTML(df.to_html())
easier way. You could make your object inherit from the Error object. Example:
function NotImplementError(message)
{
this.message = message;
Error.call();
Error.call(message);
}
what we are doing is using the function call() which call the constructor of the Error class so is basicly the same thing as implementing a class inheritance in other object oriented languages.
For getting all the info about the cordova package use this command:
npm info cordova
This article helps. In particular, this section:
-File
Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.
i.e.
powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3
means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.
I Hope this will help you.
echo getcwd().'<br>'; // getcwd() will return current working directory
echo dirname(getcwd(),1).'<br>';
echo dirname(getcwd(),2).'<br>';
echo dirname(getcwd(),3).'<br>';
Output :
C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64
This did the trick for me: I was able to find which macro called a particular query. Incidentally, the reason someone who does know how to code in VBA would want to write something like this is when they've inherited something macro-ish written by someone who doesn't know how to code in VBA.
Function utlFindQueryInMacro
( strMacroNameLike As String
, strQueryName As String
) As String
' (c) 2012 Doug Den Hoed
' NOTE: requires reference to Microsoft Scripting Library
Dim varItem As Variant
Dim strMacroName As String
Dim oFSO As New FileSystemObject
Dim oFS
Dim strFileContents As String
Dim strMacroNames As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
If Len(strMacroName) = 0 _
Or InStr(strMacroName, strMacroNameLike) > 0 Then
'Debug.Print "*** MACRO *** "; strMacroName
Application.SaveAsText acMacro, strMacroName, "c:\temp.txt"
Set oFS = oFSO.OpenTextFile("c:\temp.txt")
strFileContents = ""
Do Until oFS.AtEndOfStream
strFileContents = strFileContents & oFS.ReadLine
Loop
Set oFS = Nothing
Set oFSO = Nothing
Kill "c:\temp.txt"
'Debug.Print strFileContents
If InStr(strFileContents, strQueryName) 0 Then
strMacroNames = strMacroNames & strMacroName & ", "
End If
End If
Next varItem
MsgBox strMacroNames
utlFindQueryInMacro = strMacroNames
End Function
You will need to use strip()
because of the extra bits in the strings.
A2 = [float(x.strip('"')) for x in A1]
There's a much better way to achieve your desired result, using SQL Server's analytic (or windowing) functions.
SELECT DISTINCT Date, MAX(Score) OVER(PARTITION BY Date) FROM ScoresTable
If you need more than just the date and max score combinations, you can use ranking functions, eg:
SELECT *
FROM ScoresTable t
JOIN (
SELECT
ScoreId,
ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Score DESC) AS [Rank]
FROM ScoresTable
) window ON window.ScoreId = p.ScoreId AND window.[Rank] = 1
You may want to use RANK() instead of ROW_NUMBER() if you want multiple records to be returned if they both share the same MAX(Score).
A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.
http://jsbin.com/ekohep/2/edit#javascript,html,live
Enjoy :)
PS, doesn't use jQuery - but obviously could.
This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.
You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.
componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
if (this.props.userName !== prevProps.userName) {
this.fetchData(this.props.userName);
}
}
Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.
For more info, refer to the official docs:
Would this parser help you?
https://github.com/fiann/jquery.ogp
It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:
$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());
Note the single-quotes around the attribute values; this prevents parse errors in jQuery.
You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).
Run this command after having installed Chocolatey (as Administrator):
choco install wget
I don't think it's a matter of being Pythonic or elegant. It's a matter of preventing exceptions as much as you can. Exceptions are meant to handle errors that might occur in code or events you have no control over.
In this case, you have full control when checking if an item is an attribute or in a dictionary, so avoid nested exceptions and stick with your second attempt.
Use \W
which is equivalent to [^a-zA-Z0-9_]
. Check the documentation, https://docs.python.org/2/library/re.html
Import re
s = 'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'
update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.
The output went to stderr. Use 2>
to capture that.
$make 2> file
JACKSON Library
One option would be to use Jackson library. First import the latest version (now is):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.0</version>
</dependency>
Then, you can implement the correct answer as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JSONUtils {
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString ) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
}
Google GSON option
Another option is to use Google Gson. Import the dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
Again, you can implement the proposed solution as:
import com.google.gson.Gson;
public final class JSONUtils {
private static final Gson gson = new Gson();
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString) {
try {
gson.fromJson(jsonInString, Object.class);
return true;
} catch(com.google.gson.JsonSyntaxException ex) {
return false;
}
}
}
A simple test follows here:
//A valid JSON String to parse.
String validJsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
// Invalid String with a missing parenthesis at the beginning.
String invalidJsonString = "\"developers\": [ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
boolean firstStringValid = JSONUtils.isJSONValid(validJsonString); //true
boolean secondStringValid = JSONUtils.isJSONValid(invalidJsonString); //false
Please, observe that there could be a "minor" issue due to trailing commas that will be fixed in release 3.0.0
.
I had this error and fixed it by adding the guard on readyState
and status
shown here:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Your code here
}
};
In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone
select
ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1,
period_next_id, period_name_long
from
(
select distinct col1, period_name_long, 'X' as num
from {TABLE}
) as x
You can have multiple tags when building the image:
$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .
Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t
Surya, your way won't work, because of two reasons:
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this
to a Groovy method as parameter context
from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."
(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)
Got this error as well lately. Tried all the above fixes, but none worked.
To disable it, type services.msc
in command prompt, then right click and disable Internet Connection Sharing. I edited the properties of it as well to disable at startup. Mine looks like so now: services capture screenshot.
The target
you tried to add in InputProps
is not the same target
you wanted which is in React.FormEvent
So, the solution I could come up with was, extending the event related types to add your target type, as:
interface MyEventTarget extends EventTarget {
value: string
}
interface MyFormEvent<T> extends React.FormEvent<T> {
target: MyEventTarget
}
interface InputProps extends React.HTMLProps<Input> {
onChange?: React.EventHandler<MyFormEvent<Input>>;
}
Once you have those classes, you can use your input component as
<Input onChange={e => alert(e.target.value)} />
without compile errors. In fact, you can also use the first two interfaces above for your other components.
A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.
But in the documentation you may read now : "All JavaScript API applications require authentication."
I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).
You better use a key when you want to be sure that your application will still work in 1 or 2 years.
EditPad Pro and PowerGREP have a unique feature that allows you to change the case of the backreference.
\U1
inserts the first backreference in uppercase,\L1
in lowercase and\F1
with the first character in uppercase and the remainder in lowercase. Finally,\I1
inserts it with the first letter of each word capitalized, and the other letters in lowercase.
Source: Goyvaerts, Jan (2006). Regular Expressions: The Complete Tutorial. Lulu.com. p. 35. ISBN 1411677609. Google Books. Retrieved on June 25, 2010.
Try Run This Query
ALTER TABLE tablename AUTO_INCREMENT = value;
Or Try This Query For The Reset Auto Increment
ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;
And Set Auto Increment Then Run This Query
ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;
For me, using OS X Catalina:
Changing from AllowOverride None
to AllowOverride All
is the one that works.
httpd.conf
is located on /etc/apache2/httpd.conf
.
Env: PHP7. MySQL8.
You might also consider Microsoft Enterprise Library Logging Block. It comes with nice designer.
Git doesn't store empty folders. Just make sure there's a file in the folder like doc/foo.txt and run git add doc
or git add doc/foo.txt
, and the folder will be added to your local repository once you've committed (and appear on GitHub once you've pushed it).
How about something like this.
function objectToArray( $object ){
if( !is_object( $object ) && !is_array( $object ) ){
return $object;
}
if( is_object( $object ) ){
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
and call this function with your object
$array = objectToArray( $yourObject );
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
Or simply:
Date.now
From MDN documentation:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970
Available since ECMAScript 5.1
It's the same as was mentioned above (new Date().getTime()
), but more shortcutted version.
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.
You can use this constructor
moment({h:0, m:0, s:0, ms:0})
http://momentjs.com/docs/#/parsing/object/
console.log( moment().format('YYYY-MM-DD HH:mm:ss') )_x000D_
_x000D_
console.log( moment({h:0, m:0, s:0, ms:0}).format('YYYY-MM-DD HH:mm:ss') )
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
I'm developing an application that needs currency conversion, and been using Open Exchange Rates because I wouldn't be paying since the app is in testing. But as of September 2012 Open Exchange Rates is gonna be paid for non-personal, so I checked out that they were using the Yahoo Finance Webservice (the one that "doesn't exist") and looking for documentation on it got here, and opted to use YQL.
Using YQL with the Yahoo Finance table (yahoo.finance.quotes) linked by NT3RP, currencies appear with symbol="ISOCODE=X", for example: "ARS=X" for Argentine Peso, "AUD=X" for Australian Dollar. "USD=X" doesn't exist, but it would be 1, since the rest are rates against USD.
The "price" value on the OP API is in the field "LastTradePriceOnly" of the table. For my application I used the "Ask" field.
In additional to the popular K8s, jasypt or vault solutions, there's also Karmahostage. It enables you to do:
@EncryptedValue("${application.secret}")
private String application;
It works the same way jasypt does, but encryption happens on a dedicated saas solution, with a more fine-grained ACL model attached to it.
Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.
Solved my problem by adding this to my ListView
:
android:scrollbars="none"
DataSet is collection of DataTables.... you can get the datatable from DataSet as below.
//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset
In SQL Server 2008 you can use a multi-table update as follows:
UPDATE tblindiantime
SET tblindiantime.CountryName = contacts.BusinessCountry
FROM tblindiantime
JOIN contacts
ON -- join condition here
You need a join condition to specify which row should be updated.
If the target table is currently empty then you should use an INSERT instead:
INSERT INTO tblindiantime (CountryName)
SELECT BusinessCountry FROM contacts
UPDATE T1,T2
INNER JOIN T1 ON T1.Brands = T2.Brands
SET
T1.Inci = T2.Inci
WHERE
T1.Category= T2.Category
AND
T1.Date = T2.Date
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1
, then push
it onto the returned array.
?Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
?
My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in
, you can sort both arrays first to reindex all their values:
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
Usage would look like:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
var diff = function(arr, arr2) {
And you'd change anywhere where the func originally said this
to arr2
.
Share : Text
@IBAction func shareOnlyText(_ sender: UIButton) {
let text = "This is the text....."
let textShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
}
Share : Image
@IBAction func shareOnlyImage(_ sender: UIButton) {
let image = UIImage(named: "Product")
let imageShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Share : Text - Image - URL
@IBAction func shareAll(_ sender: UIButton) {
let text = "This is the text...."
let image = UIImage(named: "Product")
let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
let shareAll= [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Check out the example from enable-cors.org:
In your ExpressJS app on node.js, do the following with your routes:
app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.get('/', function(req, res, next) { // Handle the get for this route }); app.post('/', function(req, res, next) { // Handle the post for this route });
The first call (app.all
) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).
[Edit]
If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static())
:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I tested this with your code, and got the headers on assets from the public
directory:
var express = require('express')
, app = express.createServer();
app.configure(function () {
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(app.router);
});
app.configure('development', function () {
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler());
});
app.listen(8888);
console.log('express running at http://localhost:%d', 8888);
You could, of course, package the function up into a module so you can do something like
// cors.js
module.exports = function() {
return function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
};
}
// server.js
cors = require('./cors');
app.use(cors());
node-dev
node-dev is great alternative to both nodemon and supervisor for developers who like to get growl (or libnotify) notifications on their desktop whenever the server restarts or when there is an error or change occur in file.
Installation:
npm install -g node-dev
Use node-dev, instead of node:
node-dev app.js
Notification on Changing file so server start automatically
console out put
This is an old question but alot of the answers in here use VB or VBA. The tag says vbscript (which is how I got here).
The answers here got kind of muddled since VB is super broad where you can have so many applications of it. My answer is solely on vbscript and accomplishes my case of formatting in YYYYMMDD in vbscript
Sharing what I've learned:
DateTime
functions in vbscript defined here so you can mix-n-match to get the result that you wantYYYYMMDD
to do that I just needed to concat DatePart
like so for the current Date: date = DatePart("yyyy",Date) & DatePart("m",Date) & DatePart("d",Date)
That's all, I hope this helps someone.
On Eclipse make a raw delete of Tomcat configuration folder under project "Servers". I tried it as last hope and it worked.
I am Using Design Support Library. And just by using custom theme I achived transparent Status Bar when Opened Navigation Drawer.
<style name="NavigationStyle" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/primaryColor</item>
<item name="colorPrimaryDark">@color/primaryColorDark</item>
<!-- To Make Navigation Drawer Fill Status Bar and become Transparent Too -->
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
Finally add theme in Manifest File
<activity
........
........
android:theme="@style/NavigationStyle">
</activity>
Do not forget to use the property, android:fitsSystemWindows="true"
in "DrawerLayout"
It is common for comparison functions to return 0
on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp()
and memcmp()
work like this.
It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare()
or similar).
look at Comparing Inline and Multi-Statement Table-Valued Functions you can find good descriptions and performance benchmarks
I have used a syntax like this before:
$(ProjectDir)..\headers
or
..\headers
As other have pointed out, the starting directory is the one your project file is in(vcproj
or vcxproj
), not where your main code is located.
Please also make sure that the modal div is nested inside your <body>
element.
From Linux kernel (GPLv2):
/*
* Divide positive or negative dividend by positive divisor and round
* to closest integer. Result is undefined for negative divisors and
* for negative dividends if the divisor variable type is unsigned.
*/
#define DIV_ROUND_CLOSEST(x, divisor)( \
{ \
typeof(x) __x = x; \
typeof(divisor) __d = divisor; \
(((typeof(x))-1) > 0 || \
((typeof(divisor))-1) > 0 || (__x) > 0) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \
)
Context
is an "interface" to the global information about an application environment. In practice, Context
is actually an abstract class, whose implementation is provided by the Android system.
It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents, etc.
In the following picture, you can see a hierarchy of classes, where Context
is the root class of this hierarchy. In particular, it's worth emphasizing that Activity
is a descendant of Context
.
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
Just use the below formation###
rules_id = ["9","10"]
sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))
note the str(tuple(rules_id))
.
How can I go from this
A - B - C - D - E
|
master
to this?
A - B - C - D - E
| |
master newbranch
With two commands
giving
A - B - C - D - E
|
newbranch
and
giving
A - B - C - D - E
| |
master newbranch
You have to add following in header:
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
Then call fixform()
in load your page.
Just just using Transformers It did not work for me I was getting type cast exception.
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class))
did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.
It worked for me when I make following changes When I have added sqlQuery.addScalar(-)
each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");
And I have join MYEngityName with NextEnity we cant just select *
in the Query it will give array of Object in the return list.
Below code sample :
session = ht.getSessionFactory().openSession();
String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM MYEngityName nft INNER JOIN NextEntity m on nft.mId = m.id where nft.txnId < ").append(lastTxnId)
.append(StringUtils.isNotBlank(regionalCountryOfService)? " And m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
.append(" order by nft.txnId desc").toString();
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
sqlQuery.addScalar("txnId",Hibernate.LONG)
.addScalar("merchantId",Hibernate.INTEGER)
.addScalar("count",Hibernate.BYTE)
.addScalar("retryReason")
.addScalar("langCode");
sqlQuery.setMaxResults(maxLimit);
return sqlQuery.list();
It might help some one. in this way work for me.
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
From MSDN:
Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers.
This means that you can use a single underscore as a member variable prefix, as long as it's followed by a lower-case letter.
This is apparently taken from section 17.4.3.1.2 of the C++ standard, but I can't find an original source for the full standard online.
See also this question.
Compare date only instead of date + time (NOW) with:
CURDATE()
You can try this way also.
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
Output:
object(stdClass)#1 (0) { }
Same problem in VS 2013
I added in Web.config :
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
It worked like a charm.
I found it on page: http://www.programmer.bz/Home/tabid/115/asp_net_sql/281/The-type-or-namespace-name-Objects-does-not-exist-in-the-namespace-SystemData.aspx
window.setInterval(function() {
alert('test');
}, 10000);
Calls a function repeatedly, with a fixed time delay between each call to that function.
modelBuilder.Property(x => x.FirstName).IsUnicode().IsRequired().HasMaxLength(50);
Upsert is what you want. UPSERT
syntax was added to SQLite with version 3.24.0 (2018-06-04).
CREATE TABLE phonebook2(
name TEXT PRIMARY KEY,
phonenumber TEXT,
validDate DATE
);
INSERT INTO phonebook2(name,phonenumber,validDate)
VALUES('Alice','704-555-1212','2018-05-08')
ON CONFLICT(name) DO UPDATE SET
phonenumber=excluded.phonenumber,
validDate=excluded.validDate
WHERE excluded.validDate>phonebook2.validDate;
Be warned that at this point the actual word "UPSERT" is not part of the upsert syntax.
The correct syntax is
INSERT INTO ... ON CONFLICT(...) DO UPDATE SET...
and if you are doing INSERT INTO SELECT ...
your select needs at least WHERE true
to solve parser ambiguity about the token ON
with the join syntax.
Be warned that INSERT OR REPLACE...
will delete the record before inserting a new one if it has to replace, which could be bad if you have foreign key cascades or other delete triggers.
No need to generate a function for it. Just do it like this:
$('a').each(function(){
var s = $(this).clone().wrap('<p>').parent().html();
console.log(s);
});
(Your browser's console will show what is logged, by the way. Most of the latest browsers since around 2009 have this feature.)
The magic is this on the end:
.clone().wrap('<p>').parent().html();
The clone means you're not actually disturbing the DOM. Run it without it and you'll see p
tags inserted before/after all hyperlinks (in this example), which is undesirable. So, yes, use .clone()
.
The way it works is that it takes each a
tag, makes a clone of it in RAM, wraps with p
tags, gets the parent of it (meaning the p
tag), and then gets the innerHTML
property of it.
EDIT: Took advice and changed div
tags to p
tags because it's less typing and works the same.
It is true that if you present a view controller modally on the iPhone, it will always be presented full screen no matter how you present it on the top view controller of a navigation controller or any other way around. But you can always show the navigation bar with the following workaround way:
Rather than presenting that view controller modally present a navigation controller modally with its root view controller set as the view controller you want:
MyViewController *myViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController =
[[UINavigationController alloc] initWithRootViewController:myViewController];
//now present this navigation controller modally
[self presentViewController:navigationController
animated:YES
completion:^{
}];
You should see a navigation bar when your view is presented modally.
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
To use it:
//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();
//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
It's valid, but rather nasty. I would suggest it's generally bad to allow fall-throughs as it can lead to some very messy spaghetti code.
It's almost certainly better to break these cases up into several switch statements or smaller functions.
[edit] @Tristopia: Your example:
Example from UCS-2 to UTF-8 conversion
r is the destination array,
wc is the input wchar_t
switch(utf8_length)
{
/* Note: code falls through cases! */
case 3: r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800;
case 2: r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0;
case 1: r[0] = wc;
}
would be clearer as to it's intention (I think) if it were written like this:
if( utf8_length >= 1 )
{
r[0] = wc;
if( utf8_length >= 2 )
{
r[1] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x0c0;
if( utf8_length == 3 )
{
r[2] = 0x80 | (wc & 0x3f); wc >>= 6; wc |= 0x800;
}
}
}
[edit2] @Tristopia: Your second example is probably the cleanest example of a good use for follow-through:
for(i=0; s[i]; i++)
{
switch(s[i])
{
case '"':
case '\'':
case '\\':
d[dlen++] = '\\';
/* fall through */
default:
d[dlen++] = s[i];
}
}
..but personally I would split the comment recognition into it's own function:
bool isComment(char charInQuestion)
{
bool charIsComment = false;
switch(charInQuestion)
{
case '"':
case '\'':
case '\\':
charIsComment = true;
default:
charIsComment = false;
}
return charIsComment;
}
for(i=0; s[i]; i++)
{
if( isComment(s[i]) )
{
d[dlen++] = '\\';
}
d[dlen++] = s[i];
}
Add it after Placeholder attribute.
[textarea* message id:message class:form-control 40x7 placeholder "Message"]
I used your own pivot as a nested query and came to this result:
SELECT
[sub].[chardate],
SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
select *
from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
[sub].[chardate],
[sub].[numericmonth]
ORDER BY
[sub].[numericmonth] ASC
None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:
while driver.find_element_by_tag_name('div'):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Divs=driver.find_element_by_tag_name('div').text
if 'End of Results' in Divs:
print 'end'
break
else:
continue