Using pure Javascript:
Don't need to pass this
to the SomeDeleteRowFunction()
:
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>
The onclick function:
function SomeDeleteRowFunction() {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
}
Another way is:
f = open("|ls")
foo = f.read()
Note that's the "pipe" character before "ls" in open. This can also be used to feed data into the programs standard input as well as reading its standard output.
In batch file:
1 @echo off(solo)=>output nothing
2 echo off(solo)=> the “echo off” shows in the command line
3 echo off(then echo something) =>
4 @echo off(then echo something)=>
See, echo off(solo), means no output in the command line, but itself shows; @echo off(solo), means no output in the command line, neither itself;
Here on a openSuse 12.3 the solution was installing the 32-bit version of libaio in addition. Oracle seems to need this now, although on 12.1 it run without the 32-bit version.
This is much easier than you're making it. The text node will not have the literal string " "
in it, it'll have have the corresponding character with code 160.
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
textNode.nodeValue = replaceNbsps(textNode.nodeValue);
UPDATE
Even easier:
textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");
While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory.
Just follow below step to fix issue.
check composer status using : composer -v
First, download the Laravel installer using Composer:
composer global require "laravel/installer"
Please check with below command:
php artisan serve
still not work then create new project with existing code. using LINK
Should anyone face the same problem.
Do this: str.substring (...(trim()) ;
Hope it helps somebodies
Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.
But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.
$("#google").click(function() {
if (situation) {
// ...
} else {
// ...
}
});
With jquery you could do to sth. like this, which will simply switch classes.
$('.showhide').click(function() {
$(this).removeClass('myclass');
$(this).addClass('showhidenew');
});
If you want to switch classes back and forth on each click, you can use toggleClass, like so:
$('.showhide').click(function() {
$(this).toggleClass('myclass');
$(this).toggleClass('showhidenew');
});
You absolutely need to make a new tuple -- then you can rebind the name (or whatever reference[s]) from the old tuple to the new one. The +=
operator can help (if there was only one reference to the old tuple), e.g.:
thetup += ('1200.00',)
does the appending and rebinding in one fell swoop.
Try using the trigger property for this:
$('select').select2().trigger('change');
I was searching for how to do this on a much newer version of xcode than the original question and while the answers here got me where I needed to go, they aren't quite accurate for location anymore. Xcode 11.3.1, you need to go into Preferences -> Components, then select the desired Simulators. You can also select tvOS and watchOS similators from the same window.
You have your print() statement in the for()
loop, It should be after so that it only prints once. the way it currently is, every time the max changes it prints a max
.
In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.
In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.
You can refer to Difference between three tier vs. n-tier
HTML: Use names as
<input name="levels[level][]">
<input name="levels[build_time][]">
PHP:
$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
foreach ($array[$fieldKey] as $key=>$value) {
$newArray[$key][$fieldKey] = $value;
}
}
$newArray will hold data as you want
Array (
[0] => Array ( [level] => 1 [build_time] => 123 )
[1] => Array ( [level] => 2 [build_time] => 456 )
)
Most people know by now that System.Reflection.Assembly.LoadWithPartialName
is deprecated, but it turns out that Add-Type -AssemblyName Microsoft.VisualBasic
does not behave much better than LoadWithPartialName
:
Rather than make any attempt to parse your request in the context of your system, [Add-Type] looks at a static, internal table to translate the "partial name" to a "full name".
If your "partial name" doesn't appear in their table, your script will fail.
If you have multiple versions of the assembly installed on your computer, there is no intelligent algorithm to choose between them. You are going to get whichever one appears in their table, probably the older, outdated one.
If the versions you have installed are all newer than the obsolete one in the table, your script will fail.
Add-Type has no intelligent parser of "partial names" like
.LoadWithPartialNames
.
What Microsoft's .Net teams says you're actually supposed to do is something like this:
Add-Type -AssemblyName 'Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Or, if you know the path, something like this:
Add-Type -Path 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualBasic\v4.0_10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualBasic.dll'
That long name given for the assembly is known as the strong name, which is both unique to the version and the assembly, and is also sometimes known as the full name.
But this leaves a couple questions unanswered:
How do I determine the strong name of what's actually being loaded on my system with a given partial name?
[System.Reflection.Assembly]::LoadWithPartialName($TypeName).Location;
[System.Reflection.Assembly]::LoadWithPartialName($TypeName).FullName;
These should also work:
Add-Type -AssemblyName $TypeName -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
If I want my script to always use a specific version of a .dll but I can't be certain of where it's installed, how do I determine what the strong name is from the .dll?
[System.Reflection.AssemblyName]::GetAssemblyName($Path).FullName;
Or:
Add-Type $Path -PassThru | Select-Object -ExpandProperty Assembly | Select-Object -ExpandProperty FullName -Unique
If I know the strong name, how do I determine the .dll path?
[Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a').Location;
And, on a similar vein, if I know the type name of what I'm using, how do I know what assembly it's coming from?
[Reflection.Assembly]::GetAssembly([Type]).Location
[Reflection.Assembly]::GetAssembly([Type]).FullName
How do I see what assemblies are available?
I suggest the GAC PowerShell module. Get-GacAssembly -Name 'Microsoft.SqlServer.Smo*' | Select Name, Version, FullName
works pretty well.
Add-Type
uses?This is a bit more complex. I can describe how to access it for any version of PowerShell with a .Net reflector (see the update below for PowerShell Core 6.0).
First, figure out which library Add-Type
comes from:
Get-Command -Name Add-Type | Select-Object -Property DLL
Open the resulting DLL with your reflector. I've used ILSpy for this because it's FLOSS, but any C# reflector should work. Open that library, and look in Microsoft.Powershell.Commands.Utility
. Under Microsoft.Powershell.Commands
, there should be AddTypeCommand
.
In the code listing for that, there is a private class, InitializeStrongNameDictionary()
. That lists the dictionary that maps the short names to the strong names. There's almost 750 entries in the library I've looked at.
Update: Now that PowerShell Core 6.0 is open source. For that version, you can skip the above steps and see the code directly online in their GitHub repository. I can't guarantee that that code matches any other version of PowerShell, however.
Update 2: Powershell 7+ does not appear to have the hash table lookup any longer. Instead they use a LoadAssemblyHelper()
method which the comments call "the closest approximation possible" to LoadWithPartialName. Basically, they do this:
loadedAssembly = Assembly.Load(new AssemblyName(assemblyName));
Now, the comments also say "users can just say Add-Type -AssemblyName Forms
(instead of System.Windows.Forms)". However, that's not what I see in Powershell v7.0.3 on Windows 10 2004.
# Returns an error
Add-Type -AssemblyName Forms
# Returns an error
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('Forms'))
# Works fine
Add-Type -AssemblyName System.Windows.Forms
# Works fine
[System.Reflection.Assembly]::Load([System.Reflection.AssemblyName]::new('System.Windows.Forms'))
So the comments appear to be a bit of a mystery.
I don't know exactly what the logic is in Assembly.Load(AssemblyName)
when there is no version or public key token specified. I would expect that this has many of the same problems that LoadWithPartialName does like potentially loading the wrong version of the assembly if you have multiple installed.
For anybody coming here looking for Visual studio 2012:
Download and Install Reference Assistant for Visual Studio 11
Later you can do:
@user1417684 and @chris-foster are right!
excerpt from working code (without error handling):
var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel = mongoose.model('items', ItemSchema);
var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {
var new_item = new ItemModel(new_item);
new_item.subitem = new_sub_item._id;
new_item.save(function (error, new_item) {
// so this is a valid way to populate via the Model
// as documented in comments above (here @stack overflow):
ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
callback(new_item.toObject());
});
// or populate directly on the result object
new_item.populate('subitem', function(error, new_item) {
callback(new_item.toObject());
});
});
});
You can use the following formula,
=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")
The thing I'd found confusing about -prune
is that it's an action (like -print
), not a test (like -name
). It alters the "to-do" list, but always returns true.
The general pattern for using -prune
is this:
find [path] [conditions to prune] -prune -o \
[your usual conditions] [actions to perform]
You pretty much always want the -o
(logical OR) immediately after -prune
, because that first part of the test (up to and including -prune
) will return false for the stuff you actually want (ie: the stuff you don't want to prune out).
Here's an example:
find . -name .snapshot -prune -o -name '*.foo' -print
This will find the "*.foo" files that aren't under ".snapshot" directories. In this example, -name .snapshot
makes up the [conditions to prune]
, and -name '*.foo' -print
is [your usual conditions]
and [actions to perform]
.
Important notes:
If all you want to do is print the results you might be used to leaving out the -print
action. You generally don't want to do that when using -prune
.
The default behavior of find is to "and" the entire expression with the -print
action if there are no actions other than -prune
(ironically) at the end. That means that writing this:
find . -name .snapshot -prune -o -name '*.foo' # DON'T DO THIS
is equivalent to writing this:
find . \( -name .snapshot -prune -o -name '*.foo' \) -print # DON'T DO THIS
which means that it'll also print out the name of the directory you're pruning, which usually isn't what you want. Instead it's better to explicitly specify the -print
action if that's what you want:
find . -name .snapshot -prune -o -name '*.foo' -print # DO THIS
If your "usual condition" happens to match files that also match your prune condition, those files will not be included in the output. The way to fix this is to add a -type d
predicate to your prune condition.
For example, suppose we wanted to prune out any directory that started with .git
(this is admittedly somewhat contrived -- normally you only need to remove the thing named exactly .git
), but other than that wanted to see all files, including files like .gitignore
. You might try this:
find . -name '.git*' -prune -o -type f -print # DON'T DO THIS
This would not include .gitignore
in the output. Here's the fixed version:
find . -name '.git*' -type d -prune -o -type f -print # DO THIS
Extra tip: if you're using the GNU version of find
, the texinfo page for find
has a more detailed explanation than its manpage (as is true for most GNU utilities).
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
When you have a lot of variables that don't need escaping, you can use an autoescape
block:
{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
You can use -[NSDictionary allKeys]
to access all the keys and loop through it.
Came across the same issue and in my case (Java project), I had to include all the dependent jars in the project's libraries section.
File -> Project Structure -> Libraries
I had to add my project dependent jars in the above section (for example; project/web/lib/). After doing so, all resolved fine. I hope this will help someone.
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
The above command worked for me even when the following error happens:
Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.
I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.
#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder
Try this:
<button (click)="click()">Click me</button>
<input class="txt" type="password" [(ngModel)]="input_pw" [ngClass]="{'hidden': isHidden}" />
component.ts:
isHidden: boolean = false;
click(){
this.isHidden = !this.isHidden;
}
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
Since C++11, you can copy arrays directly with std::array
:
std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B
Here is the documentation about std::array
Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');
Dec 4, 2020 4:58 PM
moment.locale(); // en
moment().format('LT'); // 4:59 PM
moment().format('LTS'); // 4:59:47 PM
moment().format('L'); // 12/08/2020
moment().format('l'); // 12/8/2020
moment().format('LL'); // December 8, 2020
moment().format('ll'); // Dec 8, 2020
moment().format('LLL'); // December 8, 2020 4:59 PM
moment().format('lll'); // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
Use g++
g++ -o hi hi.cpp
g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.
make sure you have added this dependency in your pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
One way to do that is to use a counter:
ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) {
...
if (--size == 0) {
// Last item.
...
}
}
Edit
Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for
loop or the iterator
, as everything you win when using the Java5 syntax will be lost in the loop itself...
for (int i = 0; i < list.size(); i++) {
...
if (i == (list.size() - 1)) {
// Last item...
}
}
or
for (Iterator it = list.iterator(); it.hasNext(); ) {
...
if (!it.hasNext()) {
// Last item...
}
}
You can use the application called Supervisor. In supervisor config you can define multiple services and ways to execute the same.
For Java and Spring boot applications the command would be
java -jar springbootapp.jar
.
Options can be provided to keep the application running always.So if the EC2 restart then Supervisor will restart you application
I found Supervisor easy to use compared to putting startup scripts in /etc/init.d/.The startup scripts would hang or go into waiting state in case of errors .
You can do this in one line, using the conditional operator and the fact that you can cast null
to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse
):
Pre C#7:
int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;
With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.
int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;
The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ?
in a URI, you should use the $_GET[]
array.
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
Use for
instead of foreach
. foreach
doesn't expose its inner workings, it enumerates anything that is IEnumerable
(which doesn't have to have an index at all).
for (int i=0; i<arr.Length; i++)
{
...
}
Besides, if what you're trying to do is find the index of a particular item in the list, you don't have to iterate it at all by yourself. Use Array.IndexOf(item)
instead.
for i in range[1,10]:
string = "string" + str(i)
The str(i)
function converts the integer into a string.
If you're looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate )
accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate )
uses that timestamp and PHP's date
function to turn that timestamp back into MySQL's standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
You can use Batch update but queries must be action(i.e. insert,update and delete) queries
Statement s = c.createStatement();
String s1 = "update emp set name='abc' where salary=984";
String s2 = "insert into emp values ('Osama',1420)";
s.addBatch(s1);
s.addBatch(s2);
s.executeBatch();
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
I found this SQL statement to be a useful place to start (sorry I can't attribute this to the original author; I found it somewhere on the internet):
SELECT * FROM
(SELECT
sql_fulltext,
sql_id,
elapsed_time,
child_number,
disk_reads,
executions,
first_load_time,
last_load_time
FROM v$sql
ORDER BY elapsed_time DESC)
WHERE ROWNUM < 10
/
This finds the top SQL statements that are currently stored in the SQL cache ordered by elapsed time. Statements will disappear from the cache over time, so it might be no good trying to diagnose last night's batch job when you roll into work at midday.
You can also try ordering by disk_reads and executions. Executions is useful because some poor applications send the same SQL statement way too many times. This SQL assumes you use bind variables correctly.
Then, you can take the sql_id
and child_number
of a statement and feed them into this baby:-
SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id', &child));
This shows the actual plan from the SQL cache and the full text of the SQL.
you can use
val resultDf = PersonDf.join(ProfileDf, PersonDf("personId") === ProfileDf("personId"))
or shorter and more flexible (as you can easely specify more than 1 columns for joining)
val resultDf = PersonDf.join(ProfileDf,Seq("personId"))
Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.
This link is helpful: How to read HTML as XML?
You specified both jQuery and Javascript in the tags so here's both approaches.
jQuery
var selector = '.nav li';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/
Pure Javascript:
var selector, elems, makeActive;
selector = '.nav li';
elems = document.querySelectorAll(selector);
makeActive = function () {
for (var i = 0; i < elems.length; i++)
elems[i].classList.remove('active');
this.classList.add('active');
};
for (var i = 0; i < elems.length; i++)
elems[i].addEventListener('mousedown', makeActive);
Fiddle: http://jsfiddle.net/rn3nc/1
jQuery with event delegation:
Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new li
s to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav
:
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
Fiddle: http://jsfiddle.net/bvf9u/1/
The subtle difference is that the handler is bound to the .nav
now, so when you click the li
the event bubbles up the DOM to the .nav
which invokes the handler if the element clicked matches your selector
argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.
It's really quite interesting. Read more about it here: http://api.jquery.com/on/
No. gettimeofday should NEVER be used to measure time.
This is causing bugs all over the place. Please don't add more bugs.
Include <tchar.h>
which has the line:
#define _tWinMain wWinMain
Something that I didn't see mentioned in the other answers here is how you deal with unwinding when you don't know where the initial segue originated, which to me is an even more important use case. For example, say you have a help view controller (H) that you display modally from two different view controllers (A and B):
A ? H
B ? H
How do you set up the unwind segue so that you go back to the correct view controller? The answer is that you declare an unwind action in A and B with the same name, e.g.:
// put in AViewController.swift and BViewController.swift
@IBAction func unwindFromHelp(sender: UIStoryboardSegue) {
// empty
}
This way, the unwind will find whichever view controller (A or B) initiated the segue and go back to it.
In other words, think of the unwind action as describing where the segue is coming from, rather than where it is going to.
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
You can't import from the parent directory without some voodoo. Here's yet another way that works with at least Python 3.6.
First, have a file test/context.py with the following content:
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
Then have the following import in the file test/test_antigravity.py:
import unittest
try:
import context
except ModuleNotFoundError:
import test.context
import antigravity
Note that the reason for this try-except clause is that
With this trickery they both work.
Now you can run all the test files within test directory with:
$ pwd
/projects/new_project
$ python -m unittest
or run an individual test file with:
$ cd test
$ python test_antigravity
Ok, it's not much prettier than having the content of context.py within test_antigravity.py, but maybe a little. Suggestions are welcome.
Code example follows. Last string suitable for use in filenames.
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> str(datetime.now(tzlocal()))
'2015-04-01 11:19:47.980883-07:00'
>>> str(datetime.now(tzlocal())).replace(' ','-').replace(':','').replace('.','-')
'2015-04-01-111947-981879-0700'
>>>
I suggest ElementTree
. There are other compatible implementations of the same API, such as lxml
, and cElementTree
in the Python standard library itself; but, in this context, what they chiefly add is even more speed -- the ease of programming part depends on the API, which ElementTree
defines.
First build an Element instance root
from the XML, e.g. with the XML function, or by parsing a file with something like:
import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()
Or any of the many other ways shown at ElementTree
. Then do something like:
for type_tag in root.findall('bar/type'):
value = type_tag.get('foobar')
print(value)
And similar, usually pretty simple, code patterns.
Because booleans have two values: true
or false
. Note that these are not strings, but actual boolean literals.
1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.
EDIT: Note that you can easily write a conversion function if you want:
public static boolean intToBool(int input)
{
if (input < 0 || input > 1)
{
throw new IllegalArgumentException("input must be 0 or 1");
}
// Note we designate 1 as true and 0 as false though some may disagree
return input == 1;
}
Though I wouldn't recommend this. Note how you cannot guarantee that an int
variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean
variable is always either true
or false
and it's obvious which one means true. :-)
So instead of the conversion function, get used to using boolean
variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.
In addition to the missing quotes around 100Mb
in the last else
, you also want to quote the constants in your if-statements if tSizeAns == "1":
, because raw_input
returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else
in the way you use it is basically equivalent to a case
or switch
in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns
is guaranteed to be in the range of tSize
. Otherwise you would have to either catch the KeyError
exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"} try: tSize = lookup[tSizeAns] except KeyError: tSize = "100Mb"
or
from collections import defaultdict [...] lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"}) tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.
RMStore is a lightweight iOS library for In-App Purchases. It wraps StoreKit API and provides you with handy blocks for asynchronous requests. Purchasing a product is as easy as calling a single method.
For the advanced users, this library also provides receipt verification, content downloads and transaction persistence.
You should use pygame like this:
from pygame import mixer
mixer.init()
mixer.music.load("path/to/music/file.mp3") # Music file can only be MP3
mixer.music.play()
# Then start a infinite loop
while True:
print("")
ObservableCollection < T > has a constructor overload which takes IEnumerable < T >
Example for a List of int
:
ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);
One more example for a List of ObjectA
:
ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
myFile = open('today','r')
ips = {}
for line in myFile:
parts = line.split()
if parts[1] == 'Failure':
ips.setdefault(parts[0], 0)
ips[parts[0]] += 1
of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
of.write(k+'\n')
Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.
Try this:
ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName'
Have you looked into ChartDirector for Python?
I can't speak about this one, but I've used ChartDirector for PHP and it's pretty good.
Basic difference is that Google App Engine (GAE) is a Platform as a Service (PaaS) whereas Google Compute Engine (GCE) is an Infrastructure as a Service (IaaS).
To run your application in GAE you just need to write your code and deploy it into GAE, no other headache. Since GAE is fully scalable, it will automatically acquire more instances in case the traffic goes higher and decrease the instances when traffic decreases. You will be charged for the resources you really use, I mean, you will be billed for the Instance-Hours, Transferred Data, Storage etc your app really used. But the restriction is, you can create your application in only Python, PHP, Java, NodeJS, .NET, Ruby and **Go.
On the other hand, GCE provides you full infrastructure in the form of Virtual Machine. You have complete control over those VMs' environment and runtime as you can write or install any program there. Actually GCE is the way to use Google Data Centers virtually. In GCE you have to manually configure your infrastructure to handle scalability by using Load Balancer.
Both GAE and GCE are part of Google Cloud Platform.
Update: In March 2014 Google announced a new service under App Engine named Managed Virtual Machine. Managed VMs offers app engine applications a bit more flexibility over app platform, CPU and memory options. Like GCE you can create a custom runtime environment in these VMs for app engine application. Actually Managed VMs of App Engine blurs the frontier between IAAS and PAAS to some extent.
From the documentation:
/is
Includes the same files./it
Includes "tweaked" files.
"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.
robocopy src dst sample.txt /is # copy if attributes are equal
robocopy src dst sample.txt /it # copy if attributes differ
robocopy src dst sample.txt /is /it # copy irrespective of attributes
This answer on Super User has a good explanation of what kind of files the selection parameters match.
With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy
generated in my tests I would consider this a bug.
PS C:\temp> New-Item src -Type Directory >$null PS C:\temp> New-Item dst -Type Directory >$null PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Modified 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Same 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\src\sample.txt test001 PS C:\temp> Get-Content .\dst\sample.txt test002
The file is listed as copied, and since it becomes a same file after the first robocopy
run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall
). The behavior also doesn't change if the data flag is set explicitly (/copy:d
).
I had to modify the last write time to get robocopy
to actually synchronize the data.
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date) PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ 100% Newer 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\dst\sample.txt test001
An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy
to copy the data:
& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
Where-Object { $_.Trim() } |
ForEach-Object {
$f = Get-Item $_
$f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
}
& robocopy src dst /copyall /mir
Switching to xcopy
is probably your best option:
& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y
If property hibernate.ddl-auto = update
, then it will not create the tables automatically.
To create tables automatically, you need to set the property to
hibernate.ddl-auto = create
The list of option which is used in the spring boot are
validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session
none: is all other cases
So for the first time you can set it to create and then next time on-wards you should set it to update.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
Using executeUpdate()
on the Query
API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.
Consider the following example :
Employee employee= (Employee)entityManager.find(Employee.class , 1);
entityManager
.createQuery("update Employee set name = \'xxxx\' where id=1")
.executeUpdate();
After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee)
to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.
Normally , executeUpdate()
is used in the bulk update process as it is faster due to bypassing the persistent context
The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.
Employee employee= (Employee)entityManager.find(Employee.class ,1);
employee.setName("Updated Name");
Is it possible that MySql listening on the same port as JBoss?
Is there a port number given in the error message - something like Address already in use: JVM_Bind:8080
You can change the port in JBoss server.xml to test this.
Running composer dump-autoload
solves it for me.
It can be caused by a classpath contamination. Check that you /WEB-INF/lib
doesn't contain something like jsp-api-*.jar
.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.
Try this:
if ($.browser.msie)
{
// Some other solution as applies to whatever IE compatible video player used.
}
else
{
$('video')[0].pause();
}
But, consider that $.browser is deprecated, but I haven't found a comparable solution.
If you have root, delete all of the folders on the path:
/data/app-lib/
And then restart your device.
I had this issue many times, and this fix worked for me each time. It even has an XDA thread.
I write all folders, because if there is a problem with one app, there is a good chance you have this issue with other apps too. Plus, it's annoying to find just the folders of the problematic app/s .
I am not sure whether anyone faced issues with getting the whole string "test from adb". Using the escape character in front of the space worked for me.
adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test\ from\ adb" -n com.whereismywifeserver/.IntentReceiver
You can also open your js file path in the chrome browser which will only display text.
However you can dynamically create the page by including:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'myjs.js';
document.head.appendChild(script);
Now you can have access to the js variables and functions in the console.
Now when you explore the elements it should have included.
So not i guess you dont need a html file.
Petar Ivanov's answer to replace a character at a specific index in a string question
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Regex-based searching is sometimes faster than generator approach:
RRR = re.compile(r'(.*)\n')
def f4(arg):
return (i.group(1) for i in RRR.finditer(arg))
Try this:
From this question.
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
Use STATS in the BACKUP command if it is just a script.
Inside code it is a bit more complicated. In ODBC for example, you set SQL_ATTR_ASYNC_ENABLE and then look for SQL_STILL_EXECUTING return code, and do some repeated calls of SQLExecDirect until you get a SQL_SUCCESS (or eqiv).
from CSS tricks:
https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
const originalString = `
<div>
<p>Hey that's <span>somthing</span></p>
</div>
`;
const strippedString = originalString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
_x000D_
IB and Swift
Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,
the goal is to move a subview (let's say green) to the top.
In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.
Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.
There are a couple of different ways to do this programmatically.
Method 1
yellowView.bringSubviewToFront(greenView)
This method is the programmatic equivalent of the IB answer above.
It only works if the subviews are siblings of each other.
An array of the subviews is contained in yellowView.subviews
. Here, bringSubviewToFront
moves the greenView
from index 0
to 2
. This can be observed with
print(yellowView.subviews.indexOf(greenView))
Method 2
greenView.layer.zPosition = 1
0
for all the other views, the result is that the greenView
looks like it is on top. However, it still remains at index 0
of the yellowView.subviews
array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.zPosition
could be set to CGFloat.greatestFiniteMagnitude
(CGFloat(FLT_MAX)
in older versions of Swift) to ensure that it is on top.If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
To make an app with NO status bars,
Click info.plist, right-click to "Add row".
Add these two, with these settings:
That's all there is to it.
Now (on Boostrap 3 and 4) its simply :
.carousel-inner img {
margin: auto;
}
Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.
Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.
Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.
In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.
If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.
You could create two separate stylesheets and include one of them based on the comparison result
In one of the you can put
background-position : 150px 8px;
In the other one
background-position : 4px 8px;
I think that the only check you can perform in CSS is browser recognition:
Note that if variable is list of lists, some approaches would fail. For example:
v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails
v2
For the general case, use
removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]
v2
To whoever is reading this, check out createMany()
method.
/**
* Create a Collection of new instances of the related model.
*
* @param array $records
* @return \Illuminate\Database\Eloquent\Collection
*/
public function createMany(array $records)
{
$instances = $this->related->newCollection();
foreach ($records as $record) {
$instances->push($this->create($record));
}
return $instances;
}
You can solve it very simple way just invoking the input. However, if you press Enter
then the console will disapper again. Simply use this Console.ReadLine();
or Console.Read();
In Windows git bash, I fixed it by restarting git bash
It can also be done this way:
figure(xx);
set(gcf, 'name', 'Name goes here')
gcf
gets the current figure handle.
For multivalue map you can do like below (using java 8 stream api's)
Url encoding has been taken cared in this.
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
String urlQueryString = params.entrySet()
.stream()
.flatMap(stringListEntry -> stringListEntry.getValue()
.stream()
.map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
UriUtils.encode(s, StandardCharsets.UTF_8.toString())))
.collect(Collectors.joining("&"));
I tested Github Flavored Markdown for a while and can summarize with four rules:
-
For example, if your section is named this:
## 1.1 Hello World
Create a link to it this way:
[Link](#11-hello-world)
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
Check out the language reference:
http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
Following is the method I found:
1) Make a list of files with relative paths in a file (say FilesList.txt) as follows (either space separated or line separated):
foo/AccessTestInterface.java
foo/goo/AccessTestInterfaceImpl.java
2) Use the command:
javac @FilesList.txt -d classes
This will compile all the files and put the class files inside classes directory.
Now easy way to create FilesList.txt is this: Go to your source root directory.
dir *.java /s /b > FilesList.txt
But, this will populate absolute path. Using a text editor "Replace All" the path up to source directory (include \ in the end) with "" (i.e. empty string) and Save.
copy and paste this xml instead of your xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:background="@android:drawable/btn_dropdown"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:background="@android:drawable/btn_dropdown"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
</RelativeLayout>
As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory
which shows the exact version and patches installed.
For example this is a quick oneliner which should only return the version number:
$ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'
Here is an answer that works with data.table and is simpler. This assumes your data.table is named yourDF
:
j1 <- max.col(yourDF[, .(V1, V2, V3, V4)], "first")
yourDF$newCol <- c("V1", "V2", "V3", "V4")[j1]
Replace ("V1", "V2", "V3", "V4")
and (V1, V2, V3, V4)
with your column names
To Validate Text Box Accept Ascii Only use this Pattern
[\x00-\x7F]+
Currently the best documentation is the source. You can take a look at it here (attrs.xml).
You can define attributes in the top <resources>
element or inside of a <declare-styleable>
element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable>
element it can be used outside of it and you cannot create another attribute with the same name of a different type.
An <attr>
element has two xml attributes name
and format
. name
lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute
. The format
attribute can have different values depending on the 'type' of attribute you want.
You can set the format to multiple types by using |
, e.g., format="reference|color"
.
enum
attributes can be defined as follows:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag
attributes are similar except the values need to be defined so they can be bit ored together:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
In addition to attributes there is the <declare-styleable>
element. This allows you to define attributes a custom view can use. You do this by specifying an <attr>
element, if it was previously defined you do not specify the format
. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name
, as follows.
An example of a custom view <declare-styleable>
:
<declare-styleable name="MyCustomView">
<attr name="my_custom_attribute" />
<attr name="android:gravity" />
</declare-styleable>
When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android"
. You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto"
.
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:whatever="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.example.mypackage.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);
//do something with str
a.recycle();
}
The end. :)
rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position-x', newValueX);
$('#carousel').css('background-position-y', newValue);
}, function(){
$('#carousel').css('background-position-x', oldValueX);
$('#carousel').css('background-position-y', oldValueY);
});
});
It took about 4 hours of banging my head against it to come to that aggravating realization.
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
The error is that you cannot initialize a static const char*
within the class. You can only initialize integer variables there.
You need to declare the member variable in the class, and then initialize it outside the class:
// header file
class Foo {
static const char *SOMETHING;
// rest of class
};
// cpp file
const char *Foo::SOMETHING = "sommething";
If this seems annoying, think of it as being because the initialization can only appear in one translation unit. If it was in the class definition, that would usually be included by multiple files. Constant integers are a special case (which means the error message perhaps isn't as clear as it might be), and compilers can effectively replace uses of the variable with the integer value.
In contrast, a char*
variable points to an actual object in memory, which is required to really exist, and it's the definition (including initialization) which makes the object exist. The "one definition rule" means you therefore don't want to put it in a header, because then all translation units including that header would contain the definition. They could not be linked together, even though the string contains the same characters in both, because under current C++ rules you've defined two different objects with the same name, and that's not legal. The fact that they happen to have the same characters in them doesn't make it legal.
UPDATE YourTable SET columnName = null WHERE YourCondition
Had the same problem. For me it worked to call
viewPage.setAdapter( adapter );
again which caused reinstantiating the pages again.
i'll make an example,
first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit)
, and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),
setting up the netcat server to listen on port 9999: nc -l 9999
now hitting http://127.0.0.1:9999 in firefox, i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
now let us compare that with this simple script:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);
i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*
there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent
specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding
header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
now running that code, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1
and voila! our php-emulated browser
GET request should now be indistinguishable from the real firefox GET request :)
this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding
header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
running that, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)
Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?
update PRODUCTION p,
staging s
set p.name = s.name
p.count = s.count
where p.id = s.id
This would work assuming the id column matches on both tables.
there is data export option in MySQL workbech
I've had this error when there's been different RxJS-versions across projects. The internal checks in RxJS fails because there are several different Symbol_observable
. Eventually this function throws once called from a flattening operator like switchMap
.
Try importing symbol-observable in some entry point.
// main index.ts
import 'symbol-observable';
This is the best solution
numeral().unformat('0.02'); = 0.02
Try this simple function to add an dictionary item if it does not exist or update when it exists:
public void AddOrUpdateDictionaryEntry(string key, int value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
This is the same as dict[key] = value.
This resolved the issue for me... Build|Clean project Refactor|Remove unused resources I am still a beginner at this so I cannot explain why this might have worked. It was an arbitrary choice on my part; it was simple, did not require detailed changes and I just thought it might help :)
Using an UNREFERENCED_PARAMETER(p)
could work. I know it is defined in WinNT.h for Windows systems and can easily be defined for gcc as well (if it doesn't already have it).
UNREFERENCED PARAMETER(p)
is defined as
#define UNREFERENCED_PARAMETER(P) (P)
in WinNT.h.
globalThis is the future.
First, TypeScript files have two kinds of scopes
If your file hasn't any import
or export
line, this file would be executed in global scope that all declaration in it are visible outside this file.
So we would create global variables like this:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
All magic come from
var
. Replacevar
withlet
orconst
won't work.
If your file has any import
or export
line, this file would be executed within its own scope that we need to extend global by declaration-merging.
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
You can see more about module in official docs
I found the solution ! Delete folder named package in project directory and then rebuild to run it.
In my case port was already used by windows IIS service. You can check if port is being already used from cmd. Open cmd and run this command:
netstat -ano
If it is being used by IIS you can stop it by following command. Open cmd as administrator, then:
iisreset /stop
Now try running XAMPP, it should work.
Here is a solution where you can add a gradient and change its colours using only CSS:
// JS is not required for the solution. It's used only for the interactive demo._x000D_
const svg = document.querySelector('svg');_x000D_
document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green'));_x000D_
document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red'));
_x000D_
svg.green stop:nth-child(1) {_x000D_
stop-color: #60c50b;_x000D_
}_x000D_
svg.green stop:nth-child(2) {_x000D_
stop-color: #139a26;_x000D_
}_x000D_
_x000D_
svg.red stop:nth-child(1) {_x000D_
stop-color: #c84f31;_x000D_
}_x000D_
svg.red stop:nth-child(2) {_x000D_
stop-color: #dA3448;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<linearGradient id="gradient">_x000D_
<stop offset="0%" />_x000D_
<stop offset="100%" />_x000D_
</linearGradient>_x000D_
<rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>_x000D_
_x000D_
<br/>_x000D_
<button id="greenButton">Green</button>_x000D_
<button id="redButton">Red</button>
_x000D_
While this isn't currently available, this fascinating article discusses the use of the Shadow DOM, which is a technique used by browsers to limit how far cascading style sheets cascade, so to speak. He doesn't provide any APIs, as it seems that there are no current libraries able to provide access to this part of the DOM, but it's worth a look. There are links to mailing lists at the bottom of the article if this intrigues you.
I actually came across something like this not too long ago... check it out over on msdn (see the first answer)
in summary:
.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.
.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.
.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.
I summarized the info from the page based on the suggestion from the comments.
In my case this error caused by wrong /etc/nsswitch.conf configuration on debian.
I've been replaced string
hosts: files myhostname mdns4_minimal [NOTFOUND=return] dns
with
hosts: files dns
and everything works right now.
How About this..
string str = "The quick brown fox jumps over the lazy dog,";
StringBuilder sb = new StringBuilder(str);
sb.Remove(str.Length - 1, 1);
In SQL Server Import and Export Wizard you can adjust the source data types in the Advanced
tab (these become the data types of the output if creating a new table, but otherwise are just used for handling the source data).
The data types are annoyingly different than those in MS SQL, instead of VARCHAR(255)
it's DT_STR
and the output column width can be set to 255
. For VARCHAR(MAX)
it's DT_TEXT
.
So, on the Data Source selection, in the Advanced
tab, change the data type of any offending columns from DT_STR
to DT_TEXT
(You can select multiple columns and change them all at once).
26 % 7 (you will get remainder)
26 / 7 (you will get divisor can be float value )
26 // 7 (you will get divisor only integer value) )
Same question as @Dan - why not StringReader ?
If it has to be InputStreamReader, then:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);
Maven is trying to download m2e's lifecycle-mapping artifact, which M2E uses to determine how to process plugins within Eclipse (adding source folders, etc.). For some reason this artifact cannot be downloaded. Do you have an internet connection? Can other artifacts be downloaded from repositories? Proxy settings?
For more details from Maven, try turning M2E debug output on (Settings/Maven/Debug Output checkbox) and it might give you more details as to why it cannot download from the repository.
var sibling = node.nextSibling;
This will return the sibling immediately after it, or null no more siblings are available. Likewise, you can use previousSibling
.
[Edit] On second thought, this will not give the next div
tag, but the whitespace after the node. Better seems to be
var sibling = node.nextElementSibling;
There also exists a previousElementSibling
.
There are so many difference exist between Serializable and Externalizable but when we compare difference between custom Serializable(overrided writeObject() & readObject()) and Externalizable then we find that custom implementation is tightly bind with ObjectOutputStream class where as in Externalizable case , we ourself provide an implementation of ObjectOutput which may be ObjectOutputStream class or it could be some other like org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream
In case of Externalizable interface
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(key);
out.writeUTF(value);
out.writeObject(emp);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.key = in.readUTF();
this.value = in.readUTF();
this.emp = (Employee) in.readObject();
}
**In case of Serializable interface**
/*
We can comment below two method and use default serialization process as well
Sequence of class attributes in read and write methods MUST BE same.
// below will not work it will not work .
// Exception = java.io.StreamCorruptedException: invalid type code: 00\
private void writeObject(java.io.ObjectOutput stream)
*/
private void writeObject(java.io.ObjectOutputStream Outstream)
throws IOException {
System.out.println("from writeObject()");
/* We can define custom validation or business rules inside read/write methods.
This way our validation methods will be automatically
called by JVM, immediately after default serialization
and deserialization process
happens.
checkTestInfo();
*/
stream.writeUTF(name);
stream.writeInt(age);
stream.writeObject(salary);
stream.writeObject(address);
}
private void readObject(java.io.ObjectInputStream Instream)
throws IOException, ClassNotFoundException {
System.out.println("from readObject()");
name = (String) stream.readUTF();
age = stream.readInt();
salary = (BigDecimal) stream.readObject();
address = (Address) stream.readObject();
// validateTestInfo();
}
I have added sample code to explain better. please check in/out object case of Externalizable. These are not bound to any implementation directly.
Where as Outstream/Instream are tightly bind to classes. We can extends ObjectOutputStream/ObjectInputStream but it will a bit difficult to use.
Here is my take on the problem:
from math import sqrt
from itertools import count, islice
def is_prime(n):
return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1)))
This is a really simple and concise algorithm, and therefore it is not meant to be anything near the fastest or the most optimal primality check algorithm. It has a time complexity of O(sqrt(n))
. Head over here to learn more about primality tests done right and their history.
I'm gonna give you some insides about that almost esoteric single line of code that will check for prime numbers:
First of all, using range()
in Python 2 is really a bad idea, because it will create a list of numbers, which uses a lot of memory. Using xrange()
is better, because it creates a generator, which only needs to memorize the initial arguments you provide, and generates every number on-the-fly. If you're using
Python 3, range()
has been converted to a generator by default. By the way, this is still not the best solution: trying to call xrange(n)
for some n
such that n > 231-1
(which is the maximum value for a C long
) raises OverflowError
. Therefore the best way to create a range generator is to use itertools
:
xrange(2147483647+1) # OverflowError
from itertools import count, islice
count(1) # Count from 1 to infinity with step=+1
islice(count(1), 2147483648) # Count from 1 to 2^31 with step=+1
islice(count(1, 3), 2147483648) # Count from 1 to 3*2^31 with step=+3
You do not actually need to go all the way up to n
if you want to check if n
is a prime number. You can dramatically reduce the tests and only check from 2 to v(n)
(square root of n
). Here's an example:
Let's find all the divisors of n = 100
, and list them in a table:
2 x 50 = 100
4 x 25 = 100
5 x 20 = 100
10 x 10 = 100 <-- sqrt(100)
20 x 5 = 100
25 x 4 = 100
50 x 2 = 100
You will easily notice that, after the square root of n
, all the divisors we find were actually already found. For example 20
was already found doing 100/5
. The square root of a number is the exact mid-point where the divisors we found begin being duplicated. Therefore, to check if a number is prime, you'll only need to check from 2 to sqrt(n)
.
Why sqrt(n)-1
then, and not just sqrt(n)
? That's just because the second argument provided to itertools.islice()
is the number of iterations to execute. islice(count(a), b)
stops after b
iterations. That's the reason why:
for number in islice(count(10), 2):
print number,
# Will print: 10 11
for number in islice(count(1, 3), 10):
print number,
# Will print: 1 4 7 10 13 16 19 22 25 28
The function all(...)
is the same of the following:
def all(iterable):
for element in iterable:
if not element:
return False
return True
It literally checks for all the elements in the iterable
, returning False
when any of them evaluates to False
(which for an integer means only if it's zero). Why do we use it then? First of all, we don't need to use an additional index variable (like we would do using a loop), other than that: just for concision, there's no real need of it, but it looks way less bulky to work with only a single line of code instead of several nested lines.
I'm including an "unpacked" version of the is_prime()
function, to make it easier to understand and read:
from math import sqrt
from itertools import count, islice
def is_prime(n):
if n < 2:
return False
for number in islice(count(2), int(sqrt(n) - 1)):
if n % number == 0:
return False
return True
Instead of getViewById(), use
MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);
replacing the Menu.FIRST
with your menu item id.
Loop through the results and place each one in an array
use mysqli_fetch_all()
to get them all at one time
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
32-bit JVMs which expect to have a single large chunk of memory and use raw pointers cannot use more than 4 Gb (since that is the 32 bit limit which also applies to pointers). This includes Sun and - I'm pretty sure - also IBM implementations. I do not know if e.g. JRockit or others have a large memory option with their 32-bit implementations.
If you expect to be hitting this limit you should strongly consider starting a parallel track validating a 64-bit JVM for your production environment so you have that ready for when the 32-bit environment breaks down. Otherwise you will have to do that work under pressure, which is never nice.
Edit 2014-05-15: Oracle FAQ:
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.
(http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit)
Here's the full text article from hubbardr's dead link to my blog.
I found the following snippet while reading the source for Tempfile#initialize
in the Ruby core library:
begin
tmpname = File.join(tmpdir, make_tmpname(basename, n))
lock = tmpname + '.lock'
n += 1
end while @@cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while
modifier would be evaluated before the contents of begin...end
, but that is not the case. Observe:
>> begin
?> puts "do {} while ()"
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.
>> n = 3
=> 3
>> begin
?> puts n
>> n -= 1
>> end while n > 0
3
2
1
=> nil
While I would be happy to never see this idiom again, begin...end
is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
def expensive
@expensive ||= 2 + 2
end
Here is an ugly, but quick way to memoize something more complex:
def expensive
@expensive ||=
begin
n = 99
buf = ""
begin
buf << "#{n} bottles of beer on the wall\n"
# ...
n -= 1
end while n > 0
buf << "no more bottles of beer"
end
end
For those who don't want to create any models, use the following code:
var result = JsonConvert.DeserializeObject<
List<Dictionary<string,
Dictionary<string, string>>>>(content);
Note: This doesn't work for your JSON string. This is not a general solution for any JSON structure.
In Ubuntu 12.x, I added the following lines in $HOME/.wgetrc
http_proxy = http://uname:[email protected]:8080
use_proxy = on
I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.
<html>
<head>
<script language="javascript">
var ret;
function returnfunction()
{
alert(ret);
}
</script>
</head>
<body>
<form>
<label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
<input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
<input type="button" value="No" onClick="ret=false;returnfunction()" />
</form>
</body>
</html>
Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}
The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.
For instance:
echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7
Will result in output of:
2 3.4
-d sets the delimiter
-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7
.
use app.render
in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.
I experienced this on a div
that had a click event and after 20 some searches I found this snippet that saved my day.
-webkit-tap-highlight-color: rgba(0,0,0,0);
This disables the default button highlighting in webkit mobile browsers
You can get the example and sample code at the official site, as following:
<TextInput password={true} style={styles.default} value="abc" />
Reference: http://facebook.github.io/react-native/docs/textinput.html
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
Here is another way using onPageChangeListener
:
ViewPager pager = (ViewPager) findByViewId(R.id.viewpager);
FragmentPagerAdapter adapter = new FragmentPageAdapter(getFragmentManager);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int pageNumber) {
// Just define a callback method in your fragment and call it like this!
adapter.getItem(pageNumber).imVisible();
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Implicit declarations are not valid in C.
C99 removed this feature (present in C89).
gcc
chooses to only issue a warning by default with -std=c99
but a compiler has the right to refuse to translate such a program.
Jason Robinson's answer and Sami Eltamawy answer are excelent.
Just an improvement to complete the aproach, you should use compat ExifInterface.
com.android.support:exifinterface:${lastLibVersion}
You will be able to instantiate the ExifInterface(pior API <24) with InputStream
(from ContentResolver
) instead of uri paths avoiding "File not found exceptions"
https://android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html
Try the below code:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("time => " + dateFormat.format(cal.getTime()));
String time_str = dateFormat.format(cal.getTime());
String[] s = time_str.split(" ");
for (int i = 0; i < s.length; i++) {
System.out.println("date => " + s[i]);
}
int year_sys = Integer.parseInt(s[0].split("/")[0]);
int month_sys = Integer.parseInt(s[0].split("/")[1]);
int day_sys = Integer.parseInt(s[0].split("/")[2]);
int hour_sys = Integer.parseInt(s[1].split(":")[0]);
int min_sys = Integer.parseInt(s[1].split(":")[1]);
System.out.println("year_sys => " + year_sys);
System.out.println("month_sys => " + month_sys);
System.out.println("day_sys => " + day_sys);
System.out.println("hour_sys => " + hour_sys);
System.out.println("min_sys => " + min_sys);
Using CONCAT(CONCAT(,),)
worked for me when concatenating more than two strings.
My problem required working with date strings (only) and creating YYYYMMDD
from YYYY-MM-DD
as follows (i.e. without converting to date format):
CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD
You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true - readyState !=4
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
Not saying this is better, just another way:
$("#elem")[0].style.fontSize="20px";
In my case with the given code, I was able to parse the value of the passed parameter in this way.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
If you installed through Homebrew, try to run
brew services start mysql
The cookie API is kind of lame. Let me clarify...
You don't update cookies; you overwrite them:
document.cookie = "username=Arnold"; // Create 'username' cookie
document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"
You also don't delete cookies; you expire them by setting the expires
key to a time in the past (-1 works too).
Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
window.location.href = "/";
This worked for me. If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
Note the point density in proportional to inverse square of the radius, hence instead of picking r
from [0, r_max]
, pick from [0, r_max^2]
, then compute your coordinates as:
x = sqrt(r) * cos(angle)
y = sqrt(r) * sin(angle)
This will give you uniform point distribution on a disk.
If you want to view the progress of the dump try this:
pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME
You'll of course need 'pv' installed. This command works only on *nix.
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
Unfortunatelly, it is not so easy as Microsoft has removed advanced file association dialog in recent Windows editions. - With newer Windows versions you may only specify the application that is going to be used to open .jar file.
Fixing .jar file opening on Windows requires two steps.
Open the Control Panel, and chose "Default Programs -> Set Associations". Find .jar extension (Executable JAR file) there, and pick Java as default program to open this extension. It will probably be listed as "Java Platform(SE)". A faster alternative perhaps is straightforward right-click on a .jar file, and then change associated program by clicking on the "Change..." button.
Now open the regedit, and open the HKEY_CLASSES_ROOT\jarfile\shell\open\command
key. Luckilly for us, we may specify parameters there for the (Default)
value. On my Windows system it looks like: C:\app\32\jre7\bin\javaw.exe" -jar "%1" %*
but in most cases it is the following string: C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*
NOTES:
java.exe
there as it will open the shell window.The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
Clients can be compromised in many ways. For example a cell phone can be cloned. Having an access token expire means that the client is forced to re-authenticate to the authorization server. During the re-authentication, the authorization server can check other characteristics (IOW perform adaptive access management).
Refresh tokens allow for a client only re-authentication, where as re-authorize forces a dialog with the user which many have indicated they would rather not do.
Refresh tokens fit in essentially in the same place where normal web sites might choose to periodically re-authenticate users after an hour or so (e.g. banking site). It isn't highly used at present since most social web sites don't re-authenticate web users, so why would they re-authenticate a client?
A normal math answer.
Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:
With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.
So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.
For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.
Flat files do not allow providing meta information.
I would suggest writing out a HTML table containing the information you need, and let Excel read it instead. You can then use <b> tags to do what you ask for.
You call nextElement()
twice in your loop. This call moves the enumeration pointer forward.
You should modify your code like the following:
while (e.hasMoreElements()) {
String param = e.nextElement();
System.out.println(param);
}
You can use the maven.javadoc.skip
property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:
<properties>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties>
or as a command-line argument: -Dmaven.javadoc.skip=true
, to skip generation of the Javadocs.
HERE WordPress add custom class in wp_nav_menu links
OR
you can add class <li class='my_own_class'><a href=''>Link</a></li>
from admin panel:
Go to YOURSITEURL/wp-admin/nav-menus.php
open SCREEN OPTIONS
CSS CLASSES
, then you will see CSS Classes (optional)
field in each menu link.Running nginx -t
through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).
The only good solution to this problem can be found in the gulp documentation:
var gulp = require('gulp');
// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
// do stuff -- async or otherwise
cb(err); // if err is not null and not undefined, the orchestration will stop, and 'two' will not run
});
// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
// task 'one' is done now
});
gulp.task('default', ['one', 'two']);
// alternatively: gulp.task('default', ['two']);
You can program defensively, and do your import as:
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
and then in the code, just use:
data = urlopen(MIRRORS).read(AMOUNT2READ)
If the string was constructed in the same program, I would recommend using this:
String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);
But if you are specced to use \n, this driver illustrates what to do:
class NewLineTest {
public static void main(String[] args) {
String hasNewline = "this has a newline\n.";
String noNewline = "this doesn't";
System.out.println(hasNewline.contains("\n"));
System.out.println(hasNewline.contains("\\n"));
System.out.println(noNewline.contains("\n"));
System.out.println(noNewline.contains("\\n"));
}
}
Resulted in
true
false
false
false
In reponse to your comment:
class NewLineTest {
public static void main(String[] args) {
String word = "test\n.";
System.out.println(word.length());
System.out.println(word);
word = word.replace("\n","\n ");
System.out.println(word.length());
System.out.println(word);
}
}
Results in
6
test
.
7
test
.
Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)
images = xml.getElementsByTagName("imageUrl")
for i in images:
print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)
If you get errors trying to install mysqlclient with pip, you may lack the mysql dev library. Install it by running:
apt-get install libmysqlclient-dev
and try again to install mysqlclient:
pip install mysqlclient
Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:
std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100
vec = vector<uint32_t>(); // Same as "vector<uint32_t>().swap(vec)";
std::cout << vec.capacity(); // 0
It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.
You can use strlen
strlen(urarray);
You can code it yourself so you understand how it works
size_t my_strlen(const char *str)
{
size_t i;
for (i = 0; str[i]; i++);
return i;
}
if you want the size of the array then you use sizeof
char urarray[255];
printf("%zu", sizeof(urarray));
You should be able to reference sheets by the user-supplied name. Are you sure you're referencing the correct Workbook? If you have more than one workbook open at the time you refer to a sheet, that could definitely cause the problem.
If this is the problem, using ActiveWorkbook
(the currently active workbook) or ThisWorkbook
(the workbook that contains the macro) should solve it.
For example,
Set someSheet = ActiveWorkbook.Sheets("Custom Sheet")
I've tested two ways in Firefox, Chrome, IE9 and Safari.
(1). $(document.activeElement)
works as expected in Firefox, Chrome and Safari.
(2). $(':focus')
works as expected in Firefox and Safari.
I moved into the mouse to input 'name' and pressed Enter on keyboard, then I tried to get the focused element.
(1). $(document.activeElement)
returns the input:text:name as expected in Firefox, Chrome and Safari, but it returns input:submit:addPassword in IE9
(2). $(':focus')
returns input:text:name as expected in Firefox and Safari, but nothing in IE
<form action="">
<div id="block-1" class="border">
<h4>block-1</h4>
<input type="text" value="enter name here" name="name"/>
<input type="button" value="Add name" name="addName"/>
</div>
<div id="block-2" class="border">
<h4>block-2</h4>
<input type="text" value="enter password here" name="password"/>
<input type="submit" value="Add password" name="addPassword"/>
</div>
</form>
Here is what I do on my projects in jupyter notebook,
import sys
sys.path.append("../") # go to parent dir
from customFunctions import *
Then, to affect changes in customFunctions.py
,
%load_ext autoreload
%autoreload 2
JpaRepository
The Spring Data JpaRepository
defines the following two methods:
getOne
, which returns an entity proxy that is suitable for setting a @ManyToOne
or @OneToOne
parent association when persisting a child entity.findById
, which returns the entity POJO after running the SELECT statement that loads the entity from the associated tableHowever, in your case, you didn't call either getOne
or findById
:
Person person = personRepository.findOne(1L);
So, I assume the findOne
method is a method you defined in the PersonRepository
. However, the findOne
method is not very useful in your case. Since you need to fetch the Person
along with is roles
collection, it's better to use a findOneWithRoles
method instead.
You can define a PersonRepositoryCustom
interface, as follows:
public interface PersonRepository
extends JpaRepository<Person, Long>, PersonRepositoryCustom {
}
public interface PersonRepositoryCustom {
Person findOneWithRoles(Long id);
}
And define its implementation like this:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public Person findOneWithRoles(Long id)() {
return entityManager.createQuery("""
select p
from Person p
left join fetch p.roles
where p.id = :id
""", Person.class)
.setParameter("id", id)
.getSingleResult();
}
}
That's it!
It's useful to define a complete .gitignore file for your project. The reward is safe use of the convenient --all
or -a
flag to commands like add
and commit
.
Also, consider defining a global ~/.gitignore file for commonly ignored patterns such as *~
, which covers temporary files created by Emacs.
This code gives you an error because your Add
function needs to be static
:
static public int Add(int x, int y)
In C# there is a distinction between functions that operate on instances (non-static) and functions that do not operate on instances (static). Instance functions can call other instance functions and static functions because they have an implicit reference to the instance. In contrast, static functions can call only static functions, or else they must explicitly provide an instance on which to call a non-static function.
Since public static void Main(string[] args)
is static, all functions that it calls need to be static as well.
Give this link a try --> https://pypi.python.org/pypi/setuptools
I'm assuming you're on Windows (could be wrong) but if you click the green Downloads button, it should take you to a table where you can choose to download a .exe version of setuptools appropriate for your version of Python. All that eggsetup stuff should be taken care of in the executable file.
Let me know if you need more help.
I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.
Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:
Two simple <div>
:
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
content: "";_x000D_
position: relative;_x000D_
left: -3rem;_x000D_
/* padding * -1 */_x000D_
top: calc( 3rem - 4rem / 2);_x000D_
/* padding - height/2 */_x000D_
float: left;_x000D_
display: block;_x000D_
height: 4rem;_x000D_
width: 100vw;_x000D_
background: hsla(0, 0%, 100%, 0.5);_x000D_
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
font-family: monospace;_x000D_
font-size: 1.2rem;_x000D_
line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)
It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)
To edit the colors, you need to edit the URL-encoded SVG itself.
Pay attention (like in the first demo) to a change in the viewBox
to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)
Another thing to pay attention to here is the background-size
set to 100% 100%
to get it to stretch in both directions.
This is the simplest way I found after using reflector. I created an extension method for that:
public static class ProcessExtensions
{
public static bool IsRunning(this Process process)
{
if (process == null)
throw new ArgumentNullException("process");
try
{
Process.GetProcessById(process.Id);
}
catch (ArgumentException)
{
return false;
}
return true;
}
}
The Process.GetProcessById(processId)
method calls the ProcessManager.IsProcessRunning(processId)
method and throws ArgumentException
in case the process does not exist. For some reason the ProcessManager
class is internal...
Try setting host=127.0.0.1 on your db settings file, it worked for me! :)
Hope it helps!
Add text-align: center;
to the parent tag of <canvas>
. That's it.
Example:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</canvas>
</div>
$('input[type="button"]').click(function (e) {
if (e.target) {
alert(e.target.id + ' clicked');
}
});
you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}