I have found dom4j to be the tool for working with XML. Especially compared to Xerces.
The minimum configuration to properly run sqlplus
from the shell is to set ORACLE_HOME
and LD_LIBRARY_PATH
. For ease of use, you might want to set the PATH
accordingly too.
Assuming you have unzipped the required archives in /opt/oracle/instantclient_11_1
:
$ export ORACLE_HOME=/opt/oracle/instantclient_11_1
$ export LD_LIBRARY_PATH="$ORACLE_HOME"
$ export PATH="$ORACLE_HOME:$PATH"
$ sqlplus
SQL*Plus: Release 11.1.0.7.0 - Production on Wed Dec 31 14:06:06 2014
...
If you do not specifically need the alt text of an image, then you can just target the class/id of the image.
$('img.propImg').each(function(){
enter code here
}
I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.
$('img.propImg').each(function(){ //for each loop that gets all the images.
if($(this).attr('src') == "img/{{images}}") { // if the src matches this
$(this).css("display", "none") // hide the image.
}
});
perl one-liner alert
just for fun... print only one line after match
perl -lne '$next = ($.+1) if /match/; $. == $next && print' data.txt
even more fun... print the next ten lines after match
perl -lne 'push @nexts, (($.+1)..($.+10)) if /match/; $. ~~ @nexts && print' data.txt
kinda cheating though since there's actually two commands
Storing previous url in a session variable is bad, because the user might right click on multiple pages and then come back and save.
unless you save the previous url in the session variable to a hidden field in the form and after save header( "Location: save URL of calling page" );
2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:
% python
So I just use:
% winpty python
As some people have noted above, you can also use:
% python -i
2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line:
Add this code where you want to click and load Fragment. I hope it's work for you.
Fragment fragment = new yourfragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I had trouble until i used the inspector and realized react puts everything inside a div with id='root' granting that 100% height along with body and html worked for me.
Also, be careful so your href location isn't faulty. Study case:
My index page was in a temporary sub-folder named LAYOUTS. To reach the favicon.png from inside the IMAGES folder, which was a sibling of the LAYOUTS folder, I had to put a path in my href like this
href="../images/favicon-32x32.png"
Double periods are necessary for folder navigation "upwards", then the forward slash + images
string gets you into the images folder (performing a tree branch "jump") and finally you get to reference your file by writing favicon-32x32.png
.
This explanation is useful for those that start out from scratch and it would have been useful to have seen it a couple of times since I would forget that I had certain *.php files outside the LAYOUTS folder which needed different tree hrefs on my links, from the HEAD section of each page.
Reference the path to your favicon image accordingly.
You can do this:
myList.get(3).setEmail("new email");
None of the other solutions to these question worked for me.
The only think that worked is this one:
It removes "name" and "id" attributes from elements and assigns them back after 1ms. Put this in document get ready.
$(document).ready(function() {
$('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {
var input = this;
var name = $(input).attr('name');
var id = $(input).attr('id');
$(input).removeAttr('name');
$(input).removeAttr('id');
setTimeout(function () {
$(input).attr('name', name);
$(input).attr('id', id);
}, 1);
});
});
What about this solution?
#ifndef VERSION_H
#define VERSION_H
static const char SVER[] = "14.2.1";
static const char AVER[] = "1.1.0.0";
#else
extern static const char SVER[];
extern static const char AVER[];
#endif /*VERSION_H */
The only draw back I see is that the include guard doesn't save you if you include it twice in the same file.
This is a good way to get a random number between two numbers of your choice.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define randnum(min, max) \
((rand() % (int)(((max) + 1) - (min))) + (min))
int main()
{
srand(time(NULL));
printf("%d\n", randnum(1, 70));
}
Output the first time: 39
Output the second time: 61
Output the third time: 65
You can change the values after randnum
to whatever numbers you choose, and it will generate a random number for you between those two numbers.
For those of you, who are still facing this. I got this problem after I upgraded to Android Studio to 2.1.2. I was stuck at this problem for about an hour, I tried these solutions:
I double checked the gradle scripts and found this:
compileSdkVersion 23
buildToolsVersion "24.0.0"
changed to:
compileSdkVersion 23
buildToolsVersion "23.0.3"
I don't know how this caused the error, but this did the trick for me. Please let me know how this worked if you know the answer. Thanks
To read one byte:
file.read(1)
8 bits is one byte.
You basically can loop over a Range
Get a sheet
myWs = (Worksheet)MyWb.Worksheets[1];
Get the Range you're interested in If you really want to check every cell use Excel's limits
The Excel 2007 "Big Grid" increases the maximum number of rows per worksheet from 65,536 to over 1 million, and the number of columns from 256 (IV) to 16,384 (XFD). from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel
and then loop over the range
Range myBigRange = myWs.get_Range("A1", "A256");
string myValue;
foreach(Range myCell in myBigRange )
{
myValue = myCell.Value2.ToString();
}
Your return is useless if you don't assign it
list=defineAList()
I had the same issue after I started using Xcode 6.1 and changed my launcher images. I had all images in an Asset Catalog. I would get only a black screen instead of the expected static image. After trying so many things, I realised the problem was that the Asset Catalog had the Project 'Target Membership' ticked-off in its FileInspector view. Ticking it to ON did the magic and the image started to appear on App launch.
Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).
Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template
, ng-container
and ViewContainerRef
in following way:
<div>
<ng-container #outlet >
</ng-container>
</div>
<ng-template #content>
<child></child>
</ng-template>
Then in component having reference to both #outlet
and #content
we can clear outlets' content and insert another instance of child component:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;
private rerender() {
this.outletRef.clear();
this.outletRef.createEmbeddedView(this.contentRef);
}
Additionally initial content should be inserted on AfterContentInit
hook:
ngAfterContentInit() {
this.outletRef.createEmbeddedView(this.contentRef);
}
Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .
You can use System.currentTimeMillis()
.
At least in OpenJDK, Date
uses this under the covers.
The call in System
is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.
I know this post specifically asks for sorting a TreeMap by values, but for those of us that don't really care about implementation but do want a solution that keeps the collection sorted as elements are added, I would appreciate feedback on this TreeSet-based solution. For one, elements are not easily retrieved by key, but for the use case I had at hand (finding the n keys with the lowest values), this was not a requirement.
TreeSet<Map.Entry<Integer, Double>> set = new TreeSet<>(new Comparator<Map.Entry<Integer, Double>>()
{
@Override
public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2)
{
int valueComparison = o1.getValue().compareTo(o2.getValue());
return valueComparison == 0 ? o1.getKey().compareTo(o2.getKey()) : valueComparison;
}
});
int key = 5;
double value = 1.0;
set.add(new AbstractMap.SimpleEntry<>(key, value));
Just for fun:
var mystring = "this,is,a,test"
var newchar = '|'
mystring = mystring.split(',').join(newchar);
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
Update: Mercurial has added --amend
which should be the preferred option now.
You can rollback the last commit (but only the last one) with hg rollback
and then reapply it.
Important: this permanently removes the latest commit (or pull). So if you've done a hg update
that commit is no longer in your working directory then it's gone forever. So make a copy first.
Other than that, you cannot change the repository's history (including commit messages), because everything in there is check-summed. The only thing you could do is prune the history after a given changeset, and then recreate it accordingly.
None of this will work if you have already published your changes (unless you can get hold of all copies), and you also cannot "rewrite history" that include GPG-signed commits (by other people).
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:
x = Integer.valueOf(9);
Additionally, Integer
is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator
(without adding your own layer of boxing). Do the following instead:
a.set(0, 9);
Here is VERY simple script to trigger both a 'resizestart' and 'resizeend' event on the window object.
There is no need to muck around with dates and times.
The d
variable represents the number of milliseconds between resize events before triggering the resize end event, you can play with this to change how sensitive the end event is.
To listen to these events all you need to do is:
resizestart: $(window).on('resizestart', function(event){console.log('Resize Start!');});
resizeend:
$(window).on('resizeend', function(event){console.log('Resize End!');});
(function ($) {
var d = 250, t = null, e = null, h, r = false;
h = function () {
r = false;
$(window).trigger('resizeend', e);
};
$(window).on('resize', function (event) {
e = event || e;
clearTimeout(t);
if (!r) {
$(window).trigger('resizestart', e);
r = true;
}
t = setTimeout(h, d);
});
}(jQuery));
The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:
git branch -D `git branch --merged | grep -v \* | xargs`
or, further simplified to:
git branch --merged | grep -v \* | xargs git branch -D
Importantly, as noted by @AndrewC, using git branch
for scripting is discouraged. To avoid it use something like:
git for-each-ref --format '%(refname:short)' refs/heads | grep -v master | xargs git branch -D
Caution warranted on deletes!
$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
Story-123-a
Story-123-b
Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).
To assign, you should use p=p+1;
instead of p+1=p;
int main()
{
int x[3]={4,5,6};
int *p=x;
p=p+1; /*You just needed to switch the terms around*/
cout<<p<<endl;
getch();
}
I had the same problem - "Can't connect to docker daemon." (except I didn't get any 'file not found' errors on trying to start the server.)
'ps' showed that "/usr/bin/docker -d" was still running
I realised that I'd never actually succeeded in running the server myself though. Every attempt had produced
...
2014/03/24 21:57:29 pid file found, ensure docker is not running or delete /var/run/docker.pid
So I belatedly realised that installing docker had maybe registered the daemon with upstart, which had started it for me. Hence, trying to kill the daemon to manually restart it fails (operation not permitted). So I did a
sudo kill -9 <PID>
on the daemon process. Another daemon immediately took its place, and this new one DOES now let my CLI client connect:
$ sudo docker info
Containers: 0
Images: 0
Driver: aufs
Root Dir: /var/lib/docker/aufs
Dirs: 0
WARNING: No memory limit support
WARNING: No swap limit support
An ES6 update... though both filter and map might need customization.
Object.entries(theObj)
returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.
Saves a ton of work on iterating over parts of an object Object.keys(theObj)
, or Object.values()
separately.
const buttons = {_x000D_
button1: {_x000D_
text: 'Close',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button2: {_x000D_
text: 'OK',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button3: {_x000D_
text: 'Cancel',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
.filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
.map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
_x000D_
console.log(list)
_x000D_
In Xcode 5 this has been moved to:
Xcode>Preferences>Accounts>View Details button>
I see 4 issues with your code:
setState
method to actually change the stateLet's try to fix that:
componentDidMount: function() {
var intervalId = setInterval(this.timer, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
},
componentWillUnmount: function() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
},
timer: function() {
// setState method is used to update the state
this.setState({ currentCount: this.state.currentCount -1 });
},
render: function() {
// You do not need to decrease the value here
return (
<section>
{this.state.currentCount}
</section>
);
}
This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:
timer: function() {
var newCount = this.state.currentCount - 1;
if(newCount >= 0) {
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
},
I believe this example is more barebones and easier to understand then @dowomenfart.
.child {
display: inline-block;
margin: 0 1em;
flex-grow: 1;
width: calc(25% - 2em);
}
This accomplishes the same width calculations while cutting straight to the meat. The math is way easier and em
is the new standard due to its scalability and mobile-friendliness.
As of npm 5.2.0, once you've installed locally via
npm i typescript --save-dev
...you no longer need an entry in the scripts
section of package.json
-- you can now run the compiler with npx:
npx tsc
Now you don't have to update your package.json file every time you want to compile with different arguments.
OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.
You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword
to pass the password YourPassword
from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.
If you need to have the number of unique values as an additional column in the data frame containing your values (a column which may represent sample size for example), plyr provides a neat way:
data_frame <- data.frame(v = rep(c(1,2, 2, 2), 25))
library("plyr")
data_frame <- ddply(data_frame, .(v), transform, n = length(v))
Android WebView is just another render engine that render HTML contents downloaded from a HTTP server, much like Chrome or FireFox. I don't know the reason why you need get the rendered page (or screenshot) from WebView. For most of situation, this is not necessary. You can always get the raw HTML content from HTTP server directly.
There are already answers posted talking about getting the raw stream using HttpUrlConnection or HttpClient. Alternatively, there is a very handy library when dealing with HTML content parse/process on Android: JSoup, it provide very simple API to get HTML contents form HTTP server, and provide an abstract representation of HTML document to help us manage HTML parsing not only in a more OO style but also much easily:
// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
It is handy when, for example, you want to download HTML document first then add some custom css or javascript to it before passing it to WebView for rendering. Much more on their official web site, worth to check it out.
While some of the answers posted here will help find what you seek, the following sub-command of git branch is a more suitable solution for your task.
While in master
one could run the command to enumerate the branches one could safely remove, like so:
git branch --merged
develop
fpg_download_links
* master
master_merge_static
# Delete local and remote tracking branches you don't want
git branch -d fpg_download_links
git push origin :fpg_download_links
git branch -d master_merge_static
git push origin :master_merge_static
# There is also a flag to specify remote branches in the output
git branch --remotes --merged
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
Do the following test:
Open a Command Prompt and type: tnsping instance_name
where instance_name is the name of the instance you want to connect (if it's a XE database, use "tnsping xe"
If it returns ok, follow steps of Der Wolf's answer. If doesn't return ok, follow steps of Annjawn's answer.
It solved for me in both cases.
STR_TO_DATE allows you to do this, and it has a format argument.
You don't need to set the value at all. ng-model takes care of it all:
Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/
There is no problem to do sudo python setup.py install, if you're sure it's what you want to do.
The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.
so, if you want pip to be accessible os wide, that's probably the way to go. I do not say that others way are bad, but this is probably fair enough.
If g++
still gives error Try using:
g++ file.c -lstdc++
Look at this post: What is __gxx_personality_v0 for?
Make sure -lstdc++
is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.
If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:
width = 12
height = 12
plt.figure(figsize=(width, height))
As far as rm -f
doing "anything else", it does force (-f
is shorthand for --force
) silent removal in situations where rm
would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.
It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:
<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>
In this way you can set rules for all myclass
elements and then more specific rules for one
, two
and three
.
.myclass { color: #f00; }
.two { font-weight: bold; }
etc.
I am going to use a very simple snippet to illustrate the difference:
test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']
The DataFrame looks like this:
id price
0 1 1
1 2 2
2 3 3
3 1 2
4 2 3
5 3 1
6 1 3
7 2 1
8 3 2
There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.
Now, I want to find the minimum payment made by each customer. There are two ways of doing it:
Using apply
:
grouping.min()
The return looks like this:
id
1 1
2 1
3 1
Name: price, dtype: int64
pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
Using transform
:
grouping.transform(min)
The return looks like this:
0 1
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
Name: price, dtype: int64
pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9
Both methods return a Series
object, but the length
of the first one is 3 and the length
of the second one is 9.
If you want to answer What is the minimum price paid by each customer
, then the apply
method is the more suitable one to choose.
If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment
, then you want to use transform
, because:
test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row
Apply
does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.
As you type git status, (use "git checkout -- ..." to discard changes in working directory) is shown.
e.g. git checkout -- .
An example of fine-grained timing using mach_absolute_time()
in Swift 4:
let start = mach_absolute_time()
// do something
let elapsedMTU = mach_absolute_time() - start
var timebase = mach_timebase_info()
if mach_timebase_info(&timebase) == 0 {
let elapsed = Double(elapsedMTU) * Double(timebase.numer) / Double(timebase.denom)
print("render took \(elapsed)")
}
else {
print("timebase error")
}
If you use XHTML, for some reason, note that XHTML 1.0 C 4 says: “Use external scripts if your script uses < or & or ]]> or --.” That is, don’t embed script code inside a script
element but put it into a separate JavaScript file and refer to it with <script src="foo.js"></script>
.
You can use resize like this:
For n = 1 To 5
Columns(n).Resize(, 5).Select
'~~> rest of your code
Next
In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
Add 0.001
first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)
Code example:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b);
}
I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Value = "";
}
}
Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.
In [365]: import pandas as pd
In [366]: df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
In [367]: df
Out[367]:
count mt sp val
0 3 S1 MM1 a
1 2 S1 MM1 n
2 5 S3 MM1 cb
3 8 S3 MM2 mk
4 10 S4 MM2 bg
5 1 S4 MM2 dgb
6 2 S2 MM4 rd
7 2 S2 MM4 cb
8 7 S2 MM4 uyi
### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]
Out[368]:
count mt sp val
0 3 S1 MM1 a
2 5 S3 MM1 cb
3 8 S3 MM2 mk
4 10 S4 MM2 bg
8 7 S2 MM4 uyi
### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values
Out[369]: array([0, 2, 3, 4, 8])
use the val() method:
$(document).ready(function () {
var j = $("textarea");
if (j.val().length > 0) {
alert(j.val());
}
});
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
I would opt for NOT EXISTS
in this case.
SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
(SELECT 'X'
FROM Domain2 D2
WHERE D2.ShortCode = D1.ShortCode
)
you are probably using android.support.v4.app.Fragment
. For this instead of onAttach
method, just use getActivity()
to get the FragmentActivity
with which the fragment is associated with. Else you could use onAttach(Context context)
method.
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.
public void method2(){
Exception ex=new Exception();
StackTraceElement[] ste=ex.getStackTrace();
if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
super.method2();
}
else{
//subclass method2 code
}
}
I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.
I know this question was asked awhile ago, but I have done this before and it allows for more control when aligning items.If you look at it like web programming, it helps. You just nest another LinearLayout
that will contain your button inside of it. You can then change the gravity of the button's layout and make it go to the right while the TextView
is still on the left.
Try this code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal" >
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp"/>
</LinearLayout>
You may have to play with the padding on the nested layout so that it acts how you want it.
I wanted to achieve the same as asked in this question but accepted answer did not work for me in May, 2018
(maybe answer is too old or some other reason). I am using bootsrap 3.3.7
and ionic v1
.
You need to set line-height
to do set height of specific row.
.blank_row {_x000D_
line-height: 3px;_x000D_
}
_x000D_
<table class="action_table">_x000D_
<tbody>_x000D_
<tr class="header_row">_x000D_
<td>Header Item</td>_x000D_
<td>Header Item 2</td>_x000D_
<td>Header Item 3</td>_x000D_
</tr>_x000D_
<tr class="blank_row">_x000D_
<td bgcolor="#000" colspan="3"> </td>_x000D_
</tr>_x000D_
<tr class="data_row">_x000D_
<td>Data Item</td>_x000D_
<td>Data Item 2</td>_x000D_
<td>Data Item 3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
solution of TheSoftwareJedi works,
also you can archive it with using couple of value and nullable types:
static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
foreach T thing in collecion
{
if (thing.Id == id)
return thing;
}
return null;
}
Have you tried: getElementbyId('ID_OF_ID').innerHTML
?
As of Ruby 2.5 you can use delete_prefix
or delete_prefix!
to achieve this in a readable manner.
In this case "[12,23,987,43".delete_prefix("[")
.
More info here:
'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"
N.B. you can also use this to remove items from the end of a string with delete_suffix
and delete_suffix!
'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"
Edit:
Using the Tin Man's benchmark setup, it looks pretty quick too (under the last two entries delete_p
and delete_p!
). Doesn't quite pip the previous faves for speed, though is very readable.
2.5.0
user system total real
[0] 0.174766 0.000489 0.175255 ( 0.180207)
[/^./] 0.318038 0.000510 0.318548 ( 0.323679)
[/^\[/] 0.372645 0.001134 0.373779 ( 0.379029)
sub+ 0.460295 0.001510 0.461805 ( 0.467279)
sub 0.498351 0.001534 0.499885 ( 0.505729)
gsub 1.669837 0.005141 1.674978 ( 1.682853)
[1..-1] 0.199840 0.000976 0.200816 ( 0.205889)
slice 0.279661 0.000859 0.280520 ( 0.285661)
length 0.268362 0.000310 0.268672 ( 0.273829)
eat! 0.341715 0.000524 0.342239 ( 0.347097)
reverse 0.335301 0.000588 0.335889 ( 0.340965)
delete_p 0.222297 0.000832 0.223129 ( 0.228455)
delete_p! 0.225798 0.000747 0.226545 ( 0.231745)
WindowsPowershell:
option 1
ping.exe -t COMPUTERNAME|Foreach{"{0} - {1}" -f (Get-Date),$_}
option 2
Test-Connection -Count 9999 -ComputerName COMPUTERNAME | Format-Table @{Name='TimeStamp';Expression={Get-Date}},Address,ProtocolAddress,ResponseTime
I used RenderAction html helper for razor in layout.
@{
Html.RenderAction("Action", "Controller");
}
I needed it for simple string. So my action returns string and writes it down easy in view. But if you need complex data you can return PartialViewResult and model.
public PartialViewResult Action()
{
var model = someList;
return PartialView("~/Views/Shared/_maPartialView.cshtml", model);
}
You just need to put your model begining of the partial view '_maPartialView.cshtml' that you created
@model List<WhatEverYourObjeIs>
Then you can use data in the model in that partial view with html.
If you want to pass variables from the current function, another way to do this is, for example:
document.getElementById("space1").onclick = new Function("lrgWithInfo('"+myVar+"')");
If you don't need to pass information from this function, it's just:
document.getElementById("space1").onclick = new Function("lrgWithInfo('13')");
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL;
and $_POST['x'] = '';
isset($_POST['x'])
will return false
on the first example, but will return true
on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST
is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
Installing requirements.txt file inside virtual env with Python 3:
I had the same issue. I was trying to install the requirements.txt file inside a virtual environment. I found the solution.
Initially, I created my virtualenv in this way:
virtualenv -p python3 myenv
Activate the environment using:
source myenv/bin/activate
Now I installed the requirements.txt file using:
pip3 install -r requirements.txt
Installation was successful and I was able to import the modules.
Which one of those is indexable?
This one is definitely btree-indexable:
WHERE title >= '0' AND title < ':'
Note that ':' comes after '9' in ASCII.
This works in MSSQL and MySQL:
SELECT *
FROM Village
WHERE CastleType LIKE '%foo%';
this.element.attr("id")
works fine in IE8.
Model–View–Controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted by the user. Following the MVC architectural pattern decouples these major components allowing for code reuse and parallel development.
Traditionally used for desktop graphical user interfaces (GUIs), this pattern has become popular for designing web applications. Popular programming languages like JavaScript, Python, Ruby, PHP, Java, and C# have MVC frameworks that are used in web application development straight out of the box.
Model
The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic, and rules of the application.
View
Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
Controller
Accepts input and converts it to commands for the model or view.
In addition to dividing the application into these components, the model–view–controller design defines the interactions between them.
The model is responsible for managing the data of the application. It receives user input from the controller.
The view means a presentation of the model in a particular format.
The controller responds to the user input and performs interactions on the data model objects. The controller receives the input, optionally validates it and then passes the input to the model.
Model–View–ViewModel (MVVM) is a software architectural pattern.
MVVM facilitates a separation of development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the data model). The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than a view and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.
MVVM is a variation of Martin Fowler's Presentation Model design pattern. MVVM abstracts a view's state and behavior in the same way, but a Presentation Model abstracts a view (creates a view model) in a manner not dependent on a specific user-interface platform.
MVVM was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces. The pattern was incorporated into Windows Presentation Foundation (WPF) (Microsoft's .NET graphics system) and Silverlight (WPF's Internet application derivative). John Gossman, one of Microsoft's WPF and Silverlight architects, announced MVVM on his blog in 2005.
Model–View–ViewModel is also referred to as model–view–binder, especially in implementations not involving the .NET platform. ZK (a web application framework written in Java) and KnockoutJS (a JavaScript library) use model–view–binder.
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
I had similar issue. I was not able to use value="something"
to display and edit.
I had to use the below command inside my <input>
along withe ng model being declared.
[(ngModel)]=userDataToPass.pinCode
Where I have the list of data in the object userDataToPass
and the item that I need to display and edit is pinCode
.
For the same , I referred to this YouTube video
There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.
Fortunately, there's simple answers to both. First case, you want to use zip
.
x = [1, 2, 3]
y = [4, 5, 6]
for i, j in zip(x, y):
print(str(i) + " / " + str(j))
will output
1 / 4
2 / 5
3 / 6
Remember that you can put any iterable in zip
, so you could just as easily write your exmple like:
for i, j in zip(range(x), range(y)):
# do work here.
Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.
In the other case, you just want a nested loop.
for i in x:
for j in y:
print(str(i) + " / " + str(j))
gives you
1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...
You can also do this as a list comprehension.
[str(i) + " / " + str(j) for i in range(x) for j in range(y)]
Hope that helps.
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
This was good enough for me
sudo /etc/init.d/mysql restart
use for loop. like this:
for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
new_list.append(my_list[i + x])
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
For anyone who ran into the same problem I did (can't detach without killing the container, even when setting the detach key)......
When starting your containers with docker-compose up -d
instead of using docker attach {container name}
to view the tailing log ....
try docker-compose logs -f {service name}
ctrl-c kills the log tail without killing your container
{service name}
being the service listed in side of your docker-compose.yml file.. (e.g. while container name=elk_logstash_1 -> service name=logstash
HTH
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
From my testing Write-Output and [Console]::WriteLine() perform much better than Write-Host.
Depending on how much text you need to write out this may be important.
Below if the result of 5 tests each for Write-Host, Write-Output and [Console]::WriteLine().
In my limited experience, I've found when working with any sort of real world data I need to abandon the cmdlets and go straight for the lower level commands to get any decent performance out of my scripts.
measure-command {$count = 0; while ($count -lt 1000) { Write-Host "hello"; $count++ }}
1312ms
1651ms
1909ms
1685ms
1788ms
measure-command { $count = 0; while ($count -lt 1000) { Write-Output "hello"; $count++ }}
97ms
105ms
94ms
105ms
98ms
measure-command { $count = 0; while ($count -lt 1000) { [console]::WriteLine("hello"); $count++ }}
158ms
105ms
124ms
99ms
95ms
I recently created a library for creating Gson objects fluently:
It works like this:
JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
.addNull("nullKey") //1. Add a null to the object
.add("stringKey", "Hello") //2. Add a string to the object
.add("stringNullKey", (String) null) //3. Add a null string to the object
.add("numberKey", 2) //4. Add a number to the object
.add("numberNullKey", (Float) null) //5. Add a null number to the object
.add("booleanKey", true) //6. Add a boolean to the object
.add("booleanNullKey", (Boolean) null) //7. Add a null boolean to the object
.add("characterKey", 'c') //8. Add a character to the object
.add("characterNullKey", (Character) null) //9. Add a null character to the object
.addObject("objKey") //10. Add a nested object
.add("nestedPropertyKey", 4) //11. Add a nested property to the nested object
.end() //12. End nested object and return to the parent builder
.addArray("arrayKey") //13. Add an array to the object
.addObject() //14. Add a nested object to the array
.end() //15. End the nested object
.add("arrayElement") //16. Add a string to the array
.end() //17. End the array
.getJson(); //Get the JsonObject
String json = jsonObject.toString();
And through the magic of generics it generates compile errors if you try to add an element to an array with a property key or an element to an object without a property name:
JsonObject jsonArray = JsonBuilderFactory.buildArray().addObject().end().add("foo", "bar").getJson(); //Error: tried to add a string with property key to array.
JsonObject jsonObject = JsonBuilderFactory.buildObject().addArray().end().add("foo").getJson(); //Error: tried to add a string without property key to an object.
JsonArray jsonArray = JsonBuilderFactory.buildObject().addArray("foo").getJson(); //Error: tried to assign an object to an array.
JsonObject jsonObject = JsonBuilderFactory.buildArray().addObject().getJson(); //Error: tried to assign an object to an array.
Lastly there is mapping support in the API which allows you to map your domain objects to JSON. The goal being when Java8 is released you'll be able to do something like this:
Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
.add("userName", u.getName())
.add("ageInYears", u.getAge()) })
.getJson();
If you're trying to get access to a file, try the openFileOutput()
and openFileInput()
methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File
objects altogether which is a pretty clean solution.
Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic
Nonatomic means multiple thread can access the item .It is thread unsafe
So one should be very careful while using atomic .As it affect the performance of your code
Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)
If you use the gradle-android-plugin to build your app, then you can use
BuildConfig.APPLICATION_ID
to retrieve the package name from any scope, incl. a static one.
You have to make the UL
inside the div
behave like a block. Try adding
.navigation ul {
display: inline-block;
}
Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.
or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.
In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good
Try below code :
public static void main(String[] args) throws Exception{
List<String> l = new ArrayList<String>();
l.add("abc");
l.add("xyz");
l.add("test");
l.add("test123");
System.out.println(l);
List<String> dl = new ArrayList<String>();
for (int i = 0; i < l.size(); i++) {
String a = l.get(i);
System.out.println(a);
if(a.equals("test")){
dl.add(a);
}
}
l.removeAll(dl);
System.out.println(l);
}
your output :
[abc, xyz, test, test123]
abc
xyz
test
test123
[abc, xyz, test123]
Marc's answer is good (I'd comment on it if I could work out how to!)
Just thought I'd point out that it may be better to change the loop so the SELECT
only exists once (in a real case where I needed to do this, the SELECT
was quite complex, and writing it twice was a risky maintenance issue).
-- define the last customer ID handled
DECLARE @LastCustomerID INT
SET @LastCustomerID = 0
-- define the customer ID to be handled now
DECLARE @CustomerIDToHandle INT
SET @CustomerIDToHandle = 1
-- as long as we have customers......
WHILE @LastCustomerID <> @CustomerIDToHandle
BEGIN
SET @LastCustomerId = @CustomerIDToHandle
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = CustomerID
FROM Sales.Customer
WHERE CustomerID > @LastCustomerId
ORDER BY CustomerID
IF @CustomerIDToHandle <> @LastCustomerID
BEGIN
-- call your sproc
END
END
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.
On my machine in a repo I regularly use it looks like this:
KidA% cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
autocflg = true
[remote "origin"]
url = ssh://localhost:8888/opt/local/var/git/project.git
#url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.
This is the file that is getting manipulated under-the-hood when you run something like git remote rm
or git remote add
but in this case since its only a typo you made it might make sense to correct it this way.
This question is old but here is another answer because it is useful fo others:
thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
The above function waits for a specific time without freezing the software, however increases the CPU usage.
This function not only doesn't freeze the software, but also doesn't increase the CPU usage:
Private Sub wait(ByVal seconds As Integer)
For i As Integer = 0 To seconds * 100
System.Threading.Thread.Sleep(10)
Application.DoEvents()
Next
End Sub
another option ... needs remoting ...
(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version
If you'r using LINUX, first let's check apache's user, since in some distros it can be different:
egrep -i '^user|^group' /etc/httpd/conf/httpd.conf
Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:
chown -R http:http path_to_folder
chmod -R g+rw path_to_folder
Gitg is a great tool for Linux, similar to Gitx for OS X. Just run 'gitg' on the command line from somewhere inside your repository's tree structure (same with gitx).
Simple example for compareAndSet() function:
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val = new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res = val.compareAndSet(0, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was"
+ " updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
The printed is: previous value: 0 The value was updated and it is 6 Another simple example:
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res = val.compareAndSet(10, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was"
+ " updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
The printed is: Previous value: 0 The value was not updated
In YUI, if you include yuidom, you can use
YAHOO.util.Dom.addClass('div1','className');
HTH
On iOS 12 the accepted answer seems to be broken. I had it working with the following extension
import UIKit
extension UITableView {
public func scrollToBottom(animated: Bool = true) {
guard let dataSource = dataSource else {
return
}
let sections = dataSource.numberOfSections?(in: self) ?? 1
let rows = dataSource.tableView(self, numberOfRowsInSection: sections-1)
let bottomIndex = IndexPath(item: rows - 1, section: sections - 1)
scrollToRow(at: bottomIndex,
at: .bottom,
animated: animated)
}
}
You use ROWNUM.
ie.
SELECT user FROM Dual WHERE ROWNUM = 1
http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm
I'm thinking that in contrary to C or any language with pointers :
/** Javascript **/
var o = {x:10,y:20};
var o2 = {z:50,w:200};
.
o == o2 // obviously false : not the same address in memory
o <= o2 // true !
o >= o2 // also true !!
that's a huge problem :
it means that you can list/manage every objects created (allocated) by your application,
from that huge list of objects, compute some information about these (how they are linked together for example)
but when you want to retrieve the information you created about a specific object, you cannot find it in your huge list by dichotomy : there is no unique identifier per object that could be used as a replacement of the real memory address
this finally means that this is a huge problem, if you want to write in javascript :
This will make sure that the SpringBoot application is closed properly and the resources are released back to the operating system,
@Autowired
private ApplicationContext context;
@GetMapping("/shutdown-app")
public void shutdownApp() {
int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
System.exit(exitCode);
}
A simpler solution nowadays would be to use your shape as a background and then programmatically change its color via:
view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)
See PorterDuff.Mode for the available options.
UPDATE (API 29):
The above method is deprecated since API 29 and replaced by the following:
view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)
See BlendMode for the available options.
Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:
Application.StartupPath
returns the StartupPath
parameter (can be set when run the application)
System.IO.Directory.GetCurrentDirectory()
returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory
. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).
As @impulsgraw wrote. You need to check for undefined after the pipes:
<div ng-show="foo || undefined">
Show this if foo is defined!
</div>
<div ng-show="boo || !undefined">
Show this if boo is undefined!
</div>
You must feed the DOMDocument a version of your HTML with a header that make sense. Just like HTML5.
$profile ='<?xml version="1.0" encoding="'.$_encoding.'"?>'. $html;
maybe is a good idea to keep your html as valid as you can, so you don't get into issues when you'll start query... around :-) and stay away from htmlentities
!!!! That's an an necessary back and forth wasting resources.
keep your code insane!!!!
In angular 4+ we can use innerHTML
property instead of ng-bind-html
.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';
For me, the HTML Prettify
solution was extremely simple. I went to the HTML Prettify page.
Sublime Package Manager
prettify
HTML prettify
selection in the menuBoom. Done. Looks great
Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.
If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:
I'm using iteritems(
) since you tagged your question with python-2.7
results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])
Now the result will be in a list with some_function
applied to each key/value pair of the dictionary, that has foo
in its key.
If you just want to deal with the values and ignore the keys, just change the list comprehension:
results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])
some_function
can be any callable, so a lambda would work as well:
results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])
The inner list is actually not required, as you can pass a generator expression to map as well:
>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]
Bundler allows you to use gems directly from git repositories. In your Gemfile:
# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'
# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'
# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'
For more info, see https://bundler.io/v2.0/guides/git.html
Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.
Correct.
Client has a read timeout set, and server is taking longer than that to respond.
No. That would cause a timeout at the client.
One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.
That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.
It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.
An alternative way is to convert the df to a matrix then applying the list apply lappy
function over it: ldf <- lapply(as.matrix(myDF), function(x)x)
I dump my output to a text file. I then open it in notepad ++ then click the show all characters button. Not very elegant but it works.
cd /usr/local/tomcat/logs
tail -f catalina.out
SELECT convert(varchar(7), getdate(), 126)
You might wanna check out this website: http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
When you use float without width, there remains some space in that row. To block this space you can use clear:both;
in next element.
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
Remove the data attribute as you are not POSTING
anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor
and use @Url.Action
rather than a static string:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
Place the link location in the action=""
of a wrapping form
tag.
Your first link would be:
<form action="1.html">
<input type="submit" class="button_active" value="1">
</form>
I just had this issue, and was able to work around it.
First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.
Run these queries:
SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');
In your PHP script, change your mysql_connect function to include the client flag 1:
define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);
This allowed me to connect successfully.
Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!
Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:
<?php const DB = [ 'host' => '...', # localhost may not work on some hosting
'user' => '...',
'pwd' => '...', ];
if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
die($query);
}
echo "Excellent, mysqli will now work";
?>
In case you cannot rely on flexbox... Place .child
into .parent
's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too.
.parent { position: relative; }_x000D_
_x000D_
.child {_x000D_
position: absolute;_x000D_
top : 50%;_x000D_
left: 50%;_x000D_
-ms-transform: translate(-50%, -50%);_x000D_
transform : translate(-50%, -50%); _x000D_
}
_x000D_
<div class="parent" style="background:lightyellow; padding:6em"> _x000D_
<div class="child" style="background:gold; padding:1em">—</div> _x000D_
</div>
_x000D_
As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.
SecureRandom sr = SecureRandom.getInstanceStrong();
byte[] salt = new byte[16];
sr.nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
Cipher aes = Cipher.getInstance("AES");
aes.init(Cipher.ENCRYPT_MODE, key);
===========
You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).
Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.
byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"
For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"
1) The best way is to set static folder. In your main file (app.js | server.js | ???):
app.use(express.static(path.join(__dirname, 'public')));
public/css/form.html
public/css/style.css
Then you got static file from "public" folder:
http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css
2)
You can create your file cache.
Use method fs.readFileSync
var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');
app.get('/', function(req, res){
res.setHeader('Content-Type', 'text/html');
res.send( cache["index.html"] );
};);
If you want to remove or unset all $_SESSION 's then try this
session_destroy();
If you want to remove specific $_SESSION['name'] then try this
session_unset('name');
The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).
Here is an example of how to set up a test for sorting:
>>> import timeit
>>> setup = '''
import random
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''
>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145
Note that the series of statements makes a fresh copy of the unsorted data on every pass.
Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.
Those are my tips for using timeit correctly. Hope this helps :-)
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
This is the commandline for removing plugins in Cordova
cordova plugin remove <pluginid>
For example I ran cordova plugin
and got a list of plugins then I used the id for the plugin to uninstall
cordova plugin remove com.monday.contact-chooser
You can get help in the commandline by typing
cordova help <command>
NOTE: This answer addresses enterprise-class development in-the-large.
This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.
In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.
Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.
The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.
I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
You can actualy fake the transparency of option
DOMElements with the following CSS:
option {
/* Whatever color you want */
background-color: #82caff;
}
The option
tag does not support rgba
colors yet.
If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564
require 'faraday'
require 'faraday_middleware'
require 'json'
# Debug:
# require "pry"
country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")
currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash
dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')
puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
I think what you are looking for is as follows.
cars_by_cylinders_gears <- mtcars %>%
group_by(cyl, gear) %>%
summarise(count = n())
This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.
find $directory -type f -name "*.in"
is a bit shorter than that whole thing (and safer - deals with whitespace in filenames and directory names).
Your script is probably failing for entries that don't have a .
in their name, making $extension
empty.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
First thing that pop-up in google results http://think2loud.com/224-reading-xml-with-jquery/ There's no simple way to access xml structure (like you described Pages->pagename->controls->test) in jQuery without any plugins.
If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.
set JAVA_HOME=C:\Program Files\Java\jdk1.6.x
If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.
JAVA_HOME=/usr/java/jdk1.6.x
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));
With the Material Components Library you can use the MaterialShapeDrawable
.
<TextView
android:id="@+id/textview"
.../>
Then you can programmatically apply a MaterialShapeDrawable
:
TextView textView = findViewById(R.id.textview);
MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable();
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,android.R.color.transparent));
shapeDrawable.setStroke(1.0f, ContextCompat.getColor(this,R.color....));
ViewCompat.setBackground(textView,shapeDrawable);
You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
span {
font-size:12px;
}
a {
color:green;
}
.test1>a:hover span {
display:none;
}
.test1>a:hover:before {
color:red;
content:"Apple";
}
</style>
</head>
<body>
<div class="test1">
<a href="#"><span>Google</span></a>
</div>
<div class="test2">
<a href="#"><span>Apple</span></a>
</div>
</body>
</html>
Note: The hover:before switch works only on the .test1 class
We tried Set instead of List and it is a nightmare: when you add two new objects, equals() and hashCode() fail to distinguish both of them ! Because they don't have any id.
typical tools like Eclipse generate that kind of code from Database tables:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
You may also read this article that explains properly how messed up JPA/Hibernate is. After reading this, I think this is the last time I use any ORM in my life.
I've also encounter Domain Driven Design guys that basically say ORM are a terrible thing.
Using TypedArray.from:
Uint8Array.from(atob(base64_string), c => c.charCodeAt(0))
Performance to be compared with the for loop version of Goran.it answer.
Your here:
<a href="#"><img src="img.jpg" /></a>
Css Gray:
img{
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: gray; /* IE6-9 */
-webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */}
Ungray:
a:hover img{
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
filter: grayscale(0%);
-moz-filter: grayscale(0%);
-ms-filter: grayscale(0%);
-o-filter: grayscale(0%);
filter: none ; /* IE6-9 */
zoom:1; /* needed to trigger "hasLayout" in IE if no width or height is set */
-webkit-filter: grayscale(0%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */
}
I found it at: http://zkiwi.com/topic/chuyen-hinh-mau-thanh-trang-den-bang-css-nhu-the-nao
Edit: IE10+ does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter. You can fix it, use one in two solutions below:
<meta http-equiv="X-UA-Compatible" content="IE=9">
download rpm packages and run the following command:
rpm -Uvh glibc-2.15-60.el6.x86_64.rpm \
glibc-common-2.15-60.el6.x86_64.rpm \
glibc-devel-2.15-60.el6.x86_64.rpm \
glibc-headers-2.15-60.el6.x86_64.rpm
If you want to use justify align in Jupyter Notebook use the following syntax:
<p style='text-align: justify;'> Your Text </p>
For right alignment:
<p style='text-align: right;'> Your Text </p>
For me it was different, I used a button theme
<style name="ButtonLight_pink" parent="android:Widget.Button">
<item name="android:background">@drawable/light_pink_btn_default_holo_light</item>
<item name="android:minHeight">48dip</item>
<item name="android:minWidth">64dip</item>
<item name="android:textColor">@color/tab_background_light_pink</item>
</style>
and because android:textColor
was white there… I didn't see any button text (Dialog buttons are basically buttons too).
There we go, changed it, fixed it.
I am working on a program that saves its data properly to %APPDATA%, but sometimes, there are system-wide settings that affect all users. So in these situations, it HAS to write to the programs installation directory.
And as far as I have read now, it's impossible to temporarily get write access to one directory. You can only run the whole application as administrator (which should be out of the question) or not be able to save that file. (all or nothing)
I guess, I will just write the file to %APPDATA% and launch an external program that copies the file into the installation folder and have THAT program demand admin privileges... dumb idea, but seems to be the only practical solution...
You just need to provide an alias for your aggregate columns in the CTE
d as (SELECT
duration,
sum(totalitems) as sumtotalitems
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
)
You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF
package main
import "fmt"
func main() {
testLine := `This is a test line 1
This is a test line 2`
fmt.Println(testLine)
}
List<List> list = map.values().stream().collect(Collectors.toList());
List<Employee> employees2 = new ArrayList<>();
list.stream().forEach(
n-> employees2.addAll(n));
Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.
Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.
var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];
My environment are:
pip install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl
works for me.
import MySQLdb, sys
# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
print ("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit()
# Creating cursor
cursor = db.cursor()
There are two ways in which this can be accomplished using vanilla javascript. The first is className
and the second is classList
. className
works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList
is an easier way to modify an element's class(es).
To outright set an element's class attribute, className
is the way to go, otherwise to modify an element's class(es), it's easier to use classList
.
Initial Html
<div id="ID"></div>
Setting the class attribute
var div = document.getElementById('ID');
div.className = "foo bar car";
Result:
<div id="ID" class="foo bar car"></div>
Adding a class
div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");
Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:
<div id="ID" class="foo bar car tar"></div>
Removing a class
div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens
Note: Just like add
, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:
<div id="ID" class="foo bar"></div>
Checking if a class attribute contains a specific class
if (div.classList.contains("foo")) {
// Do stuff
}
Toggling a class
var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed
classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added
.toggle
has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.
For more information on classList
, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.
Note: The linked Jenkins issue has since been solved.
As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:
sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available
Original
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap"/>
</basicHttpBinding>
</bindings>
After Edit/Update
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/
It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager
database role
I used this and Stuart's answer to do the following:
On the master
database (see link as to who has permissions on this):
CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'
And then on the database in question:
CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]
You can also create users like this, according to the link:
CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;
I have been battling this problem for a couple of days trying all kinds of things suggested. My dev machine was working fine, but the new machine I was deploying to was giving me the 404 error.
In IIS manager, I compared the handler mappings on both machines to realize that a lot of handlers were missing. Turns out that ASP.Net 5 was not installed on the machine.
from Python version 2.6 you can do this:
def format_builtin(n):
return format(n, ',')
For Python versions < 2.6 and just for your information, here are 2 manual solutions, they turn floats to ints but negative numbers work correctly:
def format_number_using_lists(number):
string = '%d' % number
result_list = list(string)
indexes = range(len(string))
for index in indexes[::-3][1:]:
if result_list[index] != '-':
result_list.insert(index+1, ',')
return ''.join(result_list)
few things to notice here:
And a more hardcore version:
def format_number_using_generators_and_list_comprehensions(number):
string = '%d' % number
generator = reversed(
[
value+',' if (index!=0 and value!='-' and index%3==0) else value
for index,value in enumerate(reversed(string))
]
)
return ''.join(generator)
Instructions for Drupal 8 / FontAwesome 5
Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)
Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
}
?>
Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.
Make sure you import FontAwesome, add this at the top of the CSS file
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
then add this in the CSS
input#edit-submit {
font-family: 'Font Awesome\ 5 Free';
background-color: transparent;
border: 0;
}
FLUSH ALL CACHES AND IT SHOULD WORK FINE
Add Google Font Effects
If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
$form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>
For 2 use cases:
grep -m 2
is per file max occurrence. git grep
which doesn't take -m
A good alternative in these scenarios is grep | sed 2q
to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
You can 'learn' the size of the array automatically:
template<typename T, size_t N>
void set_data(const T (&w)[N]){
w_.assign(w, w+N);
}
Hopefully, you can change the interface to set_data as above. It still accepts a C-style array as its first argument. It just happens to take it by reference.
How it works
[ Update: See here for a more comprehensive discussion on learning the size ]
Here is a more general solution:
template<typename T, size_t N>
void copy_from_array(vector<T> &target_vector, const T (&source_array)[N]) {
target_vector.assign(source_array, source_array+N);
}
This works because the array is being passed as a reference-to-an-array. In C/C++, you cannot pass an array as a function, instead it will decay to a pointer and you lose the size. But in C++, you can pass a reference to the array.
Passing an array by reference requires the types to match up exactly. The size of an array is part of its type. This means we can use the template parameter N to learn the size for us.
It might be even simpler to have this function which returns a vector. With appropriate compiler optimizations in effect, this should be faster than it looks.
template<typename T, size_t N>
vector<T> convert_array_to_vector(const T (&source_array)[N]) {
return vector<T>(source_array, source_array+N);
}
The canonical solution is the one mentioned by another respondent:
sort | uniq -c
It is shorter and more concise than what can be written in Perl or awk.
You write that you don't want to use sort, because the data's size is larger than the machine's main memory size. Don't underestimate the implementation quality of the Unix sort command. Sort was used to handle very large volumes of data (think the original AT&T's billing data) on machines with 128k (that's 131,072 bytes) of memory (PDP-11). When sort encounters more data than a preset limit (often tuned close to the size of the machine's main memory) it sorts the data it has read in main memory and writes it into a temporary file. It then repeats the action with the next chunks of data. Finally, it performs a merge sort on those intermediate files. This allows sort to work on data many times larger than the machine's main memory.
Try this
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
This article by Atul Gupta has sample code that covers several scenarios:
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
As Knu said, you can use this tool, however it's compiled only for MS-DOS. I compiled it for Win64. Download.
Usage:
Place the .exe in the same folder as the font you need to modify
Navigate to that directory in the command line
type embed fontname.fonttype
, replacing fontname with the filename and fonttype with the extension i.e. embed brokenFont.ttf
All done! Your font should now work.
Suppose you declared HashMap as :-
HashMap<Character,Integer> hs = new HashMap<>();
Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-
char temp = 'a';
if(hs.containsKey(temp)){
` int val = hs.get(temp); //val is the value corresponding to key temp
}
So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.
You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
var newvalue = $(this).val();
});
$('#myInputElement').blur(function(){
$('#myHiddenInput').val($(this).val());
});
});
</script>
<input id="myInputElement" type="text">
(untested, but it should work).
It is a security issue, so to fix it simply do the following:
If you know the target paper size, you can place your content in a DIV with that specific size and add a margin to that DIV to simulate the print margin. Unfortunately, I don't believe you have extra control over the print functionality apart from just show the print dialog box.
Use this query:
ALTER TABLE tablename ADD columname DATATYPE(size);
And here is an example:
ALTER TABLE Customer ADD LastName VARCHAR(50);
Standard C99:
#include <time.h>
time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;
clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;
The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.
What about this solution? It does not rely on knowledge of @staticmethod
decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.
class Klass(object):
class StaticMethod:
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = StaticMethod._stat_func() # call the staticmethod
def method(self):
ret = self.StaticMethod._stat_func() + Klass._ANS
return ret
You're passing in a pointer *random
but you're using it like a reference &random
The pointer (what you have) says "This is the address in memory that contains the address of random"
The reference says "This is the address of random"
My solution:
String.prototype.toCapital = function () {
return this.toLowerCase().split(' ').map(function (i) {
if (i.length > 2) {
return i.charAt(0).toUpperCase() + i.substr(1);
}
return i;
}).join(' ');
};
Example:
'álL riGht'.toCapital();
// Returns 'Áll Right'
I've got a lot of sympathy with your question, as I'm in an almost identical position myself. I appreciate what a lot of the replies are saying, and they are correct - the routine supplying the pointer should be providing a valid pointer. In my case, it is almost inconceivable that they could have corrupted the pointer - but if they had managed, it would be MY software that crashes, and ME that would get the blame :-(
My requirement isn't that I continue after a segmentation fault - that would be dangerous - I just want to report what happened to the customer before terminating so that they can fix their code rather than blaming me!
This is how I've found to do it (on Windows): http://www.cplusplus.com/reference/clibrary/csignal/signal/
To give a synopsis:
#include <signal.h>
using namespace std;
void terminate(int param)
/// Function executed if a segmentation fault is encountered during the cast to an instance.
{
cerr << "\nThe function received a corrupted reference - please check the user-supplied dll.\n";
cerr << "Terminating program...\n";
exit(1);
}
...
void MyFunction()
{
void (*previous_sigsegv_function)(int);
previous_sigsegv_function = signal(SIGSEGV, terminate);
<-- insert risky stuff here -->
signal(SIGSEGV, previous_sigsegv_function);
}
Now this appears to behave as I would hope (it prints the error message, then terminates the program) - but if someone can spot a flaw, please let me know!
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
Add a WHERE
clause
UPDATE dbo.TestStudents
SET LASTNAME = CASE
WHEN LASTNAME = 'AAA' THEN 'BBB'
WHEN LASTNAME = 'CCC' THEN 'DDD'
WHEN LASTNAME = 'EEE' THEN 'FFF'
ELSE LASTNAME
END
WHERE LASTNAME IN ('AAA', 'CCC', 'EEE')
If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.
Steps to create:
Good thing about this solution:
Not so good thing about this solution:
Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq
<button class="btn btn--animation-from-right">
<span class="btn__text-static">Cover left</span>
<div class="btn__text-dynamic">
<span class="btn__text-dynamic-inner">Cover left</span>
</div>
</button>
.btn {
padding: 10px 20px;
position: relative;
border: 2px solid #222;
color: #fff;
background-color: #222;
position: relative;
overflow: hidden;
cursor: pointer;
text-transform: uppercase;
font-family: monospace;
letter-spacing: -1px;
[class^="btn__text"] {
font-size: 24px;
}
.btn__text-dynamic,
.btn__text-dynamic-inner {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index: 2;
transition: all ease 0.5s;
}
.btn__text-dynamic {
background-color: #fff;
color: #222;
overflow: hidden;
}
&:hover {
.btn__text-dynamic {
transform: translateX(-100%);
}
.btn__text-dynamic-inner {
transform: translateX(100%);
}
}
}
.btn--animation-from-right {
&:hover {
.btn__text-dynamic {
transform: translateX(100%);
}
.btn__text-dynamic-inner {
transform: translateX(-100%);
}
}
}
You can remove .btn--animation-from-right modifier if you want to animate to the left.
I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.
I was able to get around the problem by using visibility
instead of display
. This works for me because my child element is position: absolute
, so document flow isn't being affected. It might work for others too.
This is what the original code would look like using my solution:
.child {
position: absolute;
opacity: 0;
visibility: hidden;
-webkit-transition: opacity 0.5s ease-in-out;
-moz-transition: opacity 0.5s ease-in-out;
transition: opacity 0.5s ease-in-out;
}
.parent:hover .child {
position: relative;
opacity: 0.9;
visibility: visible;
}
If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->
$searchResultQuery = Users::query();
$searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
$searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null
Or with scope in model :
public function scopeNotNullOnly($query){
return $query->where('status_message', '<>', '');
}
** Used table to align the radio and text in one line
<div >_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td><strong>Do you want to add new server ?</strong></td>_x000D_
<td><input type="radio" name="addServer" id="serverYes" value="1"></td>_x000D_
<td>Yes</td>_x000D_
<td><input type="radio" name="addServer" id="serverNo" value="1"></td>_x000D_
<td>No</td>_x000D_
_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
**
These both work for me in JavaScript and TypeScript
<img src="@/assets/images/logo.png" alt="">
or
<img src="./assets/images/logo.png" alt="">
mysqldump -h [host] -p -u [user] [database name] > filename.sql
Example in localhost
mysqldump -h localhost -p -u root cookbook > cookbook.sql
Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*
Worked after I added .conf
to the configuration file
What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).
This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id
on a OneToOne
or ManyToOne
. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn
and also define a Basic
Id
mapping for the foreign key column.
Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?
You can obtain a similar result but using an Id
on OneToOne
or ManyToOne
is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn
might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:
11.1.40 PrimaryKeyJoinColumn Annotation
The
PrimaryKeyJoinColumn
annotation specifies a primary key column that is used as a foreign key to join to another table.The
PrimaryKeyJoinColumn
annotation is used to join the primary table of an entity subclass in theJOINED
mapping strategy to the primary table of its superclass; it is used within aSecondaryTable
annotation to join a secondary table to a primary table; and it may be used in aOneToOne
mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108]....
If no
PrimaryKeyJoinColumn
annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass....
Example: Customer and ValuedCustomer subclass
@Entity @Table(name="CUST") @Inheritance(strategy=JOINED) @DiscriminatorValue("CUST") public class Customer { ... } @Entity @Table(name="VCUST") @DiscriminatorValue("VCUST") @PrimaryKeyJoinColumn(name="CUST_ID") public class ValuedCustomer extends Customer { ... }
[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over
PrimaryKeyJoinColumn
for the OneToOne mapping case.
This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?
The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.
For the record, support of Id
on OneToOne
and ManyToOne
has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.
For ssh style urls just add ssh before the url:
yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>