Or you could write your own function for it (which is what I ended up doing).
function Join-Path-Recursively($PathParts) {
$NumberOfPathParts = $PathParts.Length;
if ($NumberOfPathParts -eq 0) {
return $null
} elseif ($NumberOfPathParts -eq 1) {
return $PathParts[0]
} else {
return Join-Path -Path $PathParts[0] -ChildPath $(Join-Path-Recursively -PathParts $PathParts[1..($NumberOfPathParts-1)])
}
}
You could then call the function like this:
Join-Path-Recursively -PathParts @("C:", "Program Files", "Microsoft Office")
Join-Path-Recursively @("C:", "Program Files", "Microsoft Office")
This has the advantage of having the exact same behaviour as the normal Join-Path function and not depending on the .NET Framework.
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
On rooted device you can do this:
adb shell
su
chmod 777 /data /data/data /data/data/com.application.package/data/data/com.application.package/*
After this you should be able to browse the files on the device.
To get the databases:
chmod 777 /data/data/com.application.package/databases /data/data/com.application.package/databases/*
If it returns permission denied
on su
Go to Settings
> Developer Options
> Root access
> Apps and ADB
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
If you want to remove a specific Item or variable from the user's local storage, you can use
localStorage.removeItem("name of localStorage variable you want to remove");
One simple method is using a Globally Unique Identifier (GUID). GUIDs are usually stored as 128-bit values and are commonly displayed as 32 hexadecimal digits with groups separated by hyphens, such as {21EC2020-3AEA-4069-A2DD-08002B30309D}
.
Use the following code in C# by System.Guid.NewGuid()
.
getKey = System.Guid.NewGuid().ToString().Substring(0, 8).ToUpper(); //Will generate a random 8 digit hexadecimal string.
_key = Convert.ToString(Regex.Replace(getKey, ".{4}", "$0/")); // And use this to separate every four digits with a "/".
I hope it helps.
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
It`s a so easy solution:
To Add
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath);
To Remove
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.DeleteValue("Your Application Name", false);
As per Swift 2.2
You can get easily NSDate from String and String from NSDate. e.g.
First set date formatter
let formatter = NSDateFormatter();
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = .NoStyle
formatter.dateFormat = "MM/dd/yyyy"
Now get date from string and vice versa.
let strDate = formatter.stringFromDate(NSDate())
print(strDate)
let dateFromStr = formatter.dateFromString(strDate)
print(dateFromStr)
Now enjoy.
Just delete the files or rename them.
e.g.
$ git pull
Enter passphrase for key '/c/Users/PC983/.ssh/id_rsa':
error: Your local changes to the following files would be overwritten by merge:
ajax/productPrice.php
Please commit your changes or stash them before you merge.
error: The following untracked working tree files would be overwritten by merge:
ajax/product.php
Please move or remove them before you merge.
Aborting
Updating a04cbe7a..6aa8ead5
I had to rename/delete ajax/product.php and ajax/produtPrice.php.
Don't worry, git pull will bring them back. I suggest you to rename them instead of deleting, because you might loose some changes.
If this does not help, then you have to delete the whole Branch and create it again and then do git pull origin remotebranch
If you tried all the other answers in this question and you:
...you may have separate versions of the NuGet packages DLL in your projects' References, as the reference created by Intellisense/ReSharper will be a "normal" reference, and not a NuGet reference as expected, so the NuGet update process won't find or update it!
To fix this, remove the reference in Project A, then use NuGet to install it, and make sure the NuGet packages in all projects are the same version. (as explain in this answer)
This issue can come up whenever ReSharper/Intellisense suggests to add a reference to your project. It can be much more deeply convoluted than the example above, with multiple interweaving projects and dependencies making it hard to track down. If the reference being suggested by ReSharper/Intellisense is actually from a NuGet package, use NuGet to install it.
Note: This does not directly answer your question. This is deliberate.
A List Apart has an excellent CSS Positioning 101 article that is worth reading ... more than once. It has numerous examples that include, amongst others, your specific problem. I highly recommend it.
I like to do it with a static method in the second activity:
private static final String EXTRA_GAME_ID = "your.package.gameId";
public static void start(Context context, String gameId) {
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(EXTRA_GAME_ID, gameId);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = this.getIntent();
String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}
Then from your first activity (and for anywhere else), you just do:
SecondActivity.start(this, "the.game.id");
I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed()
if they did.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WelcomeActivity.super.onBackPressed();
}
}).create().show();
}
In the above example, you'll need to replace WelcomeActivity with the name of your activity.
I just solved it. You need to install Entity Framework again in your solution. Follow any of the approaches.
First = Right Click your Solution or Project root and click Manage NuGet Packages
. Select 'EntityFramework', select the appropriate Projects and click Ok.
or
Second = Go to Console Package Manager and run Install-Package EntityFramework
.
Hope it helps.
You can simply use:
#contentInfo_new br {display:none;}
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
That's basically it. These are the methods I use to convert to and from Unix epoch time:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return origin.AddSeconds(timestamp);
}
public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch
.
<form enctype='multipart/form-data'>
<input onchange="alert(this.value); this.value=null; return false;" type='file'>
<br>
<input type='submit' value='Upload'>
</form>
this.value=null;
is only necessary for Chrome, Firefox will work fine just with return false;
Here is a FIDDLE
My problem was with extra </div>
tag inside the first tab.
if you have control over the query which builds the jQuery object, use :eq()
$("div:eq(2)")
If you don't have control over it (for example, it's being passed from another function or something), then use .eq()
var $thirdElement = $jqObj.eq(2);
Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()
var $third4th5thElements = $jqObj.slice(2, 5);
You cannot empty an array as such, it always contains the same amount of data.
In a bigger context the data in the array may represent an empty list of items, but that has to be defined in addition to the array. The most common ways to do this is to keep a count of valid items (see the answer by pmg) or for strings to terminate them with a zero character (the answer by Felix). There are also more complicated ways, for example a ring buffer uses two indices for the positions where data is added and removed.
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
This is only if you want toget the first decimal
print(int(float(input()) * 10) % 10)
Or you can try this
num = float(input())
b = num - int(num)
c = b * 10
print(int(c))
sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
Just try this:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
Now try this running your filename.py like this:
python filename.py example example1
this will print 3 arguments in a list.
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv1 is the first argument passed, in this case 'example'
A similar question has been asked already here btw. Hope this helps!
Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()
The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.
So:
Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket();
? This is called casting
Try this
var myarray = ["item 1", "item 2", "item 3", "item 4"];
//removes the first element of the array, and returns that element apart from item 1.
myarray.shift();
console.log(myarray);
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Following is working for me on dotnet 1.0.1:
./ourView.cshtml
@Html.Partial(
"_ourPartial.cshtml",
new ViewDataDictionary(this.Vi??ewData) {
{
"hi", "hello"
}
}
);
./_ourPartial.cshtml
<h1>@this.ViewData["hi"]</h1>
Note that you can also use the C99 fixed-width types perfectly well in Objective-C:
#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform
The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h
and inttypes.h
to be useful.
Basically, what this error is saying is that if you are going to use the GROUP BY
clause, then your result is going to be a relation/table with a row for each group, so in your SELECT
statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.
Closest I can think of (keeping it simple enough) is stat
, assuming you know which files you're looking for. If you don't, *
can find most of them:
/usr/bin$ stat -c '%a %n' *
755 [
755 a2p
755 a2ps
755 aclocal
...
It handles sticky, suid and company out of the box:
$ stat -c '%a %n' /tmp /usr/bin/sudo
1777 /tmp
4755 /usr/bin/sudo
Since the OP's question is about stripping the newline character from the last element, I would reset it with the_list[-1].rstrip()
:
>>> the_list = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> the_list[-1] = ls[-1].rstrip()
>>> the_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']
It's O(1).
I am using Retrofit 1.9 to obtain a XML.
public class ServicioConexionRetrofitXML {
public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
public static final long tiempoMaximoRespuestaSegundos = 60;
public static final long tiempoMaximoLecturaSegundos = 100;
public static final OkHttpClient clienteOkHttp = new OkHttpClient();
private static RestAdapter.Builder builder = new RestAdapter.Builder().
setEndpoint(API_BASE_URL).
setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());
public static <S> S createService(Class<S> serviceClass) {
clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.6.0'
// Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
// en conflicto.
compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
Note: If you need to fetch a JSON, just remove from code above.
.setConverter(new SimpleXMLConverter())
pushing commits, whether empty or not, causes eventual git hooks to be triggered. This can do either nothing or have world shattering consequences.
In addition to cookies and localStorage
, there's at least one other place you can store "semi-persistent" client data: window.name
. Any string value you assign to window.name
will stay there until the window is closed.
To test it out, just open the console and type window.name = "foo"
, then refresh the page and type window.name
; it should respond with foo
.
This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage
for whatever reason (legacy clients), it may be an option to consider.
window.name
has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window
. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.
Note that window.name
can only store strings, but with the wide availability of JSON
, this shouldn't be much of an issue even for complex data.
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
What I usually do is create a delete page that shows a confirmation form if the request method is "GET" and deletes the data if the method was "POST" and the user chose the "Yes" option.
Then, in the page with the delete link, I add an onclick function (or just use the jQuery confirm plugin) that uses AJAX to post to the link, bypassing the confirmation page.
Here's the idea in pseudo code:
delete.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['confirm'] == 'Yes') {
delete_record($_REQUEST['id']); // From GET or POST variables
}
redirect($_POST['referer']);
}
?>
<form action="delete.php" method="post">
Are you sure?
<input type="submit" name="confirm" value="Yes">
<input type="submit" name="confirm" value="No">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
<input type="hidden" name="referer" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
</form>
Page with delete link:
<script>
function confirmDelete(link) {
if (confirm("Are you sure?")) {
doAjax(link.href, "POST"); // doAjax needs to send the "confirm" field
}
return false;
}
</script>
<a href="delete.php?id=1234" onclick="return confirmDelete(this);">Delete record</a>
Well you're right, REST is stateless. If you use a session the processing will become stateful, subsequent requests will be able to use state (from a session).
In order for a session to be rehydrated, you'll need to supply a key to associate the state. In a normal asp.net application that key is supplied by using a cookie (cookie-sessions) or url parameter (cookieless sessions).
If you need a session forget rest, sessions are irrelevant in REST based designs. If you need a session for validation then use a token or authorise by IP addresses.
After some searching, the most reasonable answer is the following:
MVC is already implemented in Android as:
Button
derived from android.view.View
.(This by the way implies no application domain logic in the activity.)
The most reasonable thing for a small developer is to follow this pattern and not to try to do what Google decided not to do.
PS Note that Activity is sometimes restarted, so it's no place for model data (the easiest way to cause a restart is to omit android:configChanges="keyboardHidden|orientation"
from the XML and turn your device).
EDIT
We may be talking about MVC, but it will be so to say FMVC, Framework--Model--View--Controller. The Framework (the Android OS) imposes its idea of component life cycle and related events, and in practice the Controller (Activity
/Service
/BroadcastReceiver
) is first of all responsible for coping with these Framework-imposed events (such as onCreate()). Should user input be processed separately? Even if it should, you cannot separate it, user input events also come from Android.
Anyway, the less code that is not Android-specific you put into your Activity
/Service
/BroadcastReceiver
, the better.
I would use PCRE and the define
keyword:
/^
((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))$
(?(DEFINE)
(?<byte>25[0-5]|2[0-4]\d|[01]?\d\d?))
/gmx
Demo: https://regex101.com/r/IB7j48/2
The reason of this is to avoid repeating the (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
pattern four times. Other solutions such as the one below work well, but it does not capture each group as it would be requested by many.
/^((\d+?)(\.|$)){4}/
The only other way to have 4 capture groups is to repeat the pattern four times:
/^(?<one>\d+)\.(?<two>\d+)\.(?<three>\d+)\.(?<four>\d+)$/
Capturing a ipv4 in perl is therefore very easy
$ echo "Hey this is my IP address 138.131.254.8, bye!" | \
perl -ne 'print "[$1, $2, $3, $4]" if \
/\b((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))
(?(DEFINE)
\b(?<byte>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
/x'
[138, 131, 254, 8]
CREATE TABLE new_table LIKE old_table;
or u can use this
CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];
I find this easier.
sort -u input_filename > output_filename
-u
stands for unique.
package test.concurrent;
public class DeadLockTest {
private static long sleepMillis;
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public static void main(String[] args) {
sleepMillis = Long.parseLong(args[0]);
DeadLockTest test = new DeadLockTest();
test.doTest();
}
private void doTest() {
Thread t1 = new Thread(new Runnable() {
public void run() {
lock12();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
lock21();
}
});
t1.start();
t2.start();
}
private void lock12() {
synchronized (lock1) {
sleep();
synchronized (lock2) {
sleep();
}
}
}
private void lock21() {
synchronized (lock2) {
sleep();
synchronized (lock1) {
sleep();
}
}
}
private void sleep() {
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
To run the deadlock test with sleep time 1 millisecond:
java -cp . test.concurrent.DeadLockTest 1
These are utf-8 encoded characters. Use utf8_decode() to convert them to normal ISO-8859-1 characters.
Assuming you want lower case letters:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:
UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx
The difference between page and window with respect to WPF: Page vs Window in WPF?
In Kotlin, you can do:
ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)
if requireContext() is accessible from where you are calling the function. I was getting an error when trying
ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)
if you had only one field to "DISTINCT", you could use:
SELECT COUNT(DISTINCT DocumentId)
FROM DocumentOutputItems
and that does return the same query plan as the original, as tested with SET SHOWPLAN_ALL ON. However you are using two fields so you could try something crazy like:
SELECT COUNT(DISTINCT convert(varchar(15),DocumentId)+'|~|'+convert(varchar(15), DocumentSessionId))
FROM DocumentOutputItems
but you'll have issues if NULLs are involved. I'd just stick with the original query.
cat will not work if there are spaces in filenames. here is a perl one-liner instead.
perl -nle 'chomp; $x+=(stat($_))[7]; END{print $x}' files.txt
#define debug_print(FMT, ARGS...) do { \
if (DEBUG) \
fprintf(stderr, "%s:%d " FMT "\n", __FUNCTION__, __LINE__, ## ARGS); \
} while (0)
for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.
Not possible. If you have only time-of-day, the clock stops at midnight. Without the context of dates, how do we know if you mean 1 AM on the next day, next week, or next decade?
So going from 11 PM to 1 AM means moving backwards in time 22 hours, running the hands of the clock counterclockwise. See the result below, a negative twenty-two hours.
Duration.between( // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
LocalTime.of( 23 , 0 ) , // A time-of-day without a date and without a time zone.
LocalTime.of( 1 , 0 ) // A time-of-day clock stops at midnight. So getting to 1 AM from 11 PM means going backwards 22 hours.
) // Return a `Duration` object.
.toString() // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
PT-22H
Crossing midnight requires the larger context of date in addition to time-of-day (see below).
How do I measure time elapsed in Java?
Instant.now()
.Duration.between
.Duration
object, extract a number of 24-hour days, hours, minutes, seconds, and fractional second in nanoseconds by calling the various to…Part
methods.toString
to generate a String
in standard ISO 8601 format of PnYnMnDTnHnMnS
.Example code, using pair of Instant
objects.
Duration.between( // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
then , // Some other `Instant` object, captured earlier with `Instant.now()`.
Instant.now() // Capture the current moment in UTC with a resolution as fine as nanoseconds, depending on the limits of your host computer hardware clock and operating system. Generally you will get current moment in microseconds (six decimal digits of fractional second) in Java 9, 10, and 11, but only milliseconds in Java 8.
) // Return a `Duration` object.
.toString() // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
PT3M27.602197S
We have new technology for this now built into Java 8 and later, the java.time framework.
The java.time framework is defined by JSR 310, inspired by the highly successful Joda-Time project, extended by the ThreeTen-Extra project, and described in the Oracle Tutorial.
The old date-time classes such as java.util.Date/.Calendar bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. They are supplanted by the java.time classes.
Other answers discuss resolution.
The java.time classes have nanosecond resolution, up to nine digits of a decimal fraction of a second. For example, 2016-03-12T04:29:39.123456789Z
.
Both the old java.util.Date/.Calendar classes and the Joda-Time classes have millisecond resolution (3 digits of fraction). For example, 2016-03-12T04:29:39.123Z
.
In Java 8, the current moment is fetched with up to only millisecond resolution because of a legacy issue. In Java 9 and later, the current time can be determined up to nanosecond resolution provided your computer’s hardware clock runs so finely.
If you truly want to work with only the time-of-day lacking any date or time zone, use the LocalTime
class.
LocalTime sooner = LocalTime.of ( 17, 00 );
LocalTime later = LocalTime.of ( 19, 00 );
A Duration
represents a span of time it terms of a count of seconds plus nanoseconds.
Duration duration = Duration.between ( sooner, later );
Dump to console.
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
sooner: 17:00 | later: 19:00 | duration: PT2H
Notice the default output of Duration::toString
is in standard ISO 8601 format. In this format, the P
marks the beginning (as in 'Period'), and the T
separates any years-months-days portion from the hours-minutes-seconds portion.
Unfortunately, working with time-of-day only gets tricky when you wrap around the clock crossing midnight. The LocalTime
class handles this by assuming you want to go backwards to an earlier point in the day.
Using the same code as above but going from 23:00
to 01:00
results in a negative twenty-two hours (PT-22H
).
LocalTime sooner = LocalTime.of ( 23, 0 );
LocalTime later = LocalTime.of ( 1, 0 );
sooner: 23:00 | later: 01:00 | duration: PT-22H
If you intend to cross midnight, it probably makes sense for you to be working with date-time values rather than time-of-day-only values.
Time zone is crucial to dates. So we specify three items: (1) the desired date, (2) desired time-of-day, and (3) the time zone as a context by which to interpret that date and time. Here we arbitrarily choose the time zone of the Montréal area.
If you define the date by only an offset-from-UTC, use a ZoneOffset
with a OffsetDateTime
. If you have a full time zone (offset plus rules for handling anomalies such as Daylight Saving Time), use a ZoneId
with a ZonedDateTime
.
LocalDate localDate = LocalDate.of ( 2016, 1, 23 );
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime sooner = ZonedDateTime.of ( localDate, LocalTime.of ( 23, 0 ), zoneId );
We specify the later time as next day at 1:00 AM.
ZonedDateTime later = ZonedDateTime.of ( localDate.plusDays ( 1 ), LocalTime.of ( 1, 0 ), zoneId );
We calculate the Duration
in the same manner as seen above. Now we get the two hours expected by this Question.
Duration duration = Duration.between ( sooner, later );
Dump to console.
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
sooner: 2016-01-23T23:00-05:00[America/Montreal] | later: 2016-01-24T01:00-05:00[America/Montreal] | duration: PT2H
If the date-times at hand had involved Daylight Saving Time (DST) or other such anomaly, the java.time classes would adjust as needed. Read class doc for details.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
How about storing the new options
in a variable
, and then using .html(variable)
to replace the data in the container
?
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
All you need is parent
part if you use pathlib
.
from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)
Will output:
C:\Program Files\Internet Explorer
Case you need all parts (already covered in other answers) use parts
:
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)
Then you will get a list:
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
Saves tone of time.
In .NET4.5
, MVC 5
Javascript:
object in JS:
mechanism that does post.
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
Objects:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
Hope this saves you some time.
borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
Ok, I solved it by adding the url for the background image at the end of the line.
Here's my working code:
.css {_x000D_
background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
Answers assembled! I wanted to just combine all the answers into one comprehensive one.
1. Check if <uses-permission android:name="android.permission.INTERNET" />
is present in manifest.xml
. Make sure that it is nested under <manifest>
and not <application>
. Thanks to sajid45 and Liyanis Velazquez
2. Ensure that you are using <uses-permission android:name="android.permission.INTERNET"/>
instead of the deprecated <uses-permission android:name="android.permission.internet"/>
. Much thanks to alan_shi and creos.
3. If minimum version is below KK, check that you have
if (18 < Build.VERSION.SDK_INT ){
//18 = JellyBean MR2, KITKAT=19
mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
or
if (Build.VERSION.SDK_INT >= 19) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
because proper webview is only added in KK (SDK 19). Thanks to Devavrata, Mike ChanSeong Kim and Liyanis Velazquez
4. Ensure that you don't have webView.getSettings().setBlockNetworkLoads (false);
. Thanks to TechNikh for pointing this out.
5. If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.
Try to trigger() event in your function:
$("form").trigger('submit'); // and then... do submit()
Why not JSON.stringify
and .includes()
?
You can easily check if a JSON object includes a value by turning it into a string and checking the string.
console.log(JSON.stringify(JSONObject).includes("dog"))
--> true
Edit: make sure to check browser compatibility for .includes()
The greps can be chained. For example:
tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"
Current Working Directory: os.getcwd()
And the __file__
attribute can help you find out where the file you are executing is located. This SO post explains everything: How do I get the path of the current executed file in Python?
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
Based on your replies to everyone else, something like this is what you're looking for.
string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string line in lines)
{
writer.WriteLine(line + "@");
}
}
as its most fundamental reason of existence is to serve as a way to send data back and forth between XML files and SQL databases.
It is written in Spanish (if that matters in a programming language) but it is very simple.
from BD_XML import Tabla
It defines an object called Tabla (Table), it can be created with a name for identification an a pre-created connection object of a pep-246 compatible database interface.
Table = Tabla('Animals')
Then you need to add columns with the agregar_columna
(add_column) method, with can take various key word arguments:
campo
(field): the name of the field
tipo
(type): the type of data stored, can be a things like 'varchar' and 'double' or name of python objects if you aren't interested in exporting to a data base latter.
defecto
(default): set a default value for the column if there is none when you add a row
there are other 3 but are only there for database tings and not actually functional
like:
Table.agregar_columna(campo='Name', tipo='str')
Table.agregar_columna(campo='Year', tipo='date')
#declaring it date, time, datetime or timestamp is important for being able to store it as a time object and not only as a number, But you can always put it as a int if you don't care for dates
Table.agregar_columna(campo='Priority', tipo='int')
Then you add the rows with the += operator (or + if you want to create a copy with an extra row)
Table += ('Cat', date(1998,1,1), 1)
Table += {'Year':date(1998,1,1), 'Priority':2, Name:'Fish'}
#…
#The condition for adding is that is a container accessible with either the column name or the position of the column in the table
Then you can generate XML and write it to a file with exportar_XML
(export_XML) and escribir_XML
(write_XML):
file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Animals.xml'))
Table.exportar_xml()
Table.escribir_xml(file)
And then import it back with importar_XML
(import_XML) with the file name and indication that you are using a file and not an string literal:
Table.importar_xml(file, tipo='archivo')
#archivo means file
This are ways you can use a Tabla object in a SQL manner.
#UPDATE <Table> SET Name = CONCAT(Name,' ',Priority), Priority = NULL WHERE id = 2
for row in Table:
if row['id'] == 2:
row['Name'] += ' ' + row['Priority']
row['Priority'] = None
print(Table)
#DELETE FROM <Table> WHERE MOD(id,2) = 0 LIMIT 1
n = 0
nmax = 1
for row in Table:
if row['id'] % 2 == 0:
del Table[row]
n += 1
if n >= nmax: break
print(Table)
this examples assume a column named 'id' but can be replaced width row.pos for your example.
if row.pos == 2:
You could check out JBoss Tools plugin.
In v 5.8.38, I set the env file as the following:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=difficultCombination
MAIL_ENCRYPTION=ssl
MAIL_FROM_NAME=myWebappName
After doing php artisan config:clear
, it worked well on a shard server.
Using configure() method two times is responsible the problem for me. Instead of using like this :
Configuration configuration = new Configuration().configure();
configuration.configure("/main/resources/hibernate.cfg.xml");
Now, I am using like this, problem does not exist anymore.
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
try{
Configuration configuration = new Configuration();
configuration.configure("/main/resources/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
catch(Exception e){
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
@echo off
set startbuild=%TIME%
C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error
copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q
echo Start Copy: %TIME%
set copystart=%TIME%
xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm
echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%
c:\link\warnings.log
:error
c:\link\errors.log
@extend .myclass;
@extend #{'.my-class'};
I have these characters show up in scripts where I do not desire them. I noticed because it ruins my HTML/CSS visual formatting : it makes a new text box.
Pretty sure a buggy editor is adding them... I suspect Komodo Edit for the Mac, in my case.
public class ThreadParameter
{
public int Port { get; set; }
public string Path { get; set; }
}
Thread t = new Thread(new ParameterizedThreadStart(Startup));
t.Start(new ThreadParameter() { Port = port, Path = path});
Create an object with the port and path objects and pass it to the Startup method.
Try the following-sibling
axis (following-sibling::td
).
This is the script I use on local boxes to set the SAN (subjectAltName) in self-signed certificates.
This script takes the domain name (example.com) and generates the SAN for *.example.com and example.com in the same certificate. The sections below are commented. Name the script (e.g. generate-ssl.sh
) and give it executable permissions. The files will be written to the same directory as the script.
Chrome 58 an onward requires SAN to be set in self-signed certificates.
#!/usr/bin/env bash
# Set the TLD domain we want to use
BASE_DOMAIN="example.com"
# Days for the cert to live
DAYS=1095
# A blank passphrase
PASSPHRASE=""
# Generated configuration file
CONFIG_FILE="config.txt"
cat > $CONFIG_FILE <<-EOF
[req]
default_bits = 2048
prompt = no
default_md = sha256
x509_extensions = v3_req
distinguished_name = dn
[dn]
C = CA
ST = BC
L = Vancouver
O = Example Corp
OU = Testing Domain
emailAddress = webmaster@$BASE_DOMAIN
CN = $BASE_DOMAIN
[v3_req]
subjectAltName = @alt_names
[alt_names]
DNS.1 = *.$BASE_DOMAIN
DNS.2 = $BASE_DOMAIN
EOF
# The file name can be anything
FILE_NAME="$BASE_DOMAIN"
# Remove previous keys
echo "Removing existing certs like $FILE_NAME.*"
chmod 770 $FILE_NAME.*
rm $FILE_NAME.*
echo "Generating certs for $BASE_DOMAIN"
# Generate our Private Key, CSR and Certificate
# Use SHA-2 as SHA-1 is unsupported from Jan 1, 2017
openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout "$FILE_NAME.key" -days $DAYS -out "$FILE_NAME.crt" -passin pass:$PASSPHRASE -config "$CONFIG_FILE"
# OPTIONAL - write an info to see the details of the generated crt
openssl x509 -noout -fingerprint -text < "$FILE_NAME.crt" > "$FILE_NAME.info"
# Protect the key
chmod 400 "$FILE_NAME.key"
This script also writes an information file, so you can inspect the new certificate and verify the SAN is set properly.
...
28:dd:b8:1e:34:b5:b1:44:1a:60:6d:e3:3c:5a:c4:
da:3d
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Alternative Name:
DNS:*.example.com, DNS:example.com
Signature Algorithm: sha256WithRSAEncryption
3b:35:5a:d6:9e:92:4f:fc:f4:f4:87:78:cd:c7:8d:cd:8c:cc:
...
If you are using Apache, then you can reference the above certificate in your configuration file like so:
<VirtualHost _default_:443>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/htdocs
SSLEngine on
SSLCertificateFile path/to/your/example.com.crt
SSLCertificateKeyFile path/to/your/example.com.key
</VirtualHost>
Remember to restart your Apache (or Nginx, or IIS) server for the new certificate to take effect.
You should use BFG Repo-Cleaner.
According to the website:
The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:
- Removing Crazy Big Files
- Removing Passwords, Credentials & other Private data
The classic procedure for reducing the size of a repository would be:
git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --strip-biggest-blobs 500 some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push
You could use a SUM
(not COUNT
!) combined with a CASE
statement, like this:
SELECT SUM(CASE WHEN myColumn=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
Note: in my own test NULL
s were not an issue, though this can be environment dependent. You could handle nulls such as:
SELECT SUM(CASE WHEN ISNULL(myColumn,0)=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
It will work for both iphone and ipad
func showImagePicker() {
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let alert = UIAlertController(title: "", message: "Upload Attachment", preferredStyle: alertStyle)
alert.addAction(UIAlertAction(title: "Choose from gallery", style: .default , handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction) in
}))
present(alert, animated: true, completion: nil)
}
This
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"¶m2="+lon);
must work. For whatever strange reason1, you need ?
before the first parameter and &
before the following ones.
Using a compound parameter like
url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);
would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20
or +
(but this is even worse style).
1 Stating that ?
separates the path and the parameters and that &
separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.
In the accepted answer's update you don't see the example for the to_date
function, so another solution using it would be:
from pyspark.sql import functions as F
df = df.withColumn(
'new_date',
F.to_date(
F.unix_timestamp('STRINGCOLUMN', 'MM-dd-yyyy').cast('timestamp')))
Just right click on that column and select properties and write getdate()
in Default value or binding
.like image:
If you want do it in CodeFirst
in EF
you should add this attributes befor of your column definition:
[Databasegenerated(Databaseoption.computed)]
this attributes can found in System.ComponentModel.Dataannotion.Schema
.
In my opinion first one is better:))
svn log
- I'm sure WebSVN has some feature for that too.
The "View Log" link near the center-top of the WebSVN overview shows the svn-log. However, the user-interface isn't exactly brilliant; I much prefer TortoiseSVN's log viewer.
If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables
Closing the quotes in
var hv = $('#h_v).text();
would help I guess
As others have pointed out queries will be slower. I'd suggest to add at least an '_ID' column to query by that instead.
Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -
$(document).on('mouseover', '.selector', function() {
//do something
});
$(document).on('mouseout', '.selector', function() {
//do something
});
This fiddle http://jsfiddle.net/TWskH/12/ illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.
My suggestion is to simply replace with mouseenter/mouseleave: -
$(document).on('mouseenter', '.selector', function() {
//do something
});
$(document).on('mouseleave', '.selector', function() {
//do something
});
Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat
Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min
. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat
If you want to terminate them-
taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F
You can use model.save(filepath)
to save a Keras model into a single HDF5 file which will contain:
In your Python code probable the last line should be:
model.save("m.hdf5")
This allows you to save the entirety of the state of a model in a single file.
Saved models can be reinstantiated via keras.models.load_model()
.
The model returned by load_model()
is a compiled model ready to be used (unless the saved model was never compiled in the first place).
model.save()
arguments:
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
I've heard that using sudo
with pip
is unsafe.
Try adding --user
to the end of your command, as mentioned here.
pip install packageName --user
I suspect that installing with this method means the packages are not available to other users.
Had the same problem on another server, but realized that locales are messed.
export LC_ALL="en_US.UTF-8"
fixed the problem
Multiple Image upload using php full source code and preview available at the below Link.
Sample code:
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path.md5(uniqid()).
".".$ext[count($ext) - 1]; //set the target path with a new name of image
$j = $j + 1; //increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
echo $j.
').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { //if file was not moved.
echo $j.
').<span id="error">please try again!.</span><br/><br/>';
}
} else { //if file size and file type was incorrect.
echo $j.
').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
http://www.allinworld99.blogspot.com/2015/05/php-multiple-file-upload.html
Update: Starting with Android SDK Manager version 21, the solution is to edit C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini
and change the value
hw.ramSize=1024
to
hw.ramSize=1024MB
The emulator is really slow, hope they will release the intel images soon use the new API17 Intel x86 images if you want to change it .. (HAXM, Configuration)
Earlier Android SDK Manager releases:
Had the same problem with the built-in WXGA800 skin. I got it working by editing the virtual device setup to:
Here my tablet config for 4.1.0 API 16
C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini
hw.lcd.density=160
sdcard.size=300M
skin.path=1280x800
skin.name=1280x800
hw.cpu.arch=arm
abi.type=armeabi-v7a
hw.cpu.model=cortex-a8
vm.heapSize=48
hw.ramSize=1024MB
image.sysdir.1=system-images\android-16\armeabi-v7a\
This config shows the software keys too
With Visual Studio Code 1.27.2:
When I go to File > Preference > Settings, I get the following tab
I type rulers in Search settings and I get the following list of settings
Clicking on the first Edit in settings.json, I can edit the user settings
Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it
With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.
The panel for selecting the default user setting values isn't shown anymore.
git clone --filter
from Git 2.19
This option will actually skip fetching most unneeded objects from the server:
git clone --depth 1 --no-checkout --filter=blob:none \
"file://$(pwd)/server_repo" local_repo
cd local_repo
git checkout master -- mydir/myfile
The server should be configured with:
git config --local uploadpack.allowfilter 1
git config --local uploadpack.allowanysha1inwant 1
There is no server support as of v2.19.0, but it can already be locally tested.
TODO: --filter=blob:none
skips all blobs, but still fetches all tree objects. But on a normal repo, this should be tiny compared to the files themselves, so this is already good enough. Asked at: https://www.spinics.net/lists/git/msg342006.html Devs replied a --filter=tree:0
is in the works to do that.
Remember that --depth 1
already implies --single-branch
, see also: How do I clone a single branch in Git?
file://$(path)
is required to overcome git clone
protocol shenanigans: How to shallow clone a local git repository with a relative path?
The format of --filter
is documented on man git-rev-list
.
An extension was made to the Git remote protocol to support this feature.
Docs on Git tree:
Test it out
#!/usr/bin/env bash
set -eu
list-objects() (
git rev-list --all --objects
echo "master commit SHA: $(git log -1 --format="%H")"
echo "mybranch commit SHA: $(git log -1 --format="%H")"
git ls-tree master
git ls-tree mybranch | grep mybranch
git ls-tree master~ | grep root
)
# Reproducibility.
export GIT_COMMITTER_NAME='a'
export GIT_COMMITTER_EMAIL='a'
export GIT_AUTHOR_NAME='a'
export GIT_AUTHOR_EMAIL='a'
export GIT_COMMITTER_DATE='2000-01-01T00:00:00+0000'
export GIT_AUTHOR_DATE='2000-01-01T00:00:00+0000'
rm -rf server_repo local_repo
mkdir server_repo
cd server_repo
# Create repo.
git init --quiet
git config --local uploadpack.allowfilter 1
git config --local uploadpack.allowanysha1inwant 1
# First commit.
# Directories present in all branches.
mkdir d1 d2
printf 'd1/a' > ./d1/a
printf 'd1/b' > ./d1/b
printf 'd2/a' > ./d2/a
printf 'd2/b' > ./d2/b
# Present only in root.
mkdir 'root'
printf 'root' > ./root/root
git add .
git commit -m 'root' --quiet
# Second commit only on master.
git rm --quiet -r ./root
mkdir 'master'
printf 'master' > ./master/master
git add .
git commit -m 'master commit' --quiet
# Second commit only on mybranch.
git checkout -b mybranch --quiet master~
git rm --quiet -r ./root
mkdir 'mybranch'
printf 'mybranch' > ./mybranch/mybranch
git add .
git commit -m 'mybranch commit' --quiet
echo "# List and identify all objects"
list-objects
echo
# Restore master.
git checkout --quiet master
cd ..
# Clone. Don't checkout for now, only .git/ dir.
git clone --depth 1 --quiet --no-checkout --filter=blob:none "file://$(pwd)/server_repo" local_repo
cd local_repo
# List missing objects from master.
echo "# Missing objects after --no-checkout"
git rev-list --all --quiet --objects --missing=print
echo
echo "# Git checkout fails without internet"
mv ../server_repo ../server_repo.off
! git checkout master
echo
echo "# Git checkout fetches the missing file from internet"
mv ../server_repo.off ../server_repo
git checkout master -- d1/a
echo
echo "# Missing objects after checking out d1/a"
git rev-list --all --quiet --objects --missing=print
Output in Git v2.19.0:
# List and identify all objects
c6fcdfaf2b1462f809aecdad83a186eeec00f9c1
fc5e97944480982cfc180a6d6634699921ee63ec
7251a83be9a03161acde7b71a8fda9be19f47128
62d67bce3c672fe2b9065f372726a11e57bade7e
b64bf435a3e54c5208a1b70b7bcb0fc627463a75 d1
308150e8fddde043f3dbbb8573abb6af1df96e63 d1/a
f70a17f51b7b30fec48a32e4f19ac15e261fd1a4 d1/b
84de03c312dc741d0f2a66df7b2f168d823e122a d2
0975df9b39e23c15f63db194df7f45c76528bccb d2/a
41484c13520fcbb6e7243a26fdb1fc9405c08520 d2/b
7d5230379e4652f1b1da7ed1e78e0b8253e03ba3 master
8b25206ff90e9432f6f1a8600f87a7bd695a24af master/master
ef29f15c9a7c5417944cc09711b6a9ee51b01d89
19f7a4ca4a038aff89d803f017f76d2b66063043 mybranch
1b671b190e293aa091239b8b5e8c149411d00523 mybranch/mybranch
c3760bb1a0ece87cdbaf9a563c77a45e30a4e30e
a0234da53ec608b54813b4271fbf00ba5318b99f root
93ca1422a8da0a9effc465eccbcb17e23015542d root/root
master commit SHA: fc5e97944480982cfc180a6d6634699921ee63ec
mybranch commit SHA: fc5e97944480982cfc180a6d6634699921ee63ec
040000 tree b64bf435a3e54c5208a1b70b7bcb0fc627463a75 d1
040000 tree 84de03c312dc741d0f2a66df7b2f168d823e122a d2
040000 tree 7d5230379e4652f1b1da7ed1e78e0b8253e03ba3 master
040000 tree 19f7a4ca4a038aff89d803f017f76d2b66063043 mybranch
040000 tree a0234da53ec608b54813b4271fbf00ba5318b99f root
# Missing objects after --no-checkout
?f70a17f51b7b30fec48a32e4f19ac15e261fd1a4
?8b25206ff90e9432f6f1a8600f87a7bd695a24af
?41484c13520fcbb6e7243a26fdb1fc9405c08520
?0975df9b39e23c15f63db194df7f45c76528bccb
?308150e8fddde043f3dbbb8573abb6af1df96e63
# Git checkout fails without internet
fatal: '/home/ciro/bak/git/test-git-web-interface/other-test-repos/partial-clone.tmp/server_repo' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
# Git checkout fetches the missing directory from internet
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1/1), 45 bytes | 45.00 KiB/s, done.
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1/1), 45 bytes | 45.00 KiB/s, done.
# Missing objects after checking out d1
?f70a17f51b7b30fec48a32e4f19ac15e261fd1a4
?8b25206ff90e9432f6f1a8600f87a7bd695a24af
?41484c13520fcbb6e7243a26fdb1fc9405c08520
?0975df9b39e23c15f63db194df7f45c76528bccb
Conclusions: all blobs except d1/a
are missing. E.g. f70a17f51b7b30fec48a32e4f19ac15e261fd1a4
, which is d1/b
, is not there after checking out d1/
.
Note that root/root
and mybranch/mybranch
are also missing, but --depth 1
hides that from the list of missing files. If you remove --depth 1
, then they show on the list of missing files.
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
As far as rm -f
doing "anything else", it does force (-f
is shorthand for --force
) silent removal in situations where rm
would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.
I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too.
What you could do is create a new class, similar to @Gregoire's example, however, you would want to override the ToString()
method so it appears correctly in the combo box e.g.
public class Language
{
private string _name;
private string _code;
public Language(string name, string code)
{
_name = name;
_code = code;
}
public string Name { get { return _name; } }
public string Code { get { return _code; } }
public override void ToString()
{
return _name;
}
}
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
Add the param declation at the top of ps1 file
test.ps1
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
result
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
Python3
use
from .user import User inside dir.py file
and
use from class.dir import Dir inside main.py
or from class.usr import User inside main.py
like so
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You have ("Something2")
by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if
statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch
:
<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>
The paragraph will be displayed when foo.bar is true, hidden when false.
You could just pass a static value (or a variable from *ngFor
or whatever)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame:
JFrame
extends Component
and Container
.
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel:
JPanel
extends Component
, Container
and JComponent
It is a generic class used to group other Component
s together.
It is useful when working with LayoutManager
s e.g. GridLayout
f.i adding components to different JPanel
s which will then be added to the JFrame
to create the gui. It will be more manageable in terms of Layout
and re-usability.
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
In a way I am reticent to add to the long list of answers. However, I searched this page for the word "portable" and came up empty. (And I did a full Stack Overflow search and also found nothing.) So I want to add this very specific answer for potential future searchers.
This answer is for if you installed VS Code in Portable Mode on Windows 10.
"Portable Mode" refers to what is described on the official VS Code web pages, which as of 21 January 2021 are found here: https://code.visualstudio.com. It does not mean the Visual Studio Code Portable project started/run by Gareth Flowers, or any similar project. (I am not saying anything bad about this or other projects - I have neither used nor evaluated.) If you are using one of those projects, you need to check with that project documentation/community - although this might work.
"Installing" VS Code in Portable Mode is downloading a .zip archive and extracting it locally wherever you want your VS Code "installation" to live. There is no actual installation or setup that is run, so there is no automatic adding of the code
command to your PATH
.
After extracting the Portable Mode VS Code files to the location of your choice, there should be a bin
folder in that location. Copy the full path of that bin
folder and add it to your System or User (your choice) PATH
variable.
You should then be able to use the code
command from PowerShell or CMD.
There is a tutorial for creating an HTML5 progress bar here. If you don't want to use HTML5 methods or you are looking for an all-browser solution, try this code:
<div style="width: 150px; height: 25px; background-color: #dbdbdb;">
<div style="height: 25px; width:87%; background-color: gold"> </div>
</div>
_x000D_
You can change the color GOLD to any progress bar color and #dbdbdb to the background-color of your progress bar.
You can try using the following code:
$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;
$mailto = '[email protected]';
$subject = 'Subject';
$message = 'My message';
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers = "From: name <[email protected]>" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $message . $eol;
// attachment
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}
Edit 14-June-2018
for more readability in some of email provider use
$body .= $eol . $message . $eol . $eol;
and
$body .= $eol . $content . $eol . $eol;
Here is my blog post about why we need to use FileProvider and how to use it correctly. Fully updated to the latest versions of Android.
Good answers so far, I want to only add that you could check the type of a node using nodeType
:
yourElement.nodeType
This will give you an integer: (taken from here)
| Value | Constant | Description | |
|-------|----------------------------------|---------------------------------------------------------------|--|
| 1 | Node.ELEMENT_NODE | An Element node such as <p> or <div>. | |
| 2 | Node.ATTRIBUTE_NODE | An Attribute of an Element. The element attributes | |
| | | are no longer implementing the Node interface in | |
| | | DOM4 specification. | |
| 3 | Node.TEXT_NODE | The actual Text of Element or Attr. | |
| 4 | Node.CDATA_SECTION_NODE | A CDATASection. | |
| 5 | Node.ENTITY_REFERENCE_NODE | An XML Entity Reference node. Removed in DOM4 specification. | |
| 6 | Node.ENTITY_NODE | An XML <!ENTITY ...> node. Removed in DOM4 specification. | |
| 7 | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document | |
| | | such as <?xml-stylesheet ... ?> declaration. | |
| 8 | Node.COMMENT_NODE | A Comment node. | |
| 9 | Node.DOCUMENT_NODE | A Document node. | |
| 10 | Node.DOCUMENT_TYPE_NODE | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. | |
| 11 | Node.DOCUMENT_FRAGMENT_NODE | A DocumentFragment node. | |
| 12 | Node.NOTATION_NODE | An XML <!NOTATION ...> node. Removed in DOM4 specification. | |
Note that according to Mozilla:
The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE
I found "git-big-picture" quite useful: https://github.com/esc/git-big-picture
It creates pretty 2D graphs using dot/graphviz instead of the rather linear, "one-dimensional" views gitk and friends produce. With the -i option it shows the branch points and merge commits but leaves out everything in-between.
I've used this much simpler solution:
setOnScrollListener( new OnScrollListener()
{
private int mInitialScroll = 0;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
int scrolledOffset = computeVerticalScrollOffset();
boolean scrollUp = scrolledOffset > mInitialScroll;
mInitialScroll = scrolledOffset;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
You can also use
./gradlew clean build
(Mac and Linux) -With ./
gradlew clean build
(Windows) -Without ./
it removes build folder, as well configure your modules and then build your project.
i use it before release any new app on playstore.
Somebody asked me to post a link to the framework! that I presented at Open World 2012. This is the full blog post that demonstrates how to architect a solution with external tables.
Worked for me:
$(".filter-mobile").click(function() {
if ($("#menuProdutos").height() > 0) {
$("#menuProdutos").animate({
height: 0
}, 200);
} else {
$("#menuProdutos").animate({
height: 500
}, 200);
}
});
I simply wrote an embedded SQL program to write a new record with date fields. It was by far best and shortest without any errors I was able to reach my requirement.
w_dob = %char(%date(*date));
exec sql insert into Tablename (ID_Number ,
AmendmentNo ,
OverrideDate ,
Operator ,
Text_ID ,
Policy_Company,
Policy_Number ,
Override ,
CREATE_USER )
values ( '801010',
1,
:w_dob,
'MYUSER',
' ',
'01',
'6535435023150',
'1',
'myuser');
_x000D_
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
As noted in other answers, you should avoid the pseudo-typedef antipattern. However, typedefs are still useful even if that is not the way to achieve them. You want to distinguish between different abstract types that have the same Java representation. You don't want to mix up strings that are passwords with those that are street addresses, or integers that represent an offset with those with those that represent an absolute value.
The Checker Framework enables you to define a typedef in a backward-compatible way. I works even for primitive classes such as int
and final classes such as String
. It has no run-time overhead and does not break equality tests.
Section Type aliases and typedefs in the Checker Framework manual describes several ways to create typedefs, depending on your needs.
You can do somthing like :
if (product != null) {
var products = Repository.Products;
var indexOf = products.IndexOf(products.Find(p => p.Id == product.Id));
Repository.Products[indexOf] = product;
// or
Repository.Products[indexOf].prop = product.prop;
}
i use firebase-database in html signup but last error i cannot understand if anybody know tell me . error is "Failed to load resource: the server responded with a status of 404 ()"
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.
2.2 configuration syntax was
Order deny,allow
Deny from all
2.4 configuration now is
Require all denied
Thus, this 2.2 syntax
order deny,allow
deny from all
allow from 127.0.0.1
Would ne now written
Require local
Here are 2 examples with maven project, step by step:
at pom.xml, add maven-jar-plugin.
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>somePackage.sample</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
screen capture: 4. open maven project box by click on the search icon and type maven,
test your jar using java -jar
The MANIFEST.MF needs to be in your resources folder and the Main.Class needs to refer to {package}-{class-name-that-contains-main-class}
Use
print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
like this:
>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>
On an unrelated side note ... using string
as a variable name even as an example variable name is very bad practice.
this.TextBox3.Text = DateTime.Now.ToString("MM.dd.yyyy");
I ran into this issue using Phusion Passenger (running as an nginx module) on a Redhat server. We already had a Javascript runtime installed. Other Rails apps in the same parent directory worked fine.
It turned out that we had a permissions issue. Run "ls -l" and see if the folder has the same owner and group as other working apps on the system. I had to run chown and chgrp on the folder (with the recursive switch) to fix it.
I think one of the original questions here was not answered. I believe that vanilla eval() is not used because then angular apps would not work as Chrome apps, which explicitly prevent eval() from being used for security reasons.
You can use Visual Studio for Android Development. See a nice article on it here
For CentOS 7 and MariaDB 10.4, I had success with the following commands:
su -
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --user=mysql"
systemctl restart mariadb
mysql -u root
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
flush privileges;
quit
systemctl unset-environment MYSQLD_OPTS
systemctl restart mariadb
Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'
e.g
a = ['001', '200', 'akdl00', 200, 100, '0']
b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]
b
>>>['1', '2', 'akdl', 200, 100, '0']
@EvilDr You can create an IUSR_[identifier] account within your AD environment and let the particular application pool run under that IUSR_[identifier] account:
"Application pool" > "Advanced Settings" > "Identity" > "Custom account"
Set your website to "Applicaton user (pass-through authentication)" and not "Specific user", in the Advanced Settings.
Now give that IUSR_[identifier] the appropriate NTFS permissions on files and folders, for example: modify on companydata.
editied to add support for ie6:
Try
<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />
This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.
This shall work (modification on above, workaround, not formula)
Modify your original formula: =IF(A1=1,B1,"filler")
Put filter on spreadsheet, choose only "filler" in column B, highlight all the cells with "filler" in them, hit delete, remove filter
window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it
$("<a href='your url'></a>").click();
Here is a small jQuery plugin that (among other things) can empty an dropdown list.
Just write:
$('your-select-element').selectUtils('setEmpty');
After some days searching the Internet I found that this error usually occurs when an html element id has the same id as some variable in the javascript function. After changing the name of one of them my code was working fine.
I answered a very similar question, and here is a way of doing this :
First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts
In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.
This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.
animations.ts
import { trigger, state, style, transition,
animate, group, query, stagger, keyframes
} from '@angular/animations';
export const SlideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
})),
state('out', style({
'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
})),
transition('in => out', [group([
animate('400ms ease-in-out', style({
'opacity': '0'
})),
animate('600ms ease-in-out', style({
'max-height': '0px'
})),
animate('700ms ease-in-out', style({
'visibility': 'hidden'
}))
]
)]),
transition('out => in', [group([
animate('1ms ease-in-out', style({
'visibility': 'visible'
})),
animate('600ms ease-in-out', style({
'max-height': '500px'
})),
animate('800ms ease-in-out', style({
'opacity': '1'
}))
]
)])
]),
]
Then in your app.component, we import the animation and create the method that will toggle the animation state.
app.component.ts
import { SlideInOutAnimation } from './animations';
@Component({
...
animations: [SlideInOutAnimation]
})
export class AppComponent {
animationState = 'in';
...
toggleShowDiv(divName: string) {
if (divName === 'divA') {
console.log(this.animationState);
this.animationState = this.animationState === 'out' ? 'in' : 'out';
console.log(this.animationState);
}
}
}
And here is how your app.component.html would look like :
<div class="wrapper">
<button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
<div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
THIS DIV IS ANIMATED</div>
<div class="content">THIS IS CONTENT DIV</div>
</div>
slideInOut refers to the animation trigger defined in animations.ts
Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/
Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [ ..., BrowserAnimationsModule ],
...
})
Use <foreach>
with a nested <FileSet>
Foreach requires ant-contrib.
Updated Example for recent ant-contrib:
<target name="foo">
<foreach target="bar" param="theFile">
<fileset dir="${server.src}" casesensitive="yes">
<include name="**/*.java"/>
<exclude name="**/*Test*"/>
</fileset>
</foreach>
</target>
<target name="bar">
<echo message="${theFile}"/>
</target>
This will antcall the target "bar" with the ${theFile} resulting in the current file.
Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-
var l: List[int] = List() // creates an empty list
l = 3 :: l // adds 3 to the head of the list
l = 4 :: l // makes int 4 as the head of the list
// Now when you will print l, you will see two elements in the list ( 4, 3)
Simply Run Your Visual Studio 2013 as Administration ... Copy the content of your Xml file.. Go to Visual Studio 2013 > Edit > Paste Special > Paste Xml as C# Classes It will create your c# classes according to your Xml file content.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.
The basic process is:
The table should, of course, be nice HTML. Something like this...
<table>
<thead>
<tr><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Sioned</td><td>62</td></tr>
<tr><td>Dylan</td><td>37</td></tr>
...etc...
</tbody>
</table>
So, first adding the click handlers...
const table = document.querySelector('table'); //get the table to be sorted
table.querySelectorAll('th') // get all the table header elements
.forEach((element, columnNo)=>{ // add a click handler for each
element.addEventListener('click', event => {
sortTable(table, columnNo); //call a function which sorts the table by a given column number
})
})
This won't work right now because the sortTable
function which is called in the event handler doesn't exist.
Lets write it...
function sortTable(table, sortColumn){
// get the data from the table cells
const tableBody = table.querySelector('tbody')
const tableData = table2data(tableBody);
// sort the extracted data
tableData.sort((a, b)=>{
if(a[sortColumn] > b[sortColumn]){
return 1;
}
return -1;
})
// put the sorted data back into the table
data2table(tableBody, tableData);
}
So now we get to the meat of the problem, we need to make the functions table2data
to get data out of the table, and data2table
to put it back in once sorted.
Here they are ...
// this function gets data from the rows and cells
// within an html tbody element
function table2data(tableBody){
const tableData = []; // create the array that'll hold the data rows
tableBody.querySelectorAll('tr')
.forEach(row=>{ // for each table row...
const rowData = []; // make an array for that row
row.querySelectorAll('td') // for each cell in that row
.forEach(cell=>{
rowData.push(cell.innerText); // add it to the row data
})
tableData.push(rowData); // add the full row to the table data
});
return tableData;
}
// this function puts data into an html tbody element
function data2table(tableBody, tableData){
tableBody.querySelectorAll('tr') // for each table row...
.forEach((row, i)=>{
const rowData = tableData[i]; // get the array for the row data
row.querySelectorAll('td') // for each table cell ...
.forEach((cell, j)=>{
cell.innerText = rowData[j]; // put the appropriate array element into the cell
})
tableData.push(rowData);
});
}
And that should do it.
A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2"
is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.
its on you ul
in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252
add this to your css
ul{
list-style:none;
}
Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!
Simply add default constructor and it should work.
You need to specify the encoding of the InputStreamReader using the Charset parameter.
Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));
This is work for me. i hope to help you.
I faced the same problem. And with the help of guys I came up with a really smart solution that solve that problem totally (run on chrome ) .
Extract all images from the network
function AllImagesUrl (domain){
return performance.getEntries()
.filter( e=>
e.initiatorType == "img" &&
new RegExp(domain).test(e.name)
)
.map( e=> e.name.replace('some cleaning work here','') ) ```
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."
Have you tried it?
Try:
DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()
(This is C# code. Change this to VB equivalent)
As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.
Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm
HTH.
Another difference is when async
function returns just Task
instead of Task<T>
then you cannot use
GetFooAsync(...).Result;
Whereas
GetFooAsync(...).GetAwaiter().GetResult();
still works.
I know the example code in the question is for the case Task<T>
, however the question is asked generally.
var formValues = {
firstName: $('#firstName').val(),
lastName: $('#lastName').val(),
phone: $('#phoneNumber').val(),
address: $('#address').val()
};
Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.
On Linux, the default implementation for SecureRandom
is NativePRNG
(source code here), which tends to be very slow. On Windows, the default is SHA1PRNG
, which as others pointed out you can also use on Linux if you specify it explicitly.
NativePRNG
differs from SHA1PRNG
and Uncommons Maths' AESCounterRNG in that it continuously receives entropy from the operating system (by reading from /dev/urandom
). The other PRNGs do not acquire any additional entropy after seeding.
AESCounterRNG is about 10x faster than SHA1PRNG
, which IIRC is itself two or three times faster than NativePRNG
.
If you need a faster PRNG that acquires entropy after initialization, see if you can find a Java implementation of Fortuna. The core PRNG of a Fortuna implementation is identical to that used by AESCounterRNG, but there is also a sophisticated system of entropy pooling and automatic reseeding.
Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me. Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
f
doesn't actually alter the value of x
(which is always the same reference to an instance of a list). Rather, it alters the contents of this list.
In both cases, a copy of a reference is passed to the function. Inside the function,
n
gets assigned a new value. Only the reference inside the function is modified, not the one outside it.x
does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x
’s value is modified.Since both the x
inside the function and outside it refer to the same value, both see the modification. By contrast, the n
inside the function and outside it refer to different values after n
was reassigned inside the function.
If you want to change just on one page, add the following style rule:
#myCustomDivID .row {
margin-top:20px;
}
If you need to use IE8, you can try this JavaScript library for vector graphics. It is like solving the "canvas" and "SVG" incompatibilities of IE8 at the same time.
I have just try it in a fast example and it works correctly. I don't know how legible is the source code but I hope it helps you. As they said in its site, the library is compatible with very old explorers.
Raphaël currently supports Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.
The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random()
just does this. Use random.uniform(a, b)
to specify a different range.
This is a better solution, using:
$("table tr:first-child").has('img')
It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.
This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.
Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.
Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.
; ' Infinite loop. End the macro by closing the program from the Windows taskbar.
Loop {
; ' Wait for ANY "Save As" dialogue box in any program.
; ' BE CAREFUL!
; ' Ignore the "Confirm Save As" dialogue if attempt is made
; ' to overwrite an existing file.
WinWait, Save As,,, Confirm Save As
IfWinNotActive, Save As,,, Confirm Save As
WinActivate, Save As,,, Confirm Save As
WinWaitActive, Save As,,, Confirm Save As
sleep, 250 ; ' 0.25 second delay
Send, {ENTER} ; ' Save the Excel file.
; ' Wait for the "Save As" dialogue box to close.
WinWaitClose, Save As,,, Confirm Save As
}
Pipe to sed -e 's/[\r\n]//g'
to remove both Carriage Returns (\r
) and Line Feeds (\n
) from each text line.
Have you followed these instructions:
http://www.squirrelsql.org/#installation
If so, are you running the batch file or the shell script to run it?
Simple Copy this text and put on the before </body>
function disableselect(e) {
return false
}
function reEnable() {
return true
}
document.onselectstart = new Function ("return false")
if (window.sidebar) {
document.onmousedown = disableselect
document.onclick = reEnable
}
A hash_map
is an older, unstandardized version of what for standardization purposes is called an unordered_map
(originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map
primarily in being unordered -- if, for example, you iterate through a map from begin()
to end()
, you get items in order by key1, but if you iterate through an unordered_map
from begin()
to end()
, you get items in a more or less arbitrary order.
An unordered_map
is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map
has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.
From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map
will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).
1 Where the order is defined by the third template parameter when you create the map, std::less<T>
by default.
I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol
.
For me, this was because ServicePointManager.SecurityProtocol
had been set to Tls | Tls11
(because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.
An option for .NET 4.5 and higher is to enable all TLS versions:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
Mine froze on the Diagnostic Tools for 3 hours. I tried disabling my firewall and turning off internet among many other attempts to resolve this. In the end the following actions allowed the installer to complete and VS2015 Community edition to launch.
All seems to be working OK so far (fingers crossed!!)
1. Put the jar (in my case,
gson-2.2.4.jar
) into the libs folder.2. Ensure that compile files (
libs/gson-2.2.4.jar
) is in your build.gradle file.3. Now Click on the "Sync Project with Gradle files"(Left to AVD manager Button on the topbar).
After I did the above three, it started working fine.
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
simply include parsley.js file in your document and in input element of mobile number enter this
data-parsley-type= "number" data-parsley-length="[10,10]" data-parsley-length-message= "Enter a Mobile Number"
you can change the message according to your requirement you also need to initialize parsley.js file in your document by writing
<script type="text/javascript">
$(document).ready(function() {
$('form').parsley();
});
</script>
---above code in your document.***
To understand methods you must first think in terms of object oriented programming: Let's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s Further the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ...
However there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance.
as pseudo code you would do:
my_toyota.drive(shop)
to change the location from my home to the shop or
my_toyota.load([milk, butter, bread]
by this the trunk is now loaded with [milk, butter, bread].
As such a method is practically a function that acts as part of the object:
class Car(vehicle)
n_wheels = 4
load(self, stuff):
'''this is a method, to load stuff into the trunk of the car'''
self.open_trunk
self.trunk.append(stuff)
self.close_trunk
the code then would be:
my_toyota = Car(red)
my_shopping = [milk, butter, bread]
my_toyota.load(my_shopping)
You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality.
However, as of php7.1, you can define your class constants with access modifiers (public
, private
or protected
).
A work around would be to define your constant as private
or protected
and then make them readable via a static function
. This function should only return the constant values if called from the static context.
You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.
Credits: http://dwellupper.io/post/48/defining-class-constants-in-php
An input
element does not support the target
attribute. The target
attribute is for a
tags and that is where it should be used.
I was pretty sure that you need to specify the NOLOCK
for each JOIN
in the query. But my experience was limited to SQL Server 2005.
When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:
[SQL Server 2008 R2]
All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
[SQL Server 2005]
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
Additionally, point to note - and this applies to both 2005 and 2008:
The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the
OPTION (EXPAND VIEWS)
query hint.
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
I got this error any time I was calling async on a renderItem function in my FlatList.
I had to create a new function to set my Firestore collection to my state before calling said state data inside my FlatList.
Using EntrySet() and for each loop
for(Map.Entry<String, String> entry: hashMap.entrySet()) {
System.out.println("Key Of map = "+ entry.getKey() +
" , value of map = " + entry.getValue() );
}
Using keyset() and for each loop
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using EntrySet() and java Iterator
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using keyset() and java Iterator
Iterator<String> keysIterator = keySet.iterator();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
}
Reference : How to iterate over Map or HashMap in java
This method work for me. It open Gmail app (if installed) and set mailto.
public void openGmail(Activity activity) {
Intent emailIntent = new Intent(Intent.ACTION_VIEW);
emailIntent.setType("text/plain");
emailIntent.setType("message/rfc822");
emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
final PackageManager pm = activity.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
activity.startActivity(emailIntent);
}
Another answer which validates day (dd) depending upon the month (mm) and the year (yyyy) (i.e., also validates 29th Feb in leap years) and allows years ranging from 0001 to 9999 (0000 in a invalid year according to the Gregorian calendar)
^(?:(?:(?:0[1-9]|[12]\d|3[01])/(?:0[13578]|1[02])|(?:0[1-9]|[12]\d|30)/(?:0[469]|11)|(?:0[1-9]|1\d|2[0-8])/02)/(?!0000)\d{4}|(?:(?:0[1-9]|[12]\d)/02/(?:(?!0000)(?:[02468][048]|[13579][26])00|(?!..00)\d{2}(?:[02468][048]|[13579][26]))))$
From the manpage for env
(GNU coreutils 6.10):
env - run a program in a modified environment
In theory you could use env
to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python
through env
lets you abstractly specify python
without knowing its path.)
In the WPF application, you can handle this by handling TextChanged
event:
void arsDigitTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
bool handle = regex.IsMatch(this.Text);
if (handle)
{
StringBuilder dd = new StringBuilder();
int i = -1;
int cursor = -1;
foreach (char item in this.Text)
{
i++;
if (char.IsDigit(item))
dd.Append(item);
else if(cursor == -1)
cursor = i;
}
this.Text = dd.ToString();
if (i == -1)
this.SelectionStart = this.Text.Length;
else
this.SelectionStart = cursor;
}
}
you can also highlight the spaces (replacing the spaces with a block):
:%s/ /¦/g
(before writing undo it)
heap space errors generally occur due to either bringing too much data back to the driver or the executor. In your code it does not seem like you are bringing anything back to the driver, but instead you maybe overloading the executors that are mapping an input record/row to another using the threeDReconstruction() method. I am not sure what is in the method definition but that is definitely causing this overloading of the executor. Now you have 2 options,
I would advise being careful with the increase and use only as much as you need. Each job is unique in terms of its memory requirements, so I would advise empirically trying different values increasing every time by a power of 2 (256M,512M,1G .. and so on)
You will arrive at a value for the executor memory that will work. Try re-running the job with this value 3 or 5 times before settling for this configuration.
SELECT name, COUNT(name) AS count
FROM table
GROUP BY name
UNION ALL
SELECT 'SUM' name, COUNT(name)
FROM table
OUTPUT:
name count
-------------------------------------------------- -----------
alpha 1
beta 3
Charlie 2
SUM 6
Regarding the original question asked in the title ...
sudo apt-get install libtcnative-1
or if you are on RHEL Linux yum install tomcat-native
The documentation states you need http://tomcat.apache.org/native-doc/
sudo apt-get install libapr1.0-dev libssl-dev
yum install apr-devel openssl-devel
Install autoenv either by
$ pip install autoenv
(or)
$ brew install autoenv
And then create .env
file in your virtualenv project folder
$ echo "source bin/activate" > .env
Now everything works fine.
If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts
double rounded = Math.rint(toround * 100) / 100;
Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;
<select name="foo" id="foo" value="${myBean.foo}">
<option value="">ALL</option>
<c:forEach items="${fooList}" var="val">
<option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>
</c:forEach>
</select>
I found this which covers most sample links, including subdirectory parts.
Regex is:
(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?
Share my stupid thought:
Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+
where distinct
is a qualifier for each column.
But after thought, I find that distinct on only one column is nonsense. Take the following relationship:
| A | B
__________
1| 1 | 2
2| 1 | 1
If we select (distinct A), B
, then what is the proper B
for A = 1
?
Thus, distinct
is a qualifier for a statement
.
Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.