Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works
>>>fun(input)
output
Good, that works, now import timeit and set up a timer
>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>
Now we have our timer set up we can see how long it takes
>>>t.timeit(number=1)
some number here
And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.
I hope this helps.
If you have cygwin installed, from it's bash shell, run your executable, say MyProgram
, using the time
utility, like so:
/usr/bin/time ./MyProgram
This will report how long the execution of your program took -- the output would look something like the following:
real 0m0.792s
user 0m0.046s
sys 0m0.218s
You could also manually modify your C program to instrument it using the clock()
library function, like so:
#include <time.h>
int main(void) {
clock_t tStart = clock();
/* Do your stuff here */
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
Use a Profiler
Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.
The advantages they have is:
There are many available open-source as well.
I really like Paul McGuire's answer, but I use Python 3. So for those who are interested: here's a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that clock()
should be used instead of time()
):
#python3
import atexit
from time import time, strftime, localtime
from datetime import timedelta
def secondsToStr(elapsed=None):
if elapsed is None:
return strftime("%Y-%m-%d %H:%M:%S", localtime())
else:
return str(timedelta(seconds=elapsed))
def log(s, elapsed=None):
line = "="*40
print(line)
print(secondsToStr(), '-', s)
if elapsed:
print("Elapsed time:", elapsed)
print(line)
print()
def endlog():
end = time()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
start = time()
atexit.register(endlog)
log("Start Program")
If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).
If using Cpanel/WHM the location of file config.default.php
is under
/usr/local/cpanel/base/3rdparty/phpMyAdmin/libraries
and you should change the $cfg['ExecTimeLimit'] = 300;
to $cfg['ExecTimeLimit'] = 0;
Changing php.ini
for a web application requires restarting Apache.
You should verify that the change took place by running a PHP script that executes the function phpinfo()
. The output of that function will tell you a lot of PHP parameters, including the timeout value.
You might also have changed a copy of php.ini
that is not the same file used by Apache.
use below statement if safe_mode
is off
set_time_limit(0);
Just a small twist, if you don't use tooling and want to time methods with low execution time: execute it many times, each time doubling the number of times it is executed until you reach a second, or so. Thus, the time of the Call to System.nanoTime and so forth, nor the accuracy of System.nanoTime does affect the result much.
int runs = 0, runsPerRound = 10;
long begin = System.nanoTime(), end;
do {
for (int i=0; i<runsPerRound; ++i) timedMethod();
end = System.nanoTime();
runs += runsPerRound;
runsPerRound *= 2;
} while (runs < Integer.MAX_VALUE / 2 && 1000000000L > end - begin);
System.out.println("Time for timedMethod() is " +
0.000000001 * (end-begin) / runs + " seconds");
Of course, the caveats about using the wall clock apply: influences of JIT-compilation, multiple threads / processes etc. Thus, you need to first execute the method a lot of times first, such that the JIT compiler does its work, and then repeat this test multiple times and take the lowest execution time.
If your application theme is AppTheme(or anything else), then in styles.xml add the following code:
<style name="HiddenTitleTheme" parent="AppTheme">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
Then in manifest file add the following in the activity tag for which you want to disable activity label:
android:theme="@style/HiddenTitleTheme"
A Relation object passes unknown method calls through to an Eloquent query Builder, which is set up to only select the related objects. That Builder in turn passes unknown method calls through to its underlying query Builder.
This means you can use the exists()
or count()
methods directly from a relation object:
$model->relation()->exists(); // bool: true if there is at least one row
$model->relation()->count(); // int: number of related rows
Note the parentheses after relation
: ->relation()
is a function call (getting the relation object), as opposed to ->relation
which a magic property getter set up for you by Laravel (getting the related object/objects).
Using the count
method on the relation object (that is, using the parentheses) will be much faster than doing $model->relation->count()
or count($model->relation)
(unless the relation has already been eager-loaded) since it runs a count query rather than pulling all of the data for any related objects from the database, just to count them. Likewise, using exists
doesn't need to pull model data either.
Both exists()
and count()
work on all relation types I've tried, so at least belongsTo
, hasOne
, hasMany
, and belongsToMany
.
Just an update for .NET core 2.0 users, you can specify application configuration after the call to CreateDefaultBuilder
:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(ConfigConfiguration)
.UseStartup<Startup>()
.Build();
static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
{
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false, reloadOnChange: true)
.AddJsonFile($"config.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
}
}
Use ipcs -a
: it gives detailed information of all resources [semaphore, shared-memory etc]
Here is the image of the output:
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
There are two ways to do it.
In the method that opens the dialog, pass in the following configuration option disableClose
as the second parameter in MatDialog#open()
and set it to true
:
export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
Alternatively, do it in the dialog component itself.
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
Here's what you're looking for:
And here's a Stackblitz demo
Here's some other use cases and code snippets of how to implement them.
As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:
import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
P.S. This is an answer which originated from this answer, where the demo was based on this answer.
To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialog will have the configuration option disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialog to close.
Afterwards, subscribe to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
Alternatively, this can be done in the dialog component:
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:
import requests
url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
More about Request object: https://requests.readthedocs.io/en/master/api/
Implement Comparable interface to Fruit.
public class Fruit implements Comparable<Fruit> {
It implements the method
@Override
public int compareTo(Fruit fruit) {
//write code here for compare name
}
Then do call sort method
Collections.sort(fruitList);
In pre Sql 2008 By taking out the date part:
GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)
As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like
if ((a.b && c.d.e) || !f)
you might want to do something like
bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f
then your if statement is simplified to
if ( (isOk && isStillOk) || alternateOk)
It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.
Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None
. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.
class Pet:
def __init__(self):
self.hair = None
self.color = None
If I used hasattr
to do this, it would return True
even if the attribute value was of type None
and this would cause my ElementTree set
command to fail.
hasattr(temp, 'hair')
>>True
If the attribute value was of type None
, getattr
would also return it which would cause my ElementTree set
command to fail.
c = getattr(temp, 'hair')
type(c)
>> NoneType
I use the following method to take care of these cases now:
def getRealAttr(class_obj, class_attr, default = ''):
temp = getattr(class_obj, class_attr, default)
if temp is None:
temp = default
elif type(temp) != str:
temp = str(temp)
return temp
This is when and how I use getattr
.
I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;
The example is just as simple:
LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)
where divisor is 10^3, or 10^6 depending on required resolution.
Install file loader first:
$ npm install file-loader --save-dev
And add this rule in webpack.config.js
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
super(...)
), which basically does the sameyou can try this...
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
You could use:
jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();
Sometimes this happens because symlinks are not allowed in template settings:
Advanced > Developer > Template Settings > Allow Symlinks
@Inject
can inject any bean, while @EJB
can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject
everywhere.
You can use textract module in python
Textract
for install
pip install textract
for read pdf
import textract
text = textract.process('path/to/pdf/file', method='pdfminer')
For detail Textract
i solved with a max-width
in my main css-file.
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
It's a simple solution with little "code"
Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.
window.open('https://play.google.com/store/apps/details?id=com.drishya');
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
Getting the address of an arbitrary object in .NET is not possible, but can be done if you change the source code and use mono. See instructions here: Get Memory Address of .NET Object (C#)
Here is another JDK 1.7+ approach demonstration with superclass logics accounted. I see it as pretty convinient with Object class hashCode() accounted, pure JDK dependency and no extra manual work. Please note Objects.hash()
is null tolerant.
I have not include any equals()
implementation but in reality you will of course need it.
import java.util.Objects;
public class Demo {
public static class A {
private final String param1;
public A(final String param1) {
this.param1 = param1;
}
@Override
public int hashCode() {
return Objects.hash(
super.hashCode(),
this.param1);
}
}
public static class B extends A {
private final String param2;
private final String param3;
public B(
final String param1,
final String param2,
final String param3) {
super(param1);
this.param2 = param2;
this.param3 = param3;
}
@Override
public final int hashCode() {
return Objects.hash(
super.hashCode(),
this.param2,
this.param3);
}
}
public static void main(String [] args) {
A a = new A("A");
B b = new B("A", "B", "C");
System.out.println("A: " + a.hashCode());
System.out.println("B: " + b.hashCode());
}
}
For anyone out there still having trouble,
try this (my hosting was from Godaddy and this is the only thing that worked for me among all the answers out there.
AddHandler x-httpd-php5-cgi .html
Run Xampp (apache) as administrator. In google chrome type:
localhost/<insert folder name here>/<insert file name>
i.e. if folder you created is "LearnPhp", file is "chapter1.php" then type
localhost/LearnPhp/chapter1.php
I created this folder in the xampp folder in the htdocs folder which gets created when you download xampp.
I think df['word'].value_counts()
should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count
should be much slower than max
. Both take some time to avoid missing values. (Compare with size
.)
In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.
For most systems, the build requirements are now mentioned in python-ldap's documentation, in the "Installing" section.
If anything is missing for your system (or your system is missing entirely), please let maintainer know! (As of 2018, I am the maintainer, so a comment here should be enough. Or you can send a pull request or mail.)
If you have the process ID (PID
) you can kill this process as follow:
Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):
Function: Output:
scanf(...) EOF
gets(<variable>) NULL
feof(stdin) 1
getchar() EOF
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
Please Just follow the screenshot and enter -fno-objc-arc .
make sure you have GDB installed on your system...
If your using Linux based OS simply in a terminal type:
sudo apt-get install gdt
when finished downloading extract the file and install.
close your IDE (in this case eclipse and open it again and run your project.
simplifying:
a = 10; b = 15; c = 20
public static boolean check(int a, int b, int c) {
return a<=b && b<=c;
}
This checks if b is between a and c
This fixes the box dead center on the screen:
HTML
<table class="box" border="1px">
<tr>
<td>
my content
</td>
</tr>
</table>
CSS
.box {
width:300px;
height:300px;
background-color:#d9d9d9;
position:fixed;
margin-left:-150px; /* half of width */
margin-top:-150px; /* half of height */
top:50%;
left:50%;
}
View Results
I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c
is a list of list of strings, or whatever you designed this function to work with
For example you might get this error if you passed [c]
to the function instead of c
I believe this is what you want:
DataTable dtTable = new DataTable();
foreach (DataRow dtRow in dtTable.Rows)
{
foreach (DataColumn dc in dtRow.ItemArray)
{
}
}
It's actually fairly easy, just enter it as a latitude,longitude pair, ie 46.38S,115.36E (which is in the middle of the ocean). You'll want to convert it to decimal though (divide the minutes portion by 60 and add it to the degrees [I've done that with your example]).
I implemented the following and it works well. Basically, I set the body dimensions according to the size of the iFrame content. It does mean that our non-iFrame menu can be scrolled off the screen, but otherwise, this makes our sites functional with iPad and iPhone. "workbox" is the ID of our iFrame.
// Configure for scrolling peculiarities of iPad and iPhone
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
document.body.style.width = "100%";
document.body.style.height = "100%";
$("#workbox").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#workbox").contents().width();
if (iframeWidth > 400)
document.body.style.width = (iframeWidth + 182) + 'px';
iframeHeight = $("#workbox").contents().height();
if (iframeHeight>200)
document.body.style.height = iframeHeight + 'px';
});
}
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
For 1D array, numpy.correlate
is faster than scipy.signal.correlate
, under different sizes, I see a consistent 5x peformance gain using numpy.correlate
. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).
# a simple benchmark
res = []
for x in range(1, 1000):
list_x = []
for y in range(1, 1000):
# generate different sizes of series to compare
l1 = np.random.choice(range(1, 100), size=x)
l2 = np.random.choice(range(1, 100), size=y)
time_start = datetime.now()
np.correlate(a=l1, v=l2)
t_np = datetime.now() - time_start
time_start = datetime.now()
scipy.signal.correlate(in1=l1, in2=l2)
t_scipy = datetime.now() - time_start
list_x.append(t_scipy / t_np)
res.append(list_x)
plt.imshow(np.matrix(res))
As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.
>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))
[14 14 10 10 14]
[ 3 8 14 14 10 10 14 8 3] # the first 3 is [0,0,1]dot[1,2,3]
UPDATE January, 2017:
According to Can I use, the user-select
is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).
All of the correct CSS variations are:
.noselect {_x000D_
-webkit-touch-callout: none; /* iOS Safari */_x000D_
-webkit-user-select: none; /* Safari */_x000D_
-khtml-user-select: none; /* Konqueror HTML */_x000D_
-moz-user-select: none; /* Firefox */_x000D_
-ms-user-select: none; /* Internet Explorer/Edge */_x000D_
user-select: none; /* Non-prefixed version, currently_x000D_
supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
Unselectable text._x000D_
</p>
_x000D_
Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.
More information can be found in Mozilla Developer Network documentation.
The Constructor
is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass()
it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like
new MyClass(someArg);
ngOnInit
is a life cycle hook called by Angular to indicate that Angular is done creating the component.
We have to import OnInit
like this in order to use it (actually implementing OnInit
is not mandatory but considered good practice):
import { Component, OnInit } from '@angular/core';
then to make use of the method OnInit
, we have to implement the class like this:
export class App implements OnInit {
constructor() {
// Called first time before the ngOnInit()
}
ngOnInit() {
// Called after the constructor and called after the first ngOnChanges()
}
}
Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
Mostly we use ngOnInit
for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".
So you should use constructor()
to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.
For more information refer here:
facing similar problem to you. In my case I have 1000's of files from cisco logs that I need to parse manually.
In order to be flexible with fields and types I have successfully tested using StringIO + read_cvs which indeed does accept a dict for the dtype specification.
I usually get each of the files ( 5k-20k lines) into a buffer and create the dtype dictionaries dynamically.
Eventually I concatenate ( with categorical... thanks to 0.19) these dataframes into a large data frame that I dump into hdf5.
Something along these lines
import pandas as pd
import io
output = io.StringIO()
output.write('A,1,20,31\n')
output.write('B,2,21,32\n')
output.write('C,3,22,33\n')
output.write('D,4,23,34\n')
output.seek(0)
df=pd.read_csv(output, header=None,
names=["A","B","C","D"],
dtype={"A":"category","B":"float32","C":"int32","D":"float64"},
sep=","
)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
A 5 non-null category
B 5 non-null float32
C 5 non-null int32
D 5 non-null float64
dtypes: category(1), float32(1), float64(1), int32(1)
memory usage: 205.0 bytes
None
Not very pythonic.... but does the job
Hope it helps.
JC
As best I can tell, it is not possible to update the select2 options without refreshing the entire list or entering some search text and using a query function.
What are those buttons supposed to do? If they are used to determine the select options, why not put them outside of the select box, and have them programmatically set the select box data and then open it? I don't understand why you would want to put them on top of the search box. If the user is not supposed to search, you can use the minimumResultsForSearch option to hide the search feature.
Edit: How about this...
HTML:
<input type="hidden" id="select2" class="select" />
Javascript
var data = [{id: 0, text: "Zero"}],
select = $('#select2');
select.select2({
query: function(query) {
query.callback({results: data});
},
width: '150px'
});
console.log('Opening select2...');
select.select2('open');
setTimeout(function() {
console.log('Updating data...');
data = [{id: 1, text: 'One'}];
}, 1500);
setTimeout(function() {
console.log('Fake keyup-change...');
select.data().select2.search.trigger('keyup-change');
}, 3000);
Example: Plunker
Edit 2: That will at least get it to update the list, however there is still some weirdness if you have entered search text before triggering the keyup-change
event.
In reply to Dimitrys answer but using Ajax.BeginForm
the following works at least with MVC >5 (4 not tested).
write a model as shown in the other answers,
In the "parent view" you will probably use a table to show the data.
Model should be an ienumerable. I assume, the model has an id
-property. Howeverm below the template, a placeholder for the modal and corresponding javascript
<table>
@foreach (var item in Model)
{
<tr> <td id="[email protected]">
@Html.Partial("dataRowView", item)
</td> </tr>
}
</table>
<div class="modal fade" id="editor-container" tabindex="-1"
role="dialog" aria-labelledby="editor-title">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" id="editor-content-container"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.editor-container').click(function () {
var url = "/area/controller/MyEditAction";
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
});
});
});
function success(data,status,xhr) {
$('#editor-container').modal('hide');
$('#editor-content-container').html("");
}
function failure(xhr,status,error) {
$('#editor-content-container').html(xhr.responseText);
$('#editor-container').modal('show');
}
</script>
note the "editor-success-id" in data table rows.
The dataRowView
is a partial containing the presentation of an model's item.
@model ModelView
@{
var item = Model;
}
<div class="row">
// some data
<button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ...
).
@model Model
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "editor-success-" + @Model.Id,
OnSuccess = "success",
OnFailure = "failure",
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div class="modal-body">
<div class="form-horizontal">
// Models input fields
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
This is where magic happens: in AjaxOptions
, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.
This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.
But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:
the corresponding controller action method for the partial edit modal
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
// Find the data row and return the edit form
Model input = await db.Models.FindAsync(id);
return PartialView("EditModel", input);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
"Id,Fields,...")] ModelView input)
{
if (TryValidateModel(input))
{
// save changes, return new data row
// status code is something in 200-range
db.Entry(input).State = EntityState.Modified;
await db.SaveChangesAsync();
return PartialView("dataRowView", (ModelView)input);
}
// set the "error status code" that will redisplay the modal
Response.StatusCode = 400;
// and return the edit form, that will be displayed as a
// modal again - including the modelstate errors!
return PartialView("EditModel", (Model)input);
}
This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.
Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js
(may be installed by NuGet):
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:
C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts
to environment variable PATH
.C:\Python35
to rename python.exe
to python3.exe
, also to C:\Python27
, rename python.exe
to python2.exe
.python2 scriptname.py
, or python3 scriptname.py
in command line to switch the version you like.SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
Not sure how useful this will be, but you can also get the context when you initialize the app. This is the soonest you can get the context, even before an @Autowire
.
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static ApplicationContext context;
// I believe this only runs during an embedded Tomcat with `mvn spring-boot:run`.
// I don't believe it runs when deploying to Tomcat on AWS.
public static void main(String[] args) {
context = SpringApplication.run(Application.class, args);
DataSource dataSource = context.getBean(javax.sql.DataSource.class);
Logger.getLogger("Application").info("DATASOURCE = " + dataSource);
In VB
: This should work
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
In C#
it would be (as per comment of Ala)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
UrlImageViewHelper will fill an ImageView with an image that is found at a URL. UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.
UrlImageViewHelper.setUrlDrawable(imageView, "http://example.com/image.png");
How about:
if (stream.markSupported() == false) {
// lets replace the stream object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(stream, baos);
stream.close();
stream = new ByteArrayInputStream(baos.toByteArray());
// now the stream should support 'mark' and 'reset'
}
I have made a little example using css
.hover {_x000D_
position: relative;_x000D_
top: 50px;_x000D_
left: 50px;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
/* hide and position tooltip */_x000D_
top: -10px;_x000D_
background-color: black;_x000D_
color: white;_x000D_
border-radius: 5px;_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
-webkit-transition: opacity 0.5s;_x000D_
-moz-transition: opacity 0.5s;_x000D_
-ms-transition: opacity 0.5s;_x000D_
-o-transition: opacity 0.5s;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover .tooltip {_x000D_
/* display tooltip on hover */_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="hover">hover_x000D_
<div class="tooltip">asdadasd_x000D_
</div>_x000D_
</div>
_x000D_
FIDDLE
AWS Ubuntu 18.04 LTS
Linux ws1 4.15.0-1023-aws #23-Ubuntu SMP Mon Sep 24 16:31:06 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc && source ~/.bashrc
Worked for me.
telnet ServerName 80
GET /index.html?
?
? means 'return', you need to hit return twice
If you want your code to pick a specific range of digits, be sure to use the &&
operator instead of the ||
.
if (x >= 4 && x <= 9) {_x000D_
// do something_x000D_
} else {_x000D_
// do something else_x000D_
}_x000D_
_x000D_
// be sure not to do this_x000D_
_x000D_
if (x >= 4 || x <= 9) {_x000D_
// do something_x000D_
} else {_x000D_
// do something else_x000D_
}
_x000D_
Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.
You formaction for multiple submit button in one form example
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress">
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress">
This worked for me with some css frameworks (material design lite [MDL]).
table {
table-layout: fixed;
white-space: normal!important;
}
td {
word-wrap: break-word;
}
We could assert
const inputElement: HTMLInputElement = document.getElementById('greet')
Or with as
-syntax
const inputElement = document.getElementById('greet') as HTMLInputElement
Giving
const inputValue = inputElement.value // now inferred to be string
Try use Build Timestamp Plugin
and use BUILD_TIMESTAMP
variable.
I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error. This article helped me and I used this script:
EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;
for more detail look at this: Linked server : The partner transaction manager has disabled its support for remote/network transactions
INSERT INTO myTable VALUES("First line\r\nSecond line\r\nThird line");
I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.
Then I found this question and answer: How to add a new row to an empty numpy array
The gist here:
The way to "start" the array that you want is:
arr = np.empty((0,3), int)
Then you can use concatenate to add rows like so:
arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)
See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html
To create a read-only user, you have to setup a different user than the one owning the tables you want to access.
If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1
So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');
Cors issue has been faced in my application. refer above screenshot. After adding proxy config issue has been resolved. my application url: localhost:4200 and requesting api url:"http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address="
Api side no-cors permission allowed. And also I'm not able to change cors-issue in server side and I had to change only in angular(client side).
Steps to resolve:
{ "/maps/*": { "target": "http://www.datasciencetoolkit.org", "secure": false, "logLevel": "debug", "changeOrigin": true } }
this.http .get<GeoCode>('maps/api/geocode/json?sensor=false&address=' + cityName) .pipe( tap(cityResponse => this.responseCache.set(cityName, cityResponse)) );
Note: We have skip hostname name url in Api request, it will auto add while giving request. whenever changing proxy.conf.js we have to restart ng-serve, then only changes will update.
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "TestProject:build", "proxyConfig": "src/proxy.conf.json" }, "configurations": { "production": { "browserTarget": "TestProject:build:production" } } },
After finishing these step restart ng-serve Proxy working correctly as expect refer here
> WARNING in
> D:\angular\Divya_Actian_Assignment\src\environments\environment.prod.ts
> is part of the TypeScript compilation but it's unused. Add only entry
> points to the 'files' or 'include' properties in your tsconfig.
> ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** : Compiled
> successfully. [HPM] GET
> /maps/api/geocode/json?sensor=false&address=chennai ->
> http://www.datasciencetoolkit.org
As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.
In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.minimumZoomScale = 0.5;
self.scrollView.maximumZoomScale = 6.0;
self.scrollView.contentSize = self.imageView.frame.size;
self.scrollView.delegate = self;
}
You are required to implement the following method to return the imageView you want to zoom.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
In versions prior to iOS9, you may also need to add this empty delegate method:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}
The Apple Documentation does a good job of describing how to do this:
I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of from x import x
and functions:
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]
print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')
This is an old thread, but I thought I should post my solution. I faced the same problem recently and the way I solved it is by following a three-step approach as outlined below which is very simple without any complex CSS.
(NOTE : Of course, for modern browsers, using the values of table or table-row or table-cell for display CSS attribute would solve the problem. But the approach I used will work equally well in modern and older browsers since it does not use these values for display CSS attribute.)
3-STEP SIMPLE APPROACH
For table with divs only so you get cells and rows just like in a table element use the following approach.
.table
class).row
class).cell
class).table {display:block; }_x000D_
.row { display:block;}_x000D_
.cell {display:inline-block;}
_x000D_
<h2>Table below using table element</h2>_x000D_
<table cellspacing="0" >_x000D_
<tr>_x000D_
<td>Mike</td>_x000D_
<td>36 years</td>_x000D_
<td>Architect</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sunil</td>_x000D_
<td>45 years</td>_x000D_
<td>Vice President aas</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jason</td>_x000D_
<td>27 years</td>_x000D_
<td>Junior Developer</td>_x000D_
</tr>_x000D_
</table>_x000D_
<h2>Table below is using Divs only</h2>_x000D_
<div class="table">_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Mike_x000D_
</div>_x000D_
<div class="cell">_x000D_
36 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Architect_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Sunil_x000D_
</div>_x000D_
<div class="cell">_x000D_
45 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Vice President_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="cell">_x000D_
Jason_x000D_
</div>_x000D_
<div class="cell">_x000D_
27 years_x000D_
</div>_x000D_
<div class="cell">_x000D_
Junior Developer_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
UPDATE 1
To get around the effect of same width not being maintained across all cells of a column as mentioned by thatslch
in a comment, one could adopt either of the two approaches below.
Specify a width for cell
class
cell {display:inline-block; width:340px;}
Use CSS of modern browsers as below.
.table {display:table; } .row { display:table-row;} .cell {display:table-cell;}
SELECT
ALL_VALUES
,COUNT(ALL_VALUES)
FROM(
SELECT
NVL2(A,'NOT NULL','NULL') AS ALL_VALUES
,NVL(A,0)
FROM US
)
GROUP BY ALL_VALUES
merge into t2 t2
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
t2.c1 = t1.c1
, t2.c2 = t1.c2
Oracle support Mathematical Subtract -
operator on Data datatype. You may directly put in select clause following statement:
to_char (s.last_upd – s.created, ‘999999D99')
Check the EXAMPLE for more visibility.
In case you need the output in termes of hours, then the below might help;
Select to_number(substr(numtodsinterval([END_TIME]-[START_TIME]),’day’,2,9))*24 +
to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),12,2))
||':’||to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),15,2))
from [TABLE_NAME];
If you want to modify just the elements:
void foo(double *bar);
is enough.
If you want to modify the address to (e.g.: realloc
), but it doesn't work for arrays:
void foo(double *&bar);
is the correct form.
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
Break-down:
8
says that you want to show 8 digits0
that you want to prefix with 0
's instead of just blank spacesx
that you want to print in lower-case hexadecimal.Quick example (thanks to Grijesh Chauhan):
#include <stdio.h>
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf("%0x\n", data); // just print data ('0' on its own has no effect)
printf("%8x\n", data); // print in 8 width and pad with blank spaces
printf("%08x\n", data); // print in 8 width and pad with 0's
return 0;
}
Output:
1d
1d
1d
0000001d
Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.
Probably my question should have been more specific. I actually know a base class for the string so solved it by:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.
import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.
int [][] twoDim = new int [5][5];
int a = (twoDim.length);//5
int b = (twoDim[0].length);//5
for(int i = 0; i < a; i++){ // 1 2 3 4 5
for(int j = 0; j <b; j++) { // 1 2 3 4 5
int x = (i+1)*(j+1);
twoDim[i][j] = x;
if (x<10) {
System.out.print(" " + x + " ");
} else {
System.out.print(x + " ");
}
}//end of for J
System.out.println();
}//end of for i
Days until Christmas:
>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86
More arithmetic here.
for(Field field : cls.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
Annotation[] annotations = field.getDeclaredAnnotations();
}
See also: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
I stumbled over the same issue and found a nice solution which does not need any static ip configuration:
You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local
You can use that DNS name to reference it in another namespace via a local service:
kind: Service
apiVersion: v1
metadata:
name: service-y
namespace: namespace-a
spec:
type: ExternalName
externalName: service-x.namespace-b.svc.cluster.local
ports:
- port: 80
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
This function will clear the sheet data starting from specified row and column :
Sub ClearWKSData(wksCur As Worksheet, iFirstRow As Integer, iFirstCol As Integer)
Dim iUsedCols As Integer
Dim iUsedRows As Integer
iUsedRows = wksCur.UsedRange.Row + wksCur.UsedRange.Rows.Count - 1
iUsedCols = wksCur.UsedRange.Column + wksCur.UsedRange.Columns.Count - 1
If iUsedRows > iFirstRow And iUsedCols > iFirstCol Then
wksCur.Range(wksCur.Cells(iFirstRow, iFirstCol), wksCur.Cells(iUsedRows, iUsedCols)).Clear
End If
End Sub
Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out.
The value of core.autocrlf is set before commit and also before checkout.
The result is below.
commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF CRLF=>CRLF
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.
EDIT:
There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):
The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.
At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.
I found that the cause of this problem in my case, was that I've combined my Angular app with a node.js application in the same source tree, and in the root tsconfig.json
I had:
"files": [
"./node_modules/@types/node/index.d.ts"
]
I changed this to
"compilerOptions": {
"types": ["node"]
}
And then to prevent node types being uses in your angular app, add this to tsconfig.app.json
:
"compilerOptions": {
"types": []
}
Thank you very much for the replies!
Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:
1 39.00 9.00
You'll end up with:
1 78.00 48.00
Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.
After much struggling, I think that the following query returns what I need it to:
SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
SELECT invoiceid, SUM(p.amount) amount
FROM invoicepayments ip
LEFT JOIN payments p ON ip.paymentid = p.paymentid
GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'
Would you guys concur?
The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block. I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block. I demonstrate this in the gif as well.
BEGIN TRY
/* RAISERROR with severity 11-19 will cause execution
| to jump to the CATCH block.
*/
RAISERROR ('Error raised in TRY block.', -- Message text.
5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
/* Use RAISERROR inside the CATCH block to return error
| information about the original error that caused
| execution to jump to the CATCH block
*/
RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
@ErrorSeverity, /* Severity */
@ErrorState /* State */
);
END CATCH;
for a solution that uses ncurses
with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys
Non of the above mentioned solutions worked for me. Below is what finally worked:
#yum update
#yum install phpmyadmin
Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.
After this, going to the browser, I got an error that said ./config.inic.php can't be accessed
#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php
This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.
Remember to restart httpd.
#service httpd restart
@Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})
I see you have added an answer to your question in SQL Server 2008 you can also do
SELECT 3 + CRYPT_GEN_RANDOM(1) % 4 /*Random number between 3 and 6*/
FROM ...
A couple of disadvantages of this method are
NEWID()
method but just thought I'd add it as another option.
Check your PrimeNumberModelTests
Target Settings.
If you can't see PrimeNumberModel.swift
file in Build Phases/Compile Sources
, add it.
A pointer-to-a-pointer is used when a reference to a pointer is required. For example, when you wish to modify the value (address pointed to) of a pointer variable declared in a calling function's scope inside a called function.
If you pass a single pointer in as an argument, you will be modifying local copies of the pointer, not the original pointer in the calling scope. With a pointer to a pointer, you modify the latter.
Environment.GetCommandLineArgs()[0]
$headers = array(
'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
Yes you can change the on / off button
android:textOn="Light ON"
android:textOff="Light OFF"
Refer for more
http://androidcoding.in/2016/09/11/android-tutorial-toggle-button
Simply set the logo's style to display:hidden
and call fadeIn
, instead of first calling hide
:
$(document).ready(function() {
$('#logo').fadeIn("normal");
});
<img src="logo.jpg" style="display:none"/>
For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .
after that you can easily compare it. Query is :
select * from demo_date where date >= '3/1/2015' and date <= '3/31/2015'.
It very simple ...... It tested it.....
Try doing it this way, it worked for me:
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`
Seems like the rule always has the validation on the first input among the pair...
const hasValue = Object.values(json).includes("bar");
function hasValueDeep(json, findValue) {
const values = Object.values(json);
let hasValue = values.includes(findValue);
values.forEach(function(value) {
if (typeof value === "object") {
hasValue = hasValue || hasValueDeep(value, findValue);
}
})
return hasValue;
}
I think thats correct. RTSP may use RTP internally.
Thanks, Thomas. I'm new to JS and I've been looking crazy for a solution to my problem. Yours helped.
I've used jquery to make a Login-box that slides down. For best user experience I desided to make the box disappear when user clicks somewhere but the box. I'm a little bit embarrassed over using about four hours fixing this. But hey, I'm new to JS.
Maybe my code can help someone out:
<body>
<button class="login">Logg inn</button>
<script type="text/javascript">
$("button.login").click(function () {
if ($("div#box:first").is(":hidden")) {
$("div#box").slideDown("slow");}
else {
$("div#box").slideUp("slow");
}
});
</script>
<div id="box">Lots of login content</div>
<script type="text/javascript">
var box = $('#box');
var login = $('.login');
login.click(function() {
box.show(); return false;
});
$(document).click(function() {
box.hide();
});
box.click(function(e) {
e.stopPropagation();
});
</script>
</body>
Try something like:
from tkinter import Tk, Button, Frame, Entry, END
class ABC(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
root = Tk()
app = ABC(master=root)
app.master.title("Simple Prog")
app.mainloop()
root.destroy()
Now you should have a frame with a title, then afterwards you can add windows for different widgets if you like.
your div looks like this:
<div class="readonly_label" id="field-function_purpose">Other</div>
With jquery you can easily get inner content:
Use .html()
: HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
var text = $('#field-function_purpose').html();
Read more about jquery .html()
or
Use .text()
: Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
var text = $('#field-function_purpose').text();
Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.
A common convention is to put the result of a build into a build
, target
or bin
directory.
The Jenkins archiver can use globs (target/*.jar
) to easily pick up the right file even if you have a unique name per build.
@NoCanDo: You cannot create an array with different data types because java only supports variables with a specific data type or object. When you are creating an array, you are pulling together an assortment of similar variables -- almost like an extended variable. All of the variables must be of the same type therefore. Java cannot differentiate the data type of your variable unless you tell it what it is. Ex: int
tells all your variables declared to it are of data type int
. What you could do is create 3 arrays with corresponding information.
int bookNumber[] = {1, 2, 3, 4, 5};
int bookName[] = {nameOfBook1, nameOfBook2, nameOfBook3, nameOfBook4, nameOfBook5}
// etc.. etc..
Now, a single index number gives you all the info for that book. Ex: All of your arrays with index number 0 ([0]) have information for book 1.
You can use lambda to bind a method to an instance:
def run(self):
print self._instanceString
class A(object):
def __init__(self):
self._instanceString = "This is instance string"
a = A()
a.run = lambda: run(a)
a.run()
Output:
This is instance string
In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS")
out to make it even faster):
var _getAllFilesFromFolder = function(dir) {
var filesystem = require("fs");
var results = [];
filesystem.readdirSync(dir).forEach(function(file) {
file = dir+'/'+file;
var stat = filesystem.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(_getAllFilesFromFolder(file))
} else results.push(file);
});
return results;
};
usage is clear:
_getAllFilesFromFolder(__dirname + "folder");
To access the index in this case you access the name
attribute:
In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
Note that if this is really what you are trying to do that the following works and is much faster:
In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop
EDIT
Looking at this question 3+ years later, you could just do:
In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
but assuming it isn't as trivial as this, whatever your rowFunc
is really doing, you should look to use the vectorised functions, and then use them against the df index:
In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
You are just Compare zeroth element with rest of the elements so it will print the value last largest value which it will contain, in you case, same problem is happening. To compare each and every elements we have to swap the values like:
double max = decMax[0];
for (int counter = 1; counter < decMax.length; counter++){
if(max<decMax[i]){
max=decMax[i]; //swapping
decMax[i]=decMax[0];
}
}
System.out.println("The max value is "+ max);
Hope this will help you
This answer has a code example, which implements the algorithm described in the paper Practical In-Place Merging by Bing-Chao Huang and Michael A. Langston. I have to admit that I do not understand the details, but the given complexity of the merge step is O(n).
From a practical perspective, there is evidence that pure in-place implementations are not performing better in real world scenarios. For example, the C++ standard defines std::inplace_merge, which is as the name implies an in-place merge operation.
Assuming that C++ libraries are typically very well optimized, it is interesting to see how it is implemented:
The implementation delegates to __inplace_merge, which dodges the problem by trying to allocate a temporary buffer:
typedef _Temporary_buffer<_BidirectionalIterator, _ValueType> _TmpBuf;
_TmpBuf __buf(__first, __len1 + __len2);
if (__buf.begin() == 0)
std::__merge_without_buffer
(__first, __middle, __last, __len1, __len2, __comp);
else
std::__merge_adaptive
(__first, __middle, __last, __len1, __len2, __buf.begin(),
_DistanceType(__buf.size()), __comp);
Otherwise, it falls back to an implementation (__merge_without_buffer), which requires no extra memory, but no longer runs in O(n) time.
Looks similar. It delegates to a function, which also tries to allocate a buffer. Depending on whether it got enough elements, it will choose the implementation. The constant-memory fallback function is called __buffered_inplace_merge.
Maybe even the fallback is still O(n) time, but the point is that they do not use the implementation if temporary memory is available.
Note that the C++ standard explicitly gives implementations the freedom to choose this approach by lowering the required complexity from O(n) to O(N log N):
Complexity: Exactly N-1 comparisons if enough additional memory is available. If the memory is insufficient, O(N log N) comparisons.
Of course, this cannot be taken as a proof that constant space in-place merges in O(n) time should never be used. On the other hand, if it would be faster, the optimized C++ libraries would probably switch to that type of implementation.
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
function Continue({show, onContinue}) {
return(<div className="row continue">
{ show ? <div className="col-11">
<button class="btn btn-primary btn-lg float-right" onClick= {onContinue}>Continue</button>
</div>
: null }
</div>);
}
I know it's 2 years late, but these answers helped me to formulate a filter function to output objects and trim the resulting strings. Since I have to format everything into a string in my final solution I went about things a little differently. Long-hand, my problem is very similar, and looks a bit like this
$verbosepreference="Continue"
write-verbose (ls | ft | out-string) # this generated too many blank lines
Here is my example:
ls | Out-Verbose # out-verbose formats the (pipelined) object(s) and then trims blanks
My Out-Verbose function looks like this:
filter Out-Verbose{
Param([parameter(valuefrompipeline=$true)][PSObject[]]$InputObject,
[scriptblock]$script={write-verbose "$_"})
Begin {
$val=@()
}
Process {
$val += $inputobject
}
End {
$val | ft -autosize -wrap|out-string |%{$_.split("`r`n")} |?{$_.length} |%{$script.Invoke()}
}
}
Note1: This solution will not scale to like millions of objects(it does not handle the pipeline serially)
Note2: You can still add a -noheaddings option. If you are wondering why I used a scriptblock here, that's to allow overloading like to send to disk-file or other output streams.
This article describes how to render text in OpenGL using various techniques.
With only using opengl, there are several ways:
I would just create a separate CSS class:
.ButtonClicked {
background-color:red;
}
And then add the class on click:
$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});
This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ?
and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.
You can also create the ability to have an "on/off" switch feel by toggling the class:
$('#ButtonId').on('click',function(){
$(this).toggleClass('ButtonClicked');
});
Shown by this jsFiddle. Just food for thought.
No. While the definition from w3c for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString
:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using
statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
var secondEmails = (from item in list2
select new { Email = item.Email }
).ToList();
var matches = from item in list1
where !secondEmails.Contains(item.Email)
select new {Email = item.Email};
This issue is because you didn't register the data access component with the interface written for it. Try using as follows
services.AddTransient<IMyDataProvider, MyDataAccess>();`
I have BaseModel class, so I needed something more generic.
//app/BaseModel.php
public function rules()
{
return $rules = [];
}
public function isValid($id = '')
{
$validation = Validator::make($this->attributes, $this->rules($id));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
In user class let's suppose I need only email and name to be validated:
//app/User.php
//User extends BaseModel
public function rules($id = '')
{
$rules = [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'password' => 'required|alpha_num|between:6,12',
'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
];
if(!empty($id))
{
$rules['email'].= ",$id";
unset($rules['password']);
unset($rules['password_confirmation']);
}
return $rules;
}
I tested this with phpunit and works fine.
//tests/models/UserTest.php
public function testUpdateExistingUser()
{
$user = User::find(1);
$result = $user->id;
$this->assertEquals(true, $result);
$user->name = 'test update';
$user->email = '[email protected]';
$user->save();
$this->assertTrue($user->isValid($user->id), 'Expected to pass');
}
I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well. (tested on Laravel 5.0)
this is the only solution that i found that works!
WebView webview;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
// Next part
class MyWebChromeClient extends WebChromeClient {
// The undocumented magic method override
// Eclipse will swear at you if you try to put @Override here
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Cv5appActivity.this.startActivityForResult(
Intent.createChooser(i, "Image Browser"),
FILECHOOSER_RESULTCODE);
}
}
In my case (having an overview page and an "add" page) I got this with my routing setup like below. It was giving the message for the AddCtrl that could not be injected...
$routeProvider.
when('/', {
redirectTo: '/overview'
}).
when('/overview', {
templateUrl: 'partials/overview.html',
controller: 'OverviewCtrl'
}).
when('/add', {
templateUrl: 'partials/add.html',
controller: 'AddCtrl'
}).
otherwise({
redirectTo: '/overview'
});
Because of the when('/'
route all my routes went to the overview and the controller could not be matched on the /add route page rendering. This was confusing because I DID see the add.html template but its controller was nowhere to be found.
Removing the '/'-route when case fixed this issue for me.
A quick answer:
mvn -fn test
Works with nested project builds.
You can use ->child
to get a child element named child.
This element will contain the text of the child element.
But if you try var_dump()
on that variable, you will see it is not actually a PHP string.
The easiest way around this is to perform a strval(xml->child);
That will convert it to an actual PHP string.
This is useful when debugging when looping your XML and using var_dump()
to check the result.
So $s = strval($xml->child);
.
If you happen to scroll down to this point, I found a solution for Firefox. It will print contents from a specific div without the footers and headers. You can customize as you wish.
Firstly, download and install this addon : JSPrintSetup.
Secondly, write this function:
<script>
function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write(elem);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
//jsPrintSetup.setPrinter('PDFCreator'); //set the printer if you wish
jsPrintSetup.setSilentPrint(1);
//sent empty page header
jsPrintSetup.setOption('headerStrLeft', '');
jsPrintSetup.setOption('headerStrCenter', '');
jsPrintSetup.setOption('headerStrRight', '');
// set empty page footer
jsPrintSetup.setOption('footerStrLeft', '');
jsPrintSetup.setOption('footerStrCenter', '');
jsPrintSetup.setOption('footerStrRight', '');
// print my window silently.
jsPrintSetup.printWindow(mywindow);
jsPrintSetup.setSilentPrint(1); //change to 0 if you want print dialog
mywindow.close();
return true;
}
</script>
Thirdly, In your code, wherever you want to write the print code, do this (I have used JQuery. You can use plain javascript):
<script>
$("#print").click(function () {
var contents = $("#yourDivToPrint").html();
PrintElem(contents);
})
</script>
Obviously, you need the link to click:
<a href="#" id="print">Print my Div</a>
And your div to print:
<div id="yourDivToPrint">....</div>
I had same problem when installing Robot Framework 2.9.2 using the Windows installer version on Windows 7.
I could solve it installing the VC14 builds require to have the "Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed" from Microsoft website.
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
my
is used for local variables, whereas our
is used for global variables.
More reading over at Variable Scoping in Perl: the basics.
To generate a number between 10 to 20 inclusive, you can use java.util.Random
int myNumber = new Random().nextInt(11) + 10
Try to delete references and add it back, some times eclipse behave weird because until and unless you fix that error it wont allow you refresh. so try to delete all dependencies project and add it back Clean and build
I still go with the uppercase for const values, but this is more out of habit than for any particular reason.
Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb.
My conclusion: Go with the camel casing. Maybe I will change my style too ;-)
Edit:
That something smells hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?
There are cases when hungarian helps. Not that many nowadays, but they still exist.
$scope.$on('$ViewData', function(event) {
//Your code.
});
Parse the string into an integer using parseInt
:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
There are 3 location providers in Android.
They are:
gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.
network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).
The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris
Code Reference : https://stackoverflow.com/a/3145655/28557
-----------------------Update-----------------------
Now Android have Fused location provider
The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage
Fused location provider provide three ways to fetch location
References :
Official site : http://developer.android.com/google/play-services/location.html
Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example
http://blog.lemberg.co.uk/fused-location-provider
--------------------------------------------------------
CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included resource), you can navigate within one click from Java class to where it is used as Spring or Hibernate bean; clicking on included JSP or JSTL tag also works, ctrl-click on JavaScript variable or function brings you to the place it is defined or shows a menu if there are more than one place, including other .js files and JS code in HTML or JSP files.
Autocomplete in HSQL expressions, in Hibernate configuration (including class, property and DB column names), in Spring configuration
<property name="propName" ref="<hit CTRL-SPACE>"
and it will show you list of those beans which you can inject into that property.
Very smart autocomplete in Java code:
interface Person {
String getName();
String getAddress();
int getAge();
}
//---
Person p;
String name = p.<CTRL-SHIFT-SPACE>
and it shows you ONLY getName(), getAddress() and toString() (only they are compatible by type) and getName() is first in the list because it has more relevant name. Latest version 8 which is still in EAP has even more smart autocomplete.
interface Country{
}
interface Address {
String getStreetAddress();
String getZipCode();
Country getCountry();
}
interface Person {
String getName();
Address getAddress();
int getAge();
}
//---
Person p;
Country c = p.<CTRL-SHIFT-SPACE>
and it will silently autocomplete it to
Country c = p.getAddress().getCountry();
Smart autocomplete in JavaScript.
function Person(name,address) {
this.getName = function() { return name };
this.getAddress = function() { return address };
}
Person.prototype.hello = function() {
return "I'm " + this.getName() + " from " + this.get<CTRL-SPACE>;
}
and it shows ONLY getName() and getAddress(), no matter how may get* methods you have in other JS objects in your project, and ctrl-click on this.getName() brings you to where this one is defined, even if there are some other getName() functions in your project.
Did I mention autocomplete and ctrl-clicking in paths to files, like <script src="", <img src="", etc?
Autocomplete in HTML tag attributes. Autocomplete in style attribute of HTML tags, both attribute names and values. Autocomplete in class attributes as well.
Type <div class="<CTRL-SPACE> and it will show you list of CSS classes defined in your project. Pick one, ctrl-click on it and you will be redirected to where it is defined.
Latest version has language injection, so you can declare that you custom JSTL tag usually contains JavaScript and it will highlight JavaScript inside it.
<ui:obfuscateJavaScript>function something(){...}</ui:obfuscateJavaScript>
You can use Find Usages of any Java class or method and it will find where it is used including not only Java classes but Hibernate, Spring, JSP and other places. Rename Method refactoring renames method not only in Java classes but anywhere including comments (it can not be sure if string in comments is really method name so it will ask). And it will find only your method even if there are methods of another class with same name. Good source control integration (does SVN support changelists? IDEA support them for every source control), ability to create a patch with your changes so you can send your changes to other team member without committing them.
When I look at HashMap in debugger's watch window, I see logical view - keys and values, last time I did it in Eclipse it was showing entries with hash and next fields - I'm not really debugging HashMap, I just want to look at it contents.
It validates Spring and Hibernate configuration right when you edit it, so I do not need to restart server to know that I misspelled class name, or added constructor parameter so my Spring cfg is invalid.
Last time I tried, I could not run Eclipse on Windows XP x64.
and it will suggest you person.name or person.address. Ctrl-click on person.name and it will navigate you to getName() method of Person class.
Type Pattern.compile("");
put \\ there, hit CTRL-SPACE and see helpful hint about what you can put into your regular expression. You can also use language injection here - define your own method that takes string parameter, declare in IntelliLang options dialog that your parameter is regular expression - and it will give you autocomplete there as well. Needless to say it highlights incorrect regular expressions.
There are few features which I'm not sure are present in Eclipse or not. But at least each member of our team who uses Eclipse, also uses some merging tool to merge local changes with changes from source control, usually WinMerge. I never need it - merging in IDEA is enough for me. By 3 clicks I can see list of file versions in source control, by 3 more clicks I can compare previous versions, or previous and current one and possibly merge.
It allows to to specify that I need all .jars inside WEB-INF\lib
folder, without picking each file separately, so when someone commits new .jar into that folder it picks it up automatically.
Mentioned above is probably 10% of what it does. I do not use Maven, Flex, Swing, EJB and a lot of other stuff, so I can not tell how it helps with them. But it does.
In my case I use a web hosting but it´s the same in local host, I used:
ps -aef | grep 'node'
for watch the node process then, the console shows the process with PID. for kill the process you have to use this command:
kill -9 PID
where PID is the process id from the command above.
I got this error after a Git branch change. For the specific case of Eclipse,there were missed lines on .settings directory for org.eclipse.wst.common.component file. As you can see below
Restoring the project dependencies with Maven Install would help.
Check the php.ini
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
ini_set('max_execution_time', 0); //0=NOLIMIT
It sucks but you can get the bean by using the ApplicationContextAware
interface. Something like :
public class Boo implements ApplicationContextAware {
private static ApplicationContext appContext;
@Autowired
Foo foo;
public static void randomMethod() {
Foo fooInstance = appContext.getBean(Foo.class);
fooInstance.doStuff();
}
@Override
public void setApplicationContext(ApplicationContext appContext) {
Boo.appContext = appContext;
}
}
You can use DataFrame.any
with parameter axis=1
for check at least one True
in row by DataFrame.isna
with boolean indexing
:
df1 = df[df.isna().any(axis=1)]
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
print (df)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat 0.8016 0.9283 1.000000 0.074804 3.985599e+01
F71_sMI_DMRI51d.dat 0.0000 0.0000 NaN 0.000000 1.000000e+25
F62_sMI_St22d7.dat 1.7210 3.8330 0.237480 0.150000 1.091832e+01
F41_Car_HOC498d.dat 1.1670 2.8090 0.364190 0.300000 7.966335e+00
F78_MI_547d.dat 1.8970 5.4590 0.095319 NaN 2.593468e+01
Explanation:
print (df.isna())
alpha1 alpha2 gamma1 gamma2 chi2min
filename
M66_MI_NSRh35d32kpoints.dat False False False False False
F71_sMI_DMRI51d.dat False False True False False
F62_sMI_St22d7.dat False False False False False
F41_Car_HOC498d.dat False False False False False
F78_MI_547d.dat False False False True False
print (df.isna().any(axis=1))
filename
M66_MI_NSRh35d32kpoints.dat False
F71_sMI_DMRI51d.dat True
F62_sMI_St22d7.dat False
F41_Car_HOC498d.dat False
F78_MI_547d.dat True
dtype: bool
df1 = df[df.isna().any(axis=1)]
print (df1)
alpha1 alpha2 gamma1 gamma2 chi2min
filename
F71_sMI_DMRI51d.dat 0.000 0.000 NaN 0.0 1.000000e+25
F78_MI_547d.dat 1.897 5.459 0.095319 NaN 2.593468e+01
I know this is an old question but I thought I'd still share my method of adding image captions. You won't be able to use the caption
or figcaption
tags, but this would be a simple alternative without using any plugins.
In your markdown, you can wrap your caption with the emphasis tag and put it directly underneath the image without inserting a new line like so:
![](path_to_image)
*image_caption*
This would generate the following HTML:
<p>
<img src="path_to_image" alt>
<em>image_caption</em>
</p>
Then in your CSS you can style it using the following selector without interfering with other em
tags on the page:
img + em { }
Note that you must not have a blank line between the image and the caption because that would instead generate:
<p>
<img src="path_to_image" alt>
</p>
<p>
<em>image_caption</em>
</p>
You can also use whatever tag you want other than em
. Just make sure there is a tag, otherwise you won't be able to style it.
In addition to the previous answers, here is a way to calculate the distance inside a SELECT:
CREATE FUNCTION Get_Distance
(
@La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE
AS
RETURN
-- Distance in Meters
SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
AS Distance
GO
Usage:
select Distance
from Place P1,
Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)
Scalar functions also work but they are very inefficient when computing large amount of data.
I hope this might help someone.
If you're really, absolutely positively sure that the NSURL is a file url, i.e. [url isFileURL]
is guaranteed to return true in your case, then you can simply use:
[UIImage imageWithContentsOfFile:url.path]
You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;
Here's a simple example:
While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.
The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.
[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]
/* CSS */_x000D_
_x000D_
div.settings {_x000D_
display:grid;_x000D_
grid-template-columns: max-content max-content;_x000D_
grid-gap:5px;_x000D_
}_x000D_
div.settings label { text-align:right; }_x000D_
div.settings label:after { content: ":"; }
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class="settings">_x000D_
<label>Label #1</label>_x000D_
<input type="text" />_x000D_
_x000D_
<label>Long Label #2</label>_x000D_
<span>Display content</span>_x000D_
_x000D_
<label>Label #3</label>_x000D_
<input type="text" />_x000D_
</div>
_x000D_
"location" directive should be inside a 'server' directive, e.g.
server {
listen 8765;
location / {
resolver 8.8.8.8;
proxy_pass http://$http_host$uri$is_args$args;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
What you exactly wan't to do ?. To change Datatype of column you can simple use alter command as
ALTER TABLE table_name ALTER COLUMN LoginDate DateTime;
But remember there should valid Date only in this column however data-type is nvarchar.
If you wan't to convert data type while fetching data then you can use CONVERT function as,
CONVERT(data_type(length),expression,style)
eg:
SELECT CONVERT(DateTime, loginDate, 6)
This will return 29 AUG 13. For details about CONVERT function you can visit ,
http://www.w3schools.com/sql/func_convert.asp.
Remember, Always use DataTime data type for DateTime column.
Thank You
public bool FindAndKillProcess(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes by using the StartsWith Method,
//this prevents us from incluing the .EXE for the process we're looking for.
//. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running
if (clsProcess.ProcessName.StartsWith(name))
{
//since we found the proccess we now need to use the
//Kill Method to kill the process. Remember, if you have
//the process running more than once, say IE open 4
//times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
try
{
clsProcess.Kill();
}
catch
{
return false;
}
//process killed, return true
return true;
}
}
//process not found, return false
return false;
}
svn status | grep "^\?" | awk '{print $2}' | xargs svn add
Taken from somewhere on the web but I've been using it for a while and it works well.
How to reproduce the above error in PHP:
php> $yarr = array(3 => 'c', 4 => 'd');
php> echo $yarr[4];
d
php> echo $yarr[1];
PHP Notice: Undefined offset: 1 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What does that error message mean?
It means the php compiler looked for the key 1
and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1
How do I make that error go away?
Ask the array if the key exists before returning its value like this:
php> echo array_key_exists(1, $yarr);
php> echo array_key_exists(4, $yarr);
1
If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".
Alternative solution that's faster:
If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];
), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131
In general I use system
, open
, IPC::Open2
, or IPC::Open3
depending on what I want to do. The qx//
operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open
to much handier.
system
: run a command and wait for it to returnUse system
when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.
#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");
or
#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");
qx//
or ``: run a command and capture its STDOUTUse qx//
when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.
#arguments are always processed by the shell
#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;
#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;
exec
: replace the current process with another process.Use exec
along with fork
when you want to run a command, don't care about its output, and don't want to wait for it to return. system
is really just
sub my_system {
die "could not fork\n" unless defined(my $pid = fork);
return waitpid $pid, 0 if $pid; #parent waits for child
exec @_; #replace child with new process
}
You may also want to read the waitpid
and perlipc
manuals.
open
: run a process and create a pipe to its STDIN or STDERRUse open
when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).
#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
or die "could not open $filename: $!";
#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
or die "could not open $filename: $!";
Use IPC::Open2
when you need to read from and write to a process's STDIN and STDOUT.
use IPC::Open2;
open2 my $out, my $in, "/usr/bin/bc"
or die "could not run bc";
print $in "5+6\n";
my $answer = <$out>;
use IPC::Open3
when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.
If you are going to be sorting this array in more than one place, it may make sense to make your array type Comparable.
class MyImageType: Comparable, Printable {
var fileID: Int
// For Printable
var description: String {
get {
return "ID: \(fileID)"
}
}
init(fileID: Int) {
self.fileID = fileID
}
}
// For Comparable
func <(left: MyImageType, right: MyImageType) -> Bool {
return left.fileID < right.fileID
}
// For Comparable
func ==(left: MyImageType, right: MyImageType) -> Bool {
return left.fileID == right.fileID
}
let one = MyImageType(fileID: 1)
let two = MyImageType(fileID: 2)
let twoA = MyImageType(fileID: 2)
let three = MyImageType(fileID: 3)
let a1 = [one, three, two]
// return a sorted array
println(sorted(a1)) // "[ID: 1, ID: 2, ID: 3]"
var a2 = [two, one, twoA, three]
// sort the array 'in place'
sort(&a2)
println(a2) // "[ID: 1, ID: 2, ID: 2, ID: 3]"
since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.
df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,
or alternatively
df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters
Look at these to build a solution more or less from scratch:
You always have the option of calling external tools from Java using the exec()
and similar methods. For instance, you could use wget
, or cURL
.
Then if you want to go into more fully-fledged stuff, thankfully the need for automated web-testing as given us very practical tools for this. Look at:
Some other libs are purposefully written with web-scraping in mind:
Java is a language, but also a platform, with many other languages running on it. Some of which integrate great syntactic sugar or libraries to easily build scrapers.
Check out:
If you know of a great library for Ruby (JRuby, with an article on scraping with JRuby and HtmlUnit) or Python (Jython) or you prefer these languages, then give their JVM ports a chance.
Some other similar questions:
As @EastOcean said, We can add it by choosing Run/Debug configurations option. In my case, I have to set configuration for junit. So on clicking Edit configurations option, a pop up window is displayed. Then followed the below steps:
Save and run.
Thank you.
if you are trying to get the elements only but not the functions then this code can help you
this.getKeys = function() {
var keys = new Array();
for(var key in this) {
if( typeof this[key] !== 'function') {
keys.push(key);
}
}
return keys;
}
this is part of my implementation of the HashMap and I only want the keys, this
is the hashmap object that contains the keys
If you have more than one element with the same ID, then you have invalid HTML.
But you can acheive the same result using classes instead. That's what they're designed for.
<input class='b' ... >
You can give it an ID as well if you need to, but it should be unique.
Once you've got the class in there, you can reference it with a dot instead of the hash, like so:
var value = $('#a .b').val();
or
var value = $('#a input.b').val();
which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).
Does not work in Chrome, but this other answers suggests a solution via a plugin:
Looks like I'm a bit late but for others with this issue try this code
p { font-size: 3vmax; }
use whatever tag you prefer and size you prefer (replace the 3)
p { font-size: 3vmin; }
is used for a max size.
if you want to current script filename as your title tag
include the function in your project
function setTitle($requestUri)
{
$explodeRequestUri = explode("/", $requestUri);
$currentFileName = end($explodeRequestUri);
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $currentFileName);
$explodeCurrentFileName = explode("-", $withoutExt);
foreach ($explodeCurrentFileName as $curFileValue)
{
$fileArrayName[] = ucfirst($curFileValue);
}
echo implode(" ", $fileArrayName);
}
and in your html include the function script and replace your title tag with this
<title>Your Project Name -
<?php setTitle($_SERVER['REQUEST_URI']); ?>
</title>
it works on php7 and above but i dont have any idea about php 5.* Hope it helps
My favorite example is "int Num = 5" here your variable is 1. defined as int 2. declared as Num and 3. instantiated with a value of five. We
A class or struct allows you to change how objects will be defined when it is later used. For example
When we learn programming these two terms are often confused because we often do both at the same time.
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
@RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml
resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the @StringHandler
annotation to the setTitle
method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion
class.
Step 4: Use the generated class in the custom view's init
method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle
will be called with "Hello, World!"
as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
Simply set includeantruntime="false"
:
<javac includeantruntime="false" ...>...</javac>
If you have to use the javac
-task multiple times you might want to consider using PreSetDef
to define your own javac
-task that always sets includeantruntime="false"
.
From http://www.coderanch.com/t/503097/tools/warning-includeantruntime-was-not-set:
That's caused by a misfeature introduced in Ant 1.8. Just add an attribute of that name to the javac task, set it to false, and forget it ever happened.
From http://ant.apache.org/manual/Tasks/javac.html:
Whether to include the Ant run-time libraries in the classpath; defaults to yes, unless build.sysclasspath is set. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
You can create "everywhere" custom search engine right from the Google Custom Search homepage ( http://www.google.com/cse/ ). You should just click 'advanced', during adding new engine. There you can provide Schema.org site type. 'Thing' is most generic type, which covers all the web.
The CLSID you describe is for the Microsoft.Office.Interop.Excel.ApplicationClass. This class basically launches excel.exe through InprocServer32. If you don't have it installed then it will return the error message you received above.
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
I know that JSON.stringfy is slow when dealing with large datasets but what if you used template literals?
Example:
const a = [1, 2, 3];
const b = [1, 2, 'test'];
const a_string = Array.isArray(a) && `${a}`;
const b_string = Array.isArray(b) && `${b}`;
const result = (a === b);
console.log(result);
Taking into consideration you're using ES6 of course.
=)
Can you post a link to the HTML in question?
Ultimately you should be able to do:
div {
margin:0;
padding: 0;
}
to remove the spacing. Is this just in one particular browser or all of them?
If you have 300 columns as you mentioned in another comment, and you want to compare on all columns (assuming the columns are all the same name), you can use a NATURAL LEFT JOIN
to implicitly join on all matching column names between the two tables so that you don't have to tediously type out all join conditions manually:
SELECT a.*
FROM tbl_1 a
NATURAL LEFT JOIN tbl_2 b
WHERE b.FirstName IS NULL
You can convert datetime to string.
published_at = "{}".format(self.published_at)
From the builtin module this.py
(import this
):
s = "foobar"
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print("".join([d.get(c, c) for c in s])) # sbbone
Using np.ix_
is the most convenient way to do it (as answered by others), but here is another interesting way to do it:
>>> rows = [0, 1, 3]
>>> cols = [0, 2]
>>> a[rows].T[cols].T
array([[ 0, 2],
[ 4, 6],
[12, 14]])
Consider the Switch Function as an alternative to multiple IIf()
expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE
approach you referenced but which is not available in Access SQL.
If you want to display a calculated field as commission
:
SELECT
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
) AS commission
FROM YourTable;
If you want to store that calculated value to a field named commission
:
UPDATE YourTable
SET commission =
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
);
Either way, see whether you find Switch()
easier to understand and manage. Multiple IIf()s
can become mind-boggling as the number of conditions grows.
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
I didn't want to open another threat so ill post my problem here
Ajax wont forward value to controller, and i just cant find an error :(
-JS
<script>
$(document).ready(function () {
$("#sMarka").change(function () {
var markaId = $(this).val();
alert(markaId);
debugger
$.ajax({
type:"POST",
url:"@Url.Action("VratiModele")",
dataType: "html",
data: { "markaId": markaId },
success: function (model) {
debugger
$("#sModel").empty();
$("#sModel").append(model);
}
});
});
});
</script>
--controller
public IActionResult VratiModele(int markaId = 0)
{
if (markaId != 0)
{
List<Model> listaModela = db.Modeli.Where(m => m.MarkaId == markaId).ToList();
ViewBag.ModelVozila = new SelectList(listaModela, "ModelId", "Naziv");
}
else
{
ViewBag.Greska = markaId.ToString();
}
return PartialView();
}
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
I submitted an updated version of a patch to the PostgreSQL JDBC driver to enable this a few years back. You'll have to build the PostreSQL JDBC driver from source (after adding in the patch) to use it:
http://archives.postgresql.org/pgsql-jdbc/2008-07/msg00012.php
if you are using it in windows, be sure to add the path to the db in "" and also to use double slash \ in the path to make sure windows understands it.
enumerate
is what you are looking for.
You might also be interested in unpacking:
# The pattern
x, y, z = [1, 2, 3]
# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
print(x) # prints the numbers 28, 4, 1990
# and also
for index, (x, y) in enumerate(l):
print(x) # prints the numbers 28, 4, 1990
Also, there is itertools.count()
so you could do something like
import itertools
for index, el in zip(itertools.count(), [28, 4, 1990]):
print(el) # prints the numbers 28, 4, 1990
The 'Access-Control-Allow-Origin' header contains multiple values
when i received this error i spent tons of hours searching solution for this but nothing works, finally i found solution to this problem which is very simple. when ''Access-Control-Allow-Origin' header added more than one time to your response this error occur, check your apache.conf or httpd.conf (Apache server), server side script, and remove unwanted entry header from these files.
Do not put the src folder in the WEB-INF directory!!
Had the exact same problem and just could not find the right solution. Hope this helps somebody.
I have an .NET Core 3.1 WebApi with EF Core. Upon receiving multiple calls at the same time, the applications was trying to add and save changes to the database at the same time.
In my case the problem was that the table that the data would be saved in did not have a primary key set.
Somehow EF Core missed when the migration was ran from the application that the ID in the model was supposed to be a primary key.
I found the problem by opening the SQL Profiler and seeing that all transactions was successfully submitted to the database (from the application) but only one new row was created. The profiler also showed that some type of deadlock was happening but I couldn't see much more in the trace logs of the profiler. On further inspection I noticed that the primary key identifier was missing on the column "Id".
The exceptions I got from my application was:
This SqlTransaction has completed; it is no longer usable.
and/or
An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
In case you want to sort in more than one direction
public static void sortOutputTable(ref DataTable output)
{
DataView dv = output.DefaultView;
dv.Sort = "specialCode ASC, otherCode DESC";
DataTable sortedDT = dv.ToTable();
output = sortedDT;
}
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "ok";
}
A solution using DateTime
(that also regards the timezone).
$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
echo "OK";
}
One more reminder if you still encounter this issue after uninstall crypto and pycrypto like this
pip3 uninstall crypto
pip3 uninstall pycrypto
Just check if there is a directory named crypto(lower case) in your site-packages under /usr/local/lib/python3.9/site-packages, make sure the python version your used and the right site-packages path, then remove the crypto directory, the try to install again.
The problem seems to be in the way how ng-model
works with input
and overwrites the name
object, making it lost for ng-repeat
.
As a workaround, one can use the following code:
<div ng-repeat="name in names">
Value: {{name}}
<input ng-model="names[$index]">
</div>
Hope it helps