A much simpler way to do this is to use vCenter Converter Standalone Client and do a P2V but in this case a V2V. It is much faster than copying the entire VM files onto some storage somewhere and copy it onto your new vCenter. It takes a long time to copy or exporting it to an OVF template and then import it. You can set your vCenter Converter Standalone Client to V2V in one step and synchronize and then have it power up the VM on the new Vcenter and shut off on the old vCenter. Simple.
For me using this method I was able to move a VM from one vCenter to another vCenter in about 30 minutes as compared to copying or exporting which took over 2hrs. Your results may vary.
This process below, from another responder, would work even better if you can present that datastore to ESXi servers on the vCenter and then follow step 2. Eliminating having to copy all the VMs then follow rest of the process.
I think the best way to do this is to use CheckedItems
:
foreach (DataRowView objDataRowView in CheckBoxList.CheckedItems)
{
// use objDataRowView as you wish
}
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public List<StudentEntity> findAllByOrderByIdAsc();
}
The code above should work. I'm using something similar:
public List<Pilot> findTop10ByOrderByLevelDesc();
It returns 10 rows with the highest level.
IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:
findAllByOrderByIdAsc(); // don't miss "by"
^
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
If the table is InnoDB, see http://dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html -- it uses consistent-read (no-locking mode) for SELECTs "that do not specify FOR UPDATE or LOCK IN SHARE MODE if the innodb_locks_unsafe_for_binlog option is set and the isolation level of the transaction is not set to SERIALIZABLE. Thus, no locks are set on rows read from the selected table".
I had an issue with R 2.15.3 whereby while trying to create a tree structure recursively on a shared network drive I would get a permission error.
To get around this oddity I manually create the structure;
mkdirs <- function(fp) {
if(!file.exists(fp)) {
mkdirs(dirname(fp))
dir.create(fp)
}
}
mkdirs("H:/foo/bar")
You can use insert
to specify where you want to new column to be. In this case, I use 0
to place the new column at the left.
df.insert(0, 'Name', 'abc')
Name Date Open High Low Close
0 abc 01-01-2015 565 600 400 450
Create a XIB file :
File -> new File ->ios->cocoa touch class -> next
make sure check mark "also create XIB file"
I would like to perform with tableview
so I choosed subclass UITableViewCell
you can choose as your requerment
XIB file desing as your wish (RestaurantTableViewCell.xib)
we need to grab the row height to set table each row hegiht
Now! need to huck them swift file . i am hucked the restaurantPhoto
and restaurantName
you can huck all of you .
Now adding a UITableView
name
The name of the nib file, which need not include the .nib extension.
owner
The object to assign as the nib’s File's Owner object.
options
A dictionary containing the options to use when opening the nib file.
first
if you do not define first then grabing all view .. so you need to grab one view inside that set frist
.
Bundle.main.loadNibNamed("yourUIView", owner: self, options: nil)?.first as! yourUIView
here is table view controller Full code
import UIKit
class RestaurantTableViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let restaurantTableviewCell = Bundle.main.loadNibNamed("RestaurantTableViewCell", owner: self, options: nil)?.first as! RestaurantTableViewCell
restaurantTableviewCell.restaurantPhoto.image = UIImage(named: "image1")
restaurantTableviewCell.restaurantName.text = "KFC Chicken"
return restaurantTableviewCell
}
// set row height
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
}
you done :)
I followed this Qiita tutorial to solve my trouble.
Environment: Cordova 8.1.1
, Android Studio 3.2
, cordova-android 7.0.0
.profile
file.export PATH="/Applications/Android Studio.app/Contents/gradle/gradle-4.6/bin":$PATH
source ~/.profle
cordova build android
PS: If [email protected]
causes build error, downgrade your platform version to 6.3.0.
You can use the -d option with mysqldump command
mysqldump -u root -p -d databasename > database.sql
I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1
Color color = -1;
Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.
So,
enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;
To handle arbitrary floating number:
function shorten(num) {
num += 0.000000001;// to deal with "12.03999999997" form
num += '';
return num.replace(/(\.\d*?)0{5,}\d+$/, '$1') * 1;
}
console.log(1.2+1.9===1.3+1.8);// false
console.log(shorten(1.2+1.9)===shorten(1.3+1.8));// true
int hours = (int)Math.Round((b - a).TotalHours)
Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):
Public Sub subCreatePDF() If Not IsPDFLibraryInstalled Then 'Better show this as a userform with a proper link: MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". Exit Sub End If ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=ActiveWorkbook.Path & Application.PathSeparator & _ ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _ Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True End Sub Private Function IsPDFLibraryInstalled() As Boolean 'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm) IsPDFLibraryInstalled = _ (Dir(Environ("commonprogramfiles") & _ "\Microsoft Shared\OFFICE" & _ Format(Val(Application.Version), "00") & _ "\EXP_PDF.DLL") <> "") End Function
I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Value = "";
}
}
open the command prompt Go to project directory
type git remote add origin your git hub repository location with.git
I am not really sure why, but as soon as I comment out the following method it works:
connectionDidFinishDownloading:destinationURL:
Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.
As of Android Studio 0.8.4 .gitignore
file is generated automatically when starting new project.
By default it contains:
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
Signalling a pod on config map update is a feature in the works (https://github.com/kubernetes/kubernetes/issues/22368).
You can always write a custom pid1 that notices the confimap has changed and restarts your app.
You can also eg: mount the same config map in 2 containers, expose a http health check in the second container that fails if the hash of config map contents changes, and shove that as the liveness probe of the first container (because containers in a pod share the same network namespace). The kubelet will restart your first container for you when the probe fails.
Of course if you don't care about which nodes the pods are on, you can simply delete them and the replication controller will "restart" them for you.
Resharper detected Microsoft.Web.Infrastructure as an unused reference an so I deleted it. Locally was working fine but then I got the same error after publishing to dev.
Conclusion, beware when deleting references marked as unused by Resharper
<target name="check-abc">
<available file="abc.txt" property="abc.present"/>
</target>
<target name="do-if-abc" depends="check-abc" if="abc.present">
...
</target>
This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn();
is what you require
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
From digging into the iOS 8 docs that are available as of Sept 9th 3:30pm there is no mention of developer access to the NFC controller to perform any NFC operations; that includes reading tags, writing tags, pairing, payments, tag emulation... Given its an NXP controller the hardware has the capability to perform these features. They did mention a 3rd party app for the watch that allowed a hotel guest to open their room door with NFC. This is a classic use case for NFC and gives some indication that the NFC controller will be open to developers at some point. Remember, the watch is not supposed to be released until Q1 2015. So for now I'd say it's closed but will be open soon. Given the 'newness' of contactless payments for the general US consumer and the recent security breaches its not surprising Apple wants to keep this closed for a while.
Disclosure: Im the CEO of GoToTags, an NFC company with obvious vested interest in Apple opening up NFC to developers.
--- Correction & Update ---
The hotel app actually uses Bluetooth, not NFC. NFC is still often used for door unlocking, just not in this one example. NFC could be used if the watch has an open NFC controller.
I do know that Apple is aware of all of this and is discussing this with their top developers and stakeholders. There has already been massive negative push back on the lack of support for reading tags. As often the case in the past, I expect Apple to eventually open this up to developers for non-payment related functionality (reading tags, pairing). I do not think Apple will ever allow other wallets though. File sharing will likely be left to AirDrop as well.
--- Update on March 23rd 2016 ---
I am continually asked for updates about this topic, often with people referencing this post. With Apple releasing the iPhone SE, many are again asking why Apple has not supported tag reading yet. In summary Apple is more focused on Apple Pay succeeding than the other use cases for NFC for now. Apple could make a lot of money from Apple Pay, and has less to make from the other uses for NFC. Apple will likely open up NFC tag reading when they feel that consumer trust and security with NFC and Apple Pay is such that it wont put Apple Pay at risk. Further information here.
--- Update on May 24th 2017 ---
A developer in Greece has hacked the iPhone 6s to get it to read NFC tags via the NFC private frameworks; more info & video. While this isn't a long term solution, it provides some guidance on some outstanding question: Is there enough power in the iPhone's NFC controller to power an NFC tag? Looks like the answer is yes. From initial testing the range is a few cm, which isn't too bad. It might also be the power is tunable; this is being investigated at this time. The implications of this are significant. If the older model phones do have enough RF power for tag reading/writing, then when Apple does open up the SDK it means there will be 100Ms of iPhones that can read NFC tags, vs the case where only the new iPhones could.
use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,
this is a code:
input type="submit" name="continue" value="submit" onClick="**return** checkform();"
Related to the question in your answer:
You have multiple options to achieve this that are way better:
Let's assume you have a model which you pass to the view:
$model = Model::find(1);
View::make('view')->withModel($model);
Now in your Model you could have a function:
public function someFunction() {
// do something
}
In your view you could call that function directly:
{{$model->someFunction()}}
This is nice if you want to do something with the model (the dataset).
If not you can still make a static function in the model:
public static function someStaticFunction($var1, $var2) {
// do something
}
And then:
{{App\Model::someStaticFunction($yourVar1,$yourVar2)}}
Hope it helps.
If using command line tools, do
sdkmanager 'extras;google;m2repository'
sdkmanager 'extras;android;m2repository'
Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work.
Python doesn't really have ++ and --, and I personally never felt it was such a loss.
I prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability.
You could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()
Okay lots of posts here, none of them helped me, days and days of google, and still no further I got to the point the wr-writing the whole app from scratch, and then I noticed this little nugget in my Web.confg
<httpCookies requireSSL="false" domain="*.localLookup.net"/>
Now I don't know why I added it however I have since noticed, its ignored in debug mode and not in a production mode (IE Installed to IIS Somewhere)
For me the solution was one of 2 options, since I don't remember why I added it I cant be sure other things don't depend on it, and second the domain name must be all lower case and a TLD not like ive done in *.localLookup.net
Maybe it helps maybe it don't. I hope it does help someone
Just connect to Internet and start Android Studio and open your project. While Gradle Sync it will download the dependencies from Internet(All JAR Files). This solved it for me. No Editing in Gradle file ,all was done by Android Studio Automatically. Using Android Studio 2.2 :)
Also don't forget to install Java JDK 1.x(7 or 8 all works fine).
for example try this :
<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>
document.getElementById("myLink1").onclick = function() { window.open( "http://www.facebook.com" ); return false; }; document.getElementById("myLink2").onclick = function() { window.open( "http://www.yahoo.com" ); return false; };
The same thing is happening for me.
The reason is: I have used a list view with margin Top so the data is starting from the bottom of the image, but the actual list view is overlapping on the image which is not visible. So even if we click on the image, the action is not performed. To fix this, I have made the list view start from the below the image so that it is not overlapping on the image itself.
I was also facing the same issue, then i tried restarting my system after every change and it worked for me:
httpd -k uninstall
.httpd -k install
.httpd -k install
.Hope you find useful.
This is really easy using jQuery.
For instance:
$(".left").mouseover(function(){$(".left1").show()});
$(".left").mouseout(function(){$(".left1").hide()});
I've update your fiddle: http://jsfiddle.net/TqDe9/2/
Took some tooling around but this is what I ended up with.
Generated and installed a certificate on IIS7. Exported as PFX from IIS
Convert to pkcs12
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.
-----BEGIN PRIVATE KEY-----
Saved as certificate.key
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
Saved as certificate.crt
-----END CERTIFICATE-----
Added to apache vhost w/ Webmin.
Have a look at the start up scripts a Java heap size is set there, it looks like you're not setting this before running Spark worker.
# Set SPARK_MEM if it isn't already set since we also use it for this process
SPARK_MEM=${SPARK_MEM:-512m}
export SPARK_MEM
# Set JAVA_OPTS to be able to load native libraries and to set heap size
JAVA_OPTS="$OUR_JAVA_OPTS"
JAVA_OPTS="$JAVA_OPTS -Djava.library.path=$SPARK_LIBRARY_PATH"
JAVA_OPTS="$JAVA_OPTS -Xms$SPARK_MEM -Xmx$SPARK_MEM"
You can find the documentation to deploy scripts here.
The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.
Specifically, you'd set the textColor
of your textViews to an XML resource like this one:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
<item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
<item android:drawable="@color/black" /> <!-- default -->
</selector>
You can also dynamically add attributes with variables directly in an object literal.
const amountAttribute = 'amount';
const foo = {
[amountAttribute]: 1
};
foo[amountAttribute + "__more"] = 2;
Results in:
{
amount: 1,
amount__more: 2
}
By using the find
command in conjunction with the mv
command, you can prevent the mv
command from trying to move directories (e.g. ..
and .
) and subdirectories. Here's one option:
find /path/subfolder -maxdepth 1 -type f -name '*' -exec mv -n {} /path \;
There are problems with some of the other answers provided. For example, each of the following will try to move subdirectories from the source path:
1) mv /path/subfolder/* /path/ ; mv /path/subfolder/.* /path/
2) mv /path/subfolder/{.,}* /path/
3) mv /source/path/{.[!.],}* /destination/path
Also, 2) includes the . and .. files and 3) misses files like ..foobar, ...barfoo, etc.
You could use, mv /source/path/{.[!.],..?,}* /destination/path
, which would include the files missed by 3), but it would still try to move subdirectories. Using the find
command with the mv
command as I describe above eliminates all these problems.
This problem is generally caused by the website/intranet URL being placed in one of:
On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.
Unfortunately setting META X-UA-Compatible
will not override this.
Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.
You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.
To see the list of domains that belong to the Intranet zone, go to:
Tools -> Internet Options -> Security -> Sites -> Advanced
If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.
You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.
Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.
All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.
If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).
const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
file.key = "new value";
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
The caveat is that json is written to the file on one line and not prettified. ex:
{
"key": "value"
}
will be...
{"key": "value"}
To avoid this, simply add these two extra arguments to JSON.stringify
JSON.stringify(file, null, 2)
null
- represents the replacer function. (in this case we don't want to alter the process)
2
- represents the spaces to indent.
Add the following to your ~/.gitconfig
file
[alias]
cat = "!git show \"$1:$2\" #"
And then try this
git cat BRANCHNAME FILEPATH
Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout
command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show
command.
In addition to already suggested p
and puts
— well, actually in most cases you do can write logger.info "blah"
just as you suggested yourself. It works in console too, not only in server mode.
But if all you want is console debugging, puts
and p
are much shorter to write, anyway.
There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0
when using document.documentElement.scrollTop
or jQuery's $(window).scrollTop()
.
However, it works consistently with:
// horizontal scrolling amount
window.pageXOffset
// vertical scrolling amount
window.pageYOffset
For an easy revert if it's just a mistake (perhaps you forked a repo, then ended up pushing to the original instead of to a new one) here's another possibility:
git reset --hard 71c27777543ccfcb0376dcdd8f6777df055ef479
Obviously swap in that number for the number of the commit you want to return to.
Everything since then will be deleted once you push again. To do that, the next step would be:
git push --force
Let's say that you have a folder named "contollers".
In your app.js you can put this code:
console.log("Loading controllers....");
var controllers = {};
var controllers_path = process.cwd() + '/controllers'
fs.readdirSync(controllers_path).forEach(function (file) {
if (file.indexOf('.js') != -1) {
controllers[file.split('.')[0]] = require(controllers_path + '/' + file)
}
});
console.log("Controllers loaded..............[ok]");
... and ...
router.get('/ping', controllers.ping.pinging);
in your controllers forlder you will have the file "ping.js" with this code:
exports.pinging = function(req, res, next){
console.log("ping ...");
}
And this is it....
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start(). The result is a new instance of class Thread, which is called join().
The .net library System.Data.SQLite also provides for encryption.
If you are trying to style an input element with :before and :after, odds are you are trying to mimic the effects of other span, div, or even a elements in your CSS stack.
As Robert Koritnik's answer points out, :before and :after can only be applied to container elements and input elements are not containers.
HOWEVER, HTML 5 introduced the button element which is a container and behaves like an input[type="submit|reset"] element.
<style>
.happy:after { content:url(smiley.gif); }
</style>
<form>
<!-- won't work -->
<input class="happy" type="submit" value="Submit" />
<!-- works -->
<button class="happy">Submit</button>
</form>
Using Apache Commons-Lang's SystemUtils.isJavaVersionAtLeast(JavaVersion)
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)
System.out.println("Java version was 8 or greater!");
If you are interested in processing Javascript on the server, there is a new open source library called Jint that allows you to execute server side Javascript. Basically it is a Javascript interpreter written in C#. I have been testing it and so far it looks quite promising.
Here's the description from the site:
Differences with other script engines:
Jint is different as it doesn't use CodeDomProvider technique which is using compilation under the hood and thus leads to memory leaks as the compiled assemblies can't be unloaded. Moreover, using this technique prevents using dynamically types variables the way JavaScript does, allowing more flexibility in your scripts. On the opposite, Jint embeds it's own parsing logic, and really interprets the scripts. Jint uses the famous ANTLR (http://www.antlr.org) library for this purpose. As it uses Javascript as its language you don't have to learn a new language, it has proven to be very powerful for scripting purposes, and you can use several text editors for syntax checking.
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add
and then just did git reset
. This basically just added and then unstaged my changes but cleared the unmerged paths.
Finally, I've a solution to my uploading problem.
In JavaScript:
var xhr = new XMLHttpRequest();
xhr.open("post", 'uploader.php', true);
xhr.setRequestHeader("pragma", "no-cache");
In PHP:
header('cache-control: no-cache');
I would suggest , to use .Net's IDisposable interface if your are thinking of to release instance after its usage.
See a sample implementation below.
public class Car : IDisposable
{
public void Dispose()
{
Dispose(true);
// any other managed resource cleanups you can do here
Gc.SuppressFinalize(this);
}
~Car() // finalizer
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_stream != null) _stream.Dispose(); // say you have to dispose a stream
}
_stream = null;
_disposed = true;
}
}
}
Now in your code:
void main()
{
using(var car = new Car())
{
// do something with car
} // here dispose will automtically get called.
}
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
Update 2020
Products are located mainly in the following tables:
wp_posts
table with post_type
like product
(or product_variation
),
wp_postmeta
table with post_id
as relational index (the product ID).
wp_wc_product_meta_lookup
table with product_id
as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)
wp_wc_order_product_lookup
table with product_id
as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)
Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:
wp_terms
wp_termmeta
wp_term_taxonomy
wp_term_relationships
- column object_id
as relational index (the product ID)
wp_woocommerce_termmeta
wp_woocommerce_attribute_taxonomies
(for product attributes only)
wp_wc_category_lookup
(for product categories hierarchy only since WooCommerce 3.7)
Product types are handled by custom taxonomy product_type
with the following default terms:
simple
grouped
variable
external
Some other product types for Subscriptions and Bookings plugins:
subscription
variable-subscription
booking
Since Woocommerce 3+ a new custom taxonomy named product_visibility
handle:
exclude-from-search
and exclude-from-catalog
featured
outofstock
rated-1
to rated-5
Particular feature: Each product attribute is a custom taxonomy…
References:
The issue could be that Github isn't present in your ~/.ssh/known_hosts file.
Append GitHub to the list of authorized hosts:
ssh-keyscan -H github.com >> ~/.ssh/known_hosts
You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:
var _this = this;
exports.somefunction = function() {
console.log('hello');
}
exports.someotherfunction = function() {
_this.somefunction();
}
One of the key differences between margin and padding is not mentioned in any of the answers: clickability and hover detection
Increasing the padding increases the effective size of the element. Sometimes I have a smallish icon that I don't want to make visibly larger but the user still needs to interact with that icon. I increase the icon's padding to give it a larger footprint for clicks and hover. Increasing the icon's margin will not have the same effect.
An answer to another question on this topic gives an example.
If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:
Javascript:
function limitDecimalPlaces(e, count) {
if (e.target.value.indexOf('.') == -1) { return; }
if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
e.target.value = parseFloat(e.target.value).toFixed(count);
}
}
HTML:
<input type="number" oninput="limitDecimalPlaces(event, 2)" />
Note that this cannot AFAIK, defend against this chrome bug with the number input.
Many modern browsers do not support autocomplete="off" for login fields anymore.
autocomplete="new-password"
is wokring instead, more information MDN docs
If you are planning on doing any kind of inheritance, then I would recommend this.constructor
. This simple example should illustrate why:
class ConstructorSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(this.name, n);
}
callPrint(){
this.constructor.print(this.n);
}
}
class ConstructorSub extends ConstructorSuper {
constructor(n){
this.n = n;
}
}
let test1 = new ConstructorSuper("Hello ConstructorSuper!");
console.log(test1.callPrint());
let test2 = new ConstructorSub("Hello ConstructorSub!");
console.log(test2.callPrint());
test1.callPrint()
will log ConstructorSuper Hello ConstructorSuper!
to the
consoletest2.callPrint()
will log ConstructorSub Hello ConstructorSub!
to the consoleThe named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:
class NamedSuper {
constructor(n){
this.n = n;
}
static print(n){
console.log(NamedSuper.name, n);
}
callPrint(){
NamedSuper.print(this.n);
}
}
class NamedSub extends NamedSuper {
constructor(n){
this.n = n;
}
}
let test3 = new NamedSuper("Hello NamedSuper!");
console.log(test3.callPrint());
let test4 = new NamedSub("Hello NamedSub!");
console.log(test4.callPrint());
test3.callPrint()
will log NamedSuper Hello NamedSuper!
to the
consoletest4.callPrint()
will log NamedSuper Hello NamedSub!
to the consoleSee all the above running in Babel REPL.
You can see from this that test4
still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.
On OSX, install the rename script from Homebrew:
brew install rename
Then you can do it really ridiculously easily:
rename -e 's/.*/$N.jpg/' *.jpg
Or to add a nice prefix:
rename -e 's/.*/photo-$N.jpg/' *.jpg
A void*
does not mean anything. It is a pointer, but the type that it points to is not known.
It's not that it can return "anything". A function that returns a void*
generally is doing one of the following:
operator new
and malloc
return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void
.This construct is nothing like dynamic
or object
in C#. Those tools actually know what the original type is; void*
does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.
And on a personal note, if you see code that uses void*
's "often", you should rethink what code you're looking at. void*
usage, especially in C++, should be rare, used primary for dealing in raw memory.
Main difference is that when you are querying a view then it's definition is pasted into your query. Procedure could also give results of query, but it is compiled and for so faster. Another option are indexed views..
Don't forget to seed the RNG with srand() first.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];
Hibernate is trying to say that it does not know an entity named "Books". Let's look at your entity:
@javax.persistence.Entity
@javax.persistence.Table(name = "Books")
public class Book {
Right. The table name for Book
has been renamed to "Books" but the entity name is still "Book" from the class name. If you want to set the entity name, you should use the @Entity
annotation's name instead:
// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {
That sets both the entity name and the table name.
The opposite problem happened to me when I was migrating from the Person.hbm.xml
file to using the Java annotations to describe the hibernate fields. My old XML file had:
<hibernate-mapping package="...">
<class name="Person" table="persons" lazy="true">
...
</hibernate-mapping>
And my new entity had a @Entity(name=...)
which I needed to set the name of the table.
// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {
...
What I then was seeing was HQL errors like:
QuerySyntaxException: Person is not mapped
[SELECT id FROM Person WHERE id in (:ids)]
The problem with this was that the entity name was being renamed to persons
as well. I should have set the table name using:
// no name = here so the entity can be used as Person
@javax.persistence.Entity
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {
Hope this helps others.
I used below piece of code. Here dragAndDrop(x,y) is a method of Action class. Which takes two parameters (x,y), source location, and target location respectively
try {
System.out.println("Drag and Drom started :");
Thread.sleep(12000);
Actions actions = new Actions(webdriver);
WebElement srcElement = webdriver.findElement(By.xpath("source Xpath"));
WebElement targetElement = webdriver.findElement(By.xpath("Target Xpath"));
actions.dragAndDrop(srcElement, targetElement);
actions.build().perform();
System.out.println("Drag and Drom complated :");
} catch (Exception e) {
System.out.println(e.getMessage());
resultDetails.setFlag(true);
}
This might be a bit overkill, but I always use the the np.take
function for any wrap-around indexing:
>>> a = np.array([1, 2, 3])
>>> np.take(a, range(0, len(a)+1), mode='wrap')
array([1, 2, 3, 1])
>>> np.take(a, range(-1, len(a)+1), mode='wrap')
array([3, 1, 2, 3, 1])
Try this, to make sure you configured CORS correctly:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Still not working? Check HTTP headers presence.
With the help of Tim C's answer, I was able to create an extension on UIButton
using Swift that allows you to specify the image frame by using the .setImage()
function with an extra frame
parameter
extension UIButton{
func setImage(image: UIImage?, inFrame frame: CGRect?, forState state: UIControlState){
self.setImage(image, forState: state)
if let frame = frame{
self.imageEdgeInsets = UIEdgeInsets(
top: frame.minY - self.frame.minY,
left: frame.minX - self.frame.minX,
bottom: self.frame.maxY - frame.maxY,
right: self.frame.maxX - frame.maxX
)
}
}
}
Using this, if you wanted to set the frame of a UIButton
to CGRectMake(0, 0, 64, 64)
, and set the image of it to myImage
with a frame of CGRectMake(8, 8, 48, 48)
, you could use
let button: UIButton = UIButton(frame: CGRectMake(0, 0, 64, 64))
button.setImage(
myImage,
inFrame: CGRectMake(8, 8, 48, 48),
forState: UIControlState.Normal
)
You can escape the quotes with a backslash:
"I asked my son's teacher, \"How is my son doing now?\""
So what I see with the other answers is that they don't address the fundamental architectural requirement of a static attribute in object oriented programming.
Object oriented programming actually has two different styles one is 'class based' (C++, C#, Java etc), the other is 'prototypal' (Javascript). In class based languages a 'static attribute' is supposed to be associated with the class and not the instantiated objects. This concept actually works much more intuitively in a prototypal languages like Javascript because you just assign the attribute as a value of the parent prototype like so.
function MyObject() {};
MyObject.prototype.staticAttribute = "some value";
And access it from every one of the objects that is instantiated from this constructor like so...
var childObject1 = new MyObject(); // Instantiate a child object
var childObject2 = new MyObject(); // Instantiate another child object
console.log(childObject.staticAttribute); // Access the static Attribute from child 1
console.log(childObject.staticAttribute); // Access the static Attribute from child 2
Now if you go ahead and change the MyObject.prototype.staticAttribute
the change will cascade down to the child objects that immediately inherit it.
However there are a few 'gotchas' that could significantly undermine the 'static' nature of this attribute, or just leave security vulnerability...
First make sure to hide the constructor from the Global namespace by enclosing it inside another function like the jQuery ready method
$(document).ready(function () {
function MyObject() {
// some constructor instructions
};
MyObject.prototype.staticAttribute = "some value";
var childObject = new MyObject(); // instantiate child object
console.log(childObject.staticAttribute); // test attribute
});
Second and lastly, even if you do this, the attribute is still editable from any of the other parts of your own script, so it could be the case that a bug in your code writes over the attribute on one of the child objects and detaches it from the parent prototype, so if you change the parent attribute it will no longer cascade and change the static attribute for the child object. See this jsfiddle. In different scenarios we could either Object.freeze(obj)
to stop any changes to the child object, or we could set up a setter and getter method in the constructor and access a closure, both of these have associated complexities.
It seems to me that there is not a perfect analogue between the class-based idea of a 'static attribute' and this Javascript implementation. So I think it might be better in the long run to use a different code pattern that is more Javascript friendly. Such as a central datastore or cache or even a dedicated helper object to hold all the necessary static variables.
Try the following:
var div = document.createElement("div");
div.innerHTML = "topdiv";
div.appendChild(element);
document.body.appendChild(div);
I think you should cast the pointers to (void *) to get rid of the warnings.
memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);
Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.
sizeof(struct RTCclk)
Use LinkedList
instead. Than, you can create an array if necessary.
Just try " gcc filename.c -lm" while compiling the program ...it worked for me
When cloning, by default it will not clone the events. The added rows do not have an event handler attached to them. If you call clone(true)
then it should handle them as well.
If you want to use std::string
reliably, you must #include <string>
.
You may face two errors while testing tomcat server startup.
Fixes -
The reason for choosing this option is, When the default option is given as eclipse location, we will see 404 error as it changes Catalina parameters (sometimes). But if we change it to Tomcat location, it works fine.
md5sum
worked fine for me, but I had issues with sort
and sorting file names. So instead I sorted by md5sum
result. I also needed to exclude some files in order to create comparable results.
find . -type f -print0 \
| xargs -r0 md5sum \
| grep -v ".env" \
| grep -v "vendor/autoload.php" \
| grep -v "vendor/composer/" \
| sort -d \
| md5sum
You can try downloading the Windows binaries for pip from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip.
For using pip to download other modules, see @Ben Burn's answer.
I've found that scrolling in viewWillAppear
may not work reliably because the collection view hasn't finished it's layout yet; you may scroll to the wrong item.
I've also found that scrolling in viewDidAppear
will cause a momentary flash of the unscrolled view to be visible.
And, if you scroll every time through viewDidLayoutSubviews
, the user won't be able to manually scroll because some collection layouts cause subview layout every time you scroll.
Here's what I found works reliably:
Objective C :
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// If we haven't done the initial scroll, do it once.
if (!self.initialScrollDone) {
self.initialScrollDone = YES;
[self.collectionView scrollToItemAtIndexPath:self.myInitialIndexPath
atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
}
}
Swift :
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if (!self.initialScrollDone) {
self.initialScrollDone = true
self.testNameCollectionView.scrollToItem(at:selectedIndexPath, at: .centeredHorizontally, animated: true)
}
}
You are missing the parent constructor. When your controller is loaded you must Call the parent CI_Controller class constructor in your controller constructor
<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
//Iterate through an array declared above
foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";
foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}
echo ")";
}
}
?>
OUTPUT:
lang => PHP
type => array(
c_type => MULTI
p_type => ARRAY
)
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
This article helped, it's pretty much what the other answers said but summarize and concise
https://medium.com/@andersongusmao/left-and-right-margins-on-uitableviewcell-595f0ba5f5e6
In it, he only applies them to left and right sides but the UIEdgeInsetsMake
init allows to add padding to all four points.
func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets
Description
Creates an edge inset for a button or view. An inset is a margin around a rectangle. Positive values represent margins closer to the center of the rectangle, while negative values represent margins further from the center.Parameters
top: The inset at the top of an object.
left: The inset on the left of an object
bottom: The inset on the bottom of an object.
right: The inset on the right of an object.Returns
An inset for a button or view
Note that UIEdgeInsets can also be used to achieve the same.
Xcode 9.3/Swift 4
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.
What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready()
for the initial load, then use Microsoft's PageRequestManager
(available if you have an update panel on your page) to re-subscribe every update.
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
});
The PageRequestManager
is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.
If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs)
so you can see what raised the event and only re-bind if needed.
Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx
A better option you may have, depending on your needs, is to use jQuery's .on()
. These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use .delegate()
or .on()
, so in those cases, you're better off re-subscribing.
location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL
var hash = document.URL.substr(document.URL.indexOf('#')+1)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CsvFile {
public static void main(String[]args){
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("NewData.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder builder = new StringBuilder();
String columnNamesList = "Id,Name";
// No need give the headers Like: id, Name on builder.append
builder.append(columnNamesList +"\n");
builder.append("1"+",");
builder.append("Chola");
builder.append('\n');
pw.write(builder.toString());
pw.close();
System.out.println("done!");
}
}
If it's a matter of just opening PDF to send some keys to it then why not try this
Sub Sample()
ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub
I am assuming that you have some pdf reader installed.
Fastest way is this :
public static string GetHash(string input)
{
return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
}
For Small character output use x2
in replace of of X2
In [Package Manager Console]
try the below
Install-Package NuGet.CommandLine
You can also use
Remove-Migration -Force
This will revert and remove the last applied migration
An object is mutable if, once created, its state can be changed by calling various operations on it, otherwise it is immutable.
In C# (and .NET) a string is represented by class System.String. The string
keyword is an alias for this class.
The System.String class is immutable, i.e once created its state cannot be altered.
So all the operations you perform on a string like Substring
, Remove
, Replace
, concatenation using '+' operator etc will create a new string and return it.
See the following program for demonstration -
string str = "mystring";
string newString = str.Substring(2);
Console.WriteLine(newString);
Console.WriteLine(str);
This will print 'string' and 'mystring' respectively.
For the benefits of immutability and why string are immutable check Why .NET String is immutable?.
If you want to have a string which you want to modify often you can use the StringBuilder
class. Operations on a StringBuilder
instance will modify the same object.
For more advice on when to use StringBuilder
refer to When to use StringBuilder?.
I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV
and HTML::Parser
.
To match pattern
or an empty string, use
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.\b
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b
is located:
\w
and \W
(either order):
^
and \w
\w
\w
and $
\w
This is not trivial depending on specification.
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
SDK tools required build tool version installation helped me. You just need to install required build tool version from,
SDK Manager -> SDK tool -> Show Package details -> Select required build tool version and install it.
I was getting the same error on a restored database when I tried to insert a new record using the EntityFramework. It turned out that the Indentity/Seed was screwing things up.
Using a reseed command fixed it.
DBCC CHECKIDENT ('[Prices]', RESEED, 4747030);GO
Like Jason S's answer:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I put this in my Main and look to my app.config
and test if (ConfigurationManager.AppSettings["IgnoreSSLCertificates"] == "True")
before calling that line of code.
You can add a sequence of numbers very easily with
data$ID <- seq.int(nrow(data))
If you are already using library(tidyverse)
, you can use
data <- tibble::rowid_to_column(data, "ID")
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
You must detach your entity from session before modifying its ID fields
I think your answer can be found on this page. From the page:
This Folder, Subfolders and Files:
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
Are you strong-naming your assemblies? In that case it is not a good idea to auto-increment your build number because with every new build number you will also have to update all your references.
I had the same problem. I had VMware Workstation 15.5.4 and Windows 10 version 1909 and installed Docker Desktop.
Here how I solved it:
As VMware Guide said in this link
If your Host has Windows 10 20H1 build 19041.264 or newer, upgrade/update to Workstation 15.5.6 or above. If your Host has Windows 10 1909 or earlier, disable Hyper-V on the host to resolve this issue.
Now VMware and Hyper-V can be at the same time and have both Docker and VMware at my Windows.
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function MyApp() {
const location = useLocation();
useEffect(() => {
console.log('route has been changed');
...your code
},[location.pathname]);
}
with hooks
JSON.stringify() <-> JSON.parse()
JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.
JSON.stringify() -> Object To String.
JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.
JSON.parse() -> String To Object.
Explanation: JSON.stringify(obj [, replacer [, space]]);
Replacer/Space - optional or takes integer value or you can call interger type return function.
function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}
("Jesse" or "jesse")
The above expression tests whether or not "Jesse"
evaluates to True
. If it does, then the expression will return it; otherwise, it will return "jesse"
. The expression is equivalent to writing:
"Jesse" if "Jesse" else "jesse"
Because "Jesse"
is a non-empty string though, it will always evaluate to True
and thus be returned:
>>> bool("Jesse") # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>
This means that the expression:
name == ("Jesse" or "jesse")
is basically equivalent to writing this:
name == "Jesse"
In order to fix your problem, you can use the in
operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):
Or, you can lowercase the value of name
with str.lower
and then compare it to "jesse"
directly:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
Try
console.log(_x000D_
new Date().toLocaleString().slice(9, -3)_x000D_
, new Date().toString().slice(16, -15)_x000D_
);
_x000D_
For first character in word use .capitalized
in swift and for whole-word use .uppercased()
The JTextField
offers a getText()
and a setText()
method - those are for getting and setting the content of the text field.
I also had trouble overruling a dependency in a third party library. I used scot's approach with the exclusion but I also added the dependency with the newer version in the pom. (I used Maven 3.3.3)
So for the stAX example it would look like this:
<dependency>
<groupId>a.group</groupId>
<artifactId>a.artifact</artifactId>
<version>a.version</version>
<exclusions>
<!-- STAX comes with Java 1.6 -->
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>javax.xml.stream</groupId>
</exclusion>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
</exclusions>
<dependency>
<dependency>
<groupId>javax.xml.stream</groupId>
<artifactId>stax-api</artifactId>
<version>1.0-2</version>
</dependency>
This worked for me.
pip3 install --user package-name # for Python3
pip install --user package-name # for Python2
The --user
flag tells Python to install in the user home directory. By default it will go to system locations. credit
You can validate a TypeScript type at runtime using ts-validate-type, like so (does require a Babel plugin though):
const user = validateType<{ name: string }>(data);
If you want to implements or extends any other class then Runnable
interface is most preferable, otherwise, if you do not want any other class to extend or implement then Thread
class is preferable.
The most common difference is
When you extends Thread
class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
When you implements Runnable
, you can save space for your class to extend any other class in the future or now.
Java doesn't support multiple inheritances, which means you can only extend one class in Java so once you extended Thread class you lost your chance and cannot extend or inherit another class in Java.
In Object-oriented programming, extending a class generally means, adding new functionality, and modifying or improving behaviors. If we are not making any modification on Thread then use Runnable interface instead.
Runnable interface represents a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is a good design decision.
Separating task as Runnable means we can reuse the task and also has the liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.
Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.
Inheriting all Thread methods are additional overhead just for representing a Task which can be done easily with Runnable.
Courtesy from javarevisited.blogspot.com
These were some of the notable differences between Thread and Runnable in Java. If you know any other differences on Thread vs Runnable than please share it via comments. I personally use Runnable over Thread for this scenario and recommends to use Runnable or Callable interface based on your requirement.
However, the significant difference is.
When you extends Thread
class, each of your thread creates a unique object and associate with it.
When you implements Runnable
, it shares the same object to multiple threads.
On Fedora 22, you need to do this instead:
sudo dnf install python-devel
sudo dnf install openldap-devel
I can't find toByteArray()
as @atrioom said, so I use StringWriter
, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString
:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
I know you've already accepted an answer but I believe the problem has to do with calling bind() on a client socket. This might be OK but bind() and shutdown() don't seem to play well together. Also, SO_REUSEADDR is generally used with listen sockets. i.e. on the server side.
You should be passing and ip/port to connect(). Like this:
comSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
comSocket.connect(('', 5555))
Don't call bind(), don't set SO_REUSEADDR.
Partial workaround for gradient transition is to use inset box shadow - you can transition either the box shadow itself, or the background color - e.g. if you create inset box shadow of the same color as background and than use transition on background color, it creates illusion that plain background is changing to radial gradient
.button SPAN {
padding: 10px 30px;
border: 1px solid ##009CC5;
-moz-box-shadow: inset 0 0 20px 1px #00a7d1;
-webkit-box-shadow: inset 0 0 20px 1px#00a7d1;
box-shadow: inset 0 0 20px 1px #00a7d1;
background-color: #00a7d1;
-webkit-transition: background-color 0.5s linear;
-moz-transition: background-color 0.5s linear;
-o-transition: background-color 0.5s linear;
transition: background-color 0.5s linear;
}
.button SPAN:hover {
background-color: #00c5f7;
}
In some scenarios, port
can only be designated by the environment and is saved in a user environment variable. Below is how node.js apps work with it.
The process
object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()
.
The process.env
property returns an object containing the user environment.
An example of this object looks like:
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
For example,
terminal: set a new user environment variable, not permanently
export MY_TEST_PORT=9999
app.js: read the new environment variable from node app
console.log(process.env.MY_TEST_PORT)
terminal: run the node app and get the value
$ node app.js
9999
Its better to understand by trying your own code...
Read more
http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html
1) Convert a String to Uppercase
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
2) Convert a String to Lowercase
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
3) Convert a String to TitleCase
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(TextBox1.Text());
Since July 2017 you can use cmp.Equal
with cmpopts.IgnoreFields
option.
func TestPerson(t *testing.T) {
type person struct {
ID int
Name string
}
p1 := person{ID: 1, Name: "john doe"}
p2 := person{ID: 2, Name: "john doe"}
println(cmp.Equal(p1, p2))
println(cmp.Equal(p1, p2, cmpopts.IgnoreFields(person{}, "ID")))
// Prints:
// false
// true
}
Note that you can also hit this error if you accidentally type:
#define <stdio.h>
...instead of...
#include <stdio.>
Using Neon - just happened to me too. You would have to delete the Eclipse version (not from disk) in your Project Explorer and import the projects as existing projects. Of course, ensure that the project folders as a whole were moved and that the Eclipse meta files are still there as mentioned by @koenpeters.
Refactor does not handle this.
Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0
so it runs after DOM was loaded.
Find it here: JsFiddle
$timeout(function () {
$scope.form.uName.$dirty = true;
}, 0);
I think this is what you are looking for
<asp:TextBox ID="txbPass" runat="server" TextMode="Password"></asp:TextBox>
use this formula to convert a pandas DataFrame to a list of dictionaries :
import json
json_list = json.loads(json.dumps(list(DataFrame.T.to_dict().values())))
using WebkitView
Swift 9.3 iOS 11.3
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
var hideStatusBar = true
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
self.setNeedsStatusBarAppearanceUpdate()
let myURL = URL(string: "https://www.apple.com/")
let myRequest = URLRequest(url: myURL!)
UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
webView.load(myRequest)
}
}
extension UIApplication {
var statusBarView: UIView? {
return value(forKey: "statusBar") as? UIView
}
}
You can use float:left in DIV or use SPAN tag, like
<div style="width:100px;float:left"> First </div>
<div> Second </div>
<br/>
or
<span style="width:100px;"> First </span>
<span> Second </span>
<br/>
I would recommend NOT to use global
/ window
/ eval
for this purpose.
Instead, do it this way:
define all methods as properties of Handler:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Now call it like this
var somefunc = "application_run";
Handler[somefunc]('jerry');
Output: jerry
Case when importing functions from different files
import { func1, func2 } from "../utility";
const Handler= {
func1,
func2
};
Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");
I just came up with this method which may be hardware intensive but it is working:
You can replace all characters which match the regex by an empty string.
This is a oneliner:
notMatched = re.sub(regex, "", string)
I used this because I was forced to use a very complex regex and couldn't figure out how to invert every part of it within a reasonable amount of time.
This will only return you the string result, not any match objects!
Try to add this:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
I think you're missing something.
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
</ul>
In FF4, this displays a 100px black bar, followed by a 500px red block.
A little bit different example:
<ul>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:black;">
</div>
</li>
</ul>
<ul>
<li style="height:100px;">
<div style="height:500px; background-color:red;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:blue;">
</div>
</li>
<li style="height:100px;overflow:hidden;">
<div style="height:500px; background-color:green;">
</div>
</li>
</ul>
If you have an instance function (i.e. one that gets passed self) you can use self to get a reference to the class using self.__class__
For example in the code below tornado creates an instance to handle get requests, but we can get hold of the get_handler
class and use it to hold a riak client so we do not need to create one for every request.
import tornado.web
import riak
class get_handler(tornado.web.requestHandler):
riak_client = None
def post(self):
cls = self.__class__
if cls.riak_client is None:
cls.riak_client = riak.RiakClient(pb_port=8087, protocol='pbc')
# Additional code to send response to the request ...
You can use the following function to enqueue script or style from plugin.
function my_enqueued_assets() {
wp_enqueue_script('my-js-file', plugin_dir_url(__FILE__) . '/js/script.js', '', time());
wp_enqueue_style('my-css-file', plugin_dir_url(__FILE__) . '/css/style.css', '', time());
}
add_action('wp_enqueue_scripts', 'my_enqueued_assets');
@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.
WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;
Hope this helps... :D
While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.
A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.
git checkout --orphan BRANCHNAME
This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.
Now for whatever reason, git needs a bit of cleanup after an orphan checkout.
rm .git/index
rm -r *
Make sure everything is committed before deleting
Once the orphan branch is clean, you can use it normally.
Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.
# repo 1
git push origin master:master-1
# repo 2
git push origin master:master-2
According to Wikipedia:
5222 TCP XMPP client connection (RFC 6120) Official 5223 TCP XMPP client connection over SSL Unofficial 5269 TCP XMPP server connection (RFC 6120) Official 5298 TCP UDP XMPP JEP-0174: Link-Local Messaging / Official XEP-0174: Serverless Messaging 8010 TCP XMPP File transfers Unofficial
The port numbers are defined in RFC 6120 § 14.7.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
If you're targeting Android 6.0 - Marshmallow (API level 23) or higher it's possible to use the new NetworkCapabilities class, i.e:
public static boolean hasInternetConnection(final Context context) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.
getSystemService(Context.CONNECTIVITY_SERVICE);
final Network network = connectivityManager.getActiveNetwork();
final NetworkCapabilities capabilities = connectivityManager
.getNetworkCapabilities(network);
return capabilities != null
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
}
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
In a nutshell, if you turn on the OAuth 2.0
for Canvas advanced option, Facebook will send a $_REQUEST['signed_request']
along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You might be able to workaround this by running initdb -U postgres -D /path/to/data
or running it as user postgres, since it defaults to the current user. GL!
Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger
That is especially handy when your Bar.someMethod() is private
.
You can use windows Powershell to execute a query and output it to a text file
Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt
A verbose equivalent is to combine $LASTEXITCODE
and -eq 0
:
msbuild.exe args; if ($LASTEXITCODE -eq 0) { echo 'it built'; } else { echo 'it failed'; }
I'm not sure why if ($?)
didn't work for me, but this one did.
If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.
See this MSDN article on the MergeOption enum:
Identity Resolution, State Management, and Change Tracking
This seems to be a good article on EF performance:
First step get container id:
docker ps
This will show you something like
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0
1170fe9e9460
is the container id in this case.
Second, enter the docker :
docker exec -it [container_id] bash
so in the above case:
docker exec -it 1170fe9e9460 bash
>>> ok
{'five': '5', 'two': '2', 'one': '1'}
>>> if ('two' and 'one' and 'five') in ok:
... print "cool"
...
cool
This seems to work
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
Use event delegation by assigning the onclick
to the <ol>
. Then pass the event
object as the argument, and using that, grab the text from the clicked element.
function addText(event) {_x000D_
var targ = event.target || event.srcElement;_x000D_
document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
<li>Hello</li>_x000D_
<li>World</li>_x000D_
<li>Earthlings</li>_x000D_
</ol>
_x000D_
Note that this method of passing the event
object works in older IE as well as W3 compliant systems.
rosipov's rule works great!
I use it on live sites to display a blank or special message ;) in place of a direct access attempt to files I'd rather to protect a bit from direct view. I think it's more fun than a 403 Forbidden.
So taking rosipov's rule to redirect any direct request to {gif,jpg,js,txt} files to 'messageforcurious' :
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.ltd.*$ [NC]
RewriteRule \.(gif|jpg|js|txt)$ /messageforcurious [L]
I see it as a polite way to disallow direct acces to, say, a CMS sensible files like xml, javascript... with security in mind: To all these bots scrawling the web nowadays, I wonder what their algo will make from my 'messageforcurious'.
For anyone looking for a UI option using IIS Manager.
Some improvements to avoid wrongly detect the visibility of soft keyboard on high density devices:
Threshold of height difference should be defined as 128 dp, not 128 pixels.
Refer to Google design doc about Metrics and Grid, 48 dp is comfortable size for touch object and 32 dp is minimum for buttons. Generic soft keyboard should include 4 rows of key buttons, so minimum keyboard height should be: 32 dp * 4 = 128 dp, that means threshold size should transfer to pixels by multiply device density. For xxxhdpi devices (density 4), the soft keyboard height threshold should be 128 * 4 = 512 pixels.
Height difference between root view and its visible area:
root view height - status bar height - visible frame height = root view bottom - visible frame bottom, since status bar height equal to the top of root view visible frame.
private final String TAG = "TextEditor";
private TextView mTextEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
mTextEditor = (TextView) findViewById(R.id.text_editor);
mTextEditor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
isKeyboardShown(mTextEditor.getRootView());
}
});
}
private boolean isKeyboardShown(View rootView) {
/* 128dp = 32dp * 4, minimum button height 32dp and generic 4 rows soft keyboard */
final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
/* heightDiff = rootView height - status bar height (r.top) - visible frame height (r.bottom - r.top) */
int heightDiff = rootView.getBottom() - r.bottom;
/* Threshold size: dp to pixels, multiply with display density */
boolean isKeyboardShown = heightDiff > SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD * dm.density;
Log.d(TAG, "isKeyboardShown ? " + isKeyboardShown + ", heightDiff:" + heightDiff + ", density:" + dm.density
+ "root view height:" + rootView.getHeight() + ", rect:" + r);
return isKeyboardShown;
}
I know it's now 2020, but I couldn't see an answer that satisfied the "ignore" part of the question. Turns out, you can tell TSLint to do just that using a directive;
// @ts-ignore
this.x = this.x.filter(x => x.someProp !== false);
Normally this would throw an error, stating that 'someProp does not exist on type'. With the comment, that error goes away.
This will stop any errors being thrown when compiling and should also stop your IDE complaining at you.
it is not possible to pragmatically get the permission... but ill suggest you to put that line of code in try{} catch{} which make your app unfortunately stop... and in catch body make a dialog box which will navigate the user to small tutorial to enable the draw over other apps permission... then on yes button click put this code...
Intent callSettingIntent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(callSettingIntent);
this intent is to directly open the list of draw over other apps to manage permissions and then from here it is one click to the draw over other apps Permissions ... i know this is Not the answer you're looking for... but Im doing this in my apps...
<input type='submit' />
doesn't support HTML inside of it, since it's a single self-closing tag. <button>
, on the other hand, supports HTML, images, etc. inside because it's a tag pair: <button><img src='myimage.gif' /></button>
. <button>
is also more flexible when it comes to CSS styling.
The disadvantage of <button>
is that it's not fully supported by older browsers. IE6/7, for example, don't display it correctly.
Unless you have some specific reason, it's probably best to stick to <input type='submit' />
.
You can always press CTRL-B + SHIFT-D to choose which client you want to detach from the session.
tmux will list all sessions with their current dimension. Then you simply detach from all the smaller sized sessions.
Just awk
, no need combination of tools.
# awk '{for(i=1;i<=NF;i++){if($i~/^th/){print $i}}}' file
the
the
the
this
thoroughly
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:
def addstudent():
print("Student Added.")
then called by writing addstudent()
.
I would recommend using a while
loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked)
, then put the if statements after the while. Or you can do a while
loop and continue
the loop if a valid option is not selected.
Additionally, a dictionary is defined in the following way:
my_dict = {key:definition,...}
Why not use an object1?
var dict = { "a": 1, "b": 2, "c": 3 };
Then you can update it like so
dict.a = 23;
or
dict["a"] = 23;
If you wan't to delete2 a particular key, it's as simple as:
delete dict.a;
1 See Objects vs arrays in Javascript for key/value pairs.
2 See the delete
operator.
sometimes even after clearing border
s.
the reason is that you have images inside the td
, giving the images display:block
solves it.
Below is the way we are going within our developing application.
import java.text.SimpleDateFormat
String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)
println(dateAdded)
The output looks like
Sun Nov 11 09:30:31 GMT 2018
In your example, we could adjust a bit to meet your need. If I were you, I will do:
String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)
I hope this would help you much.
Update:
As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).
const classes = element.className.split(' ').filter(Boolean);
or more modern
const classes = element.classList;
Old:
With all the given answers, you should never forget to user .trim() (or $.trim())
Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2 class3'..
This would turn into ['class1', 'class2','','','', 'class3']..
When you use trim, all multiple spaces get removed..
To get the right ownership, you can set the group setuid bit on the directory with
chmod g+rwxs dirname
This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.
I don't know of a way to force the permissions you want if the user's umask is too strong.
To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.
contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }
Here's a simple script that generally does the trick for me:
SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
FROM sys.dm_exec_requests
WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
In WPF, you use a DispatcherTimer
.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
To expand on Charles Duffy's answer, Nginx uses the daemon off
directive to run in the foreground. If it's inconvenient to put this in the configuration file, we can specify it directly on the command line. This makes it easy to run in debug mode (foreground) and directly switch to running in production mode (background) by changing command line args.
To run in foreground:
nginx -g 'daemon off;'
To run in background:
nginx
Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).
<a class="article" href="link/for/non-js-users.html">
<span style="display: none;">{"id": 1, "title":"Something"}</span>
Text of Link
</a>
// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);
dgg
will delete everything from your current line to the top of the file.
d
is the deletion command, and gg
is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.
Also
dG
will delete all lines at or below the current one
I don't know if I am late in answering your question. After reading your question I came up with a function intersect() that can work on both list and nested list. I used recursion to define this function, it is very intuitive. Hope it is what you are looking for:
def intersect(a, b):
result=[]
for i in b:
if isinstance(i,list):
result.append(intersect(a,i))
else:
if i in a:
result.append(i)
return result
Example:
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> print intersect(c1,c2)
[[13, 32], [7, 13, 28], [1, 6]]
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> print intersect(b1,b2)
[4, 5]
You can just create a new branch and switch onto it. Commit your changes then:
git branch dirty
git checkout dirty
// And your commit follows ...
Alternatively, you can also checkout an existing branch (just git checkout <name>
). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.
You only need to change the access permissions for your WordPress Directory:
chown -R www-data:www-data your-wordpress-directory
Jérôme Petazzoni has a pretty interesting blog post on how to Attach a volume to a container while it is running. This isn't something that's built into Docker out of the box, but possible to accomplish.
As he also points out
This will not work on filesystems which are not based on block devices.
It will only work if /proc/mounts correctly lists the block device node (which, as we saw above, is not necessarily true).
Also, I only tested this on my local environment; I didn’t even try on a cloud instance or anything like that
YMMV
Its my code
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
Unfortunately, for me, setting "Expires" did not always work. The cookie was unaffected.
This code did work for me:
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
where "ASP.NET_SessionId"
is the name of the cookie. This does not really delete the cookie, but overrides it with a blank cookie, which was close enough for me.
For all users of the system via the /etc/wgetrc
or for the user only with the ~/.wgetrc
file:
use_proxy=yes
http_proxy=127.0.0.1:8080
https_proxy=127.0.0.1:8080
or via -e
options placed after the URL:
wget ... -e use_proxy=yes -e http_proxy=127.0.0.1:8080 ...
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
In Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
image = (ImageView) findViewById(R.id.imageButton);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
SimpleDateFormat sdfPic = new SimpleDateFormat(DATE_FORMAT);
currentDateandTime = sdfPic.format(new Date()).replace(" ", "");
File imagesFolder = new File(IMAGE_PATH, currentDateandTime);
imagesFolder.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = IMAGE_NAME + n + IMAGE_FORMAT;
File file = new File(imagesFolder, fname);
outputFileUri = Uri.fromFile(file);
cameraIntent= new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_DATA);
}catch(Exception e) {
e.printStackTrace();
}
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CAMERA_DATA :
final int IMAGE_MAX_SIZE = 300;
try {
// Bitmap bitmap;
File file = null;
FileInputStream fis;
BitmapFactory.Options opts;
int resizeScale;
Bitmap bmp;
file = new File(outputFileUri.getPath());
// This bit determines only the width/height of the
// bitmap
// without loading the contents
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
fis = new FileInputStream(file);
BitmapFactory.decodeStream(fis, null, opts);
fis.close();
// Find the correct scale value. It should be a power of
// 2
resizeScale = 1;
if (opts.outHeight > IMAGE_MAX_SIZE
|| opts.outWidth > IMAGE_MAX_SIZE) {
resizeScale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE/ (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5)));
}
// Load pre-scaled bitmap
opts = new BitmapFactory.Options();
opts.inSampleSize = resizeScale;
fis = new FileInputStream(file);
bmp = BitmapFactory.decodeStream(fis, null, opts);
Bitmap getBitmapSize = BitmapFactory.decodeResource(
getResources(), R.drawable.male);
image.setLayoutParams(new RelativeLayout.LayoutParams(
200,200));//(width,height);
image.setImageBitmap(bmp);
image.setRotation(90);
fis.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
imageByte = baos.toByteArray();
break;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
in layout.xml:
enter code here
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/XXXXXXX"
android:textAppearance="?android:attr/textAppearanceSmall" />
in manifest.xml:
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" />
You need to first transform data1, in your case by calling ToString()
on each element.
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Select(i => i.ToString()).Intersect(data2);
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Intersect(data2.Select(s => int.Parse(s));
Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:
int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
// All data2 strings are int's
}
Easy way to use for create dynamic header and cell in normal table :
<table width="100%" class="table">
<thead>
<tr>
<th ng-repeat="(header, value) in MyRecCollection[0]">{{header}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in MyRecCollection | filter:searchText">
<td ng-repeat="cell in row">{{cell}}</td>
</tr>
</tbody>
</table>
MyApp.controller('dataShow', function ($scope, $http) {
//$scope.gridheader = ['Name','City','Country']
$http.get('http://www.w3schools.com/website/Customers_MYSQL.php').success(function (data) {
$scope.MyRecCollection = data;
})
});
JSON Data :
[{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "Ernst Handel",
"City": "Graz",
"Country": "Austria"
}, {
"Name": "FISSA Fabrica Inter. Salchichas S.A.",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "Galería del gastrónomo",
"City": "Barcelona",
"Country": "Spain"
}, {
"Name": "Island Trading",
"City": "Cowes",
"Country": "UK"
}, {
"Name": "Königlich Essen",
"City": "Brandenburg",
"Country": "Germany"
}, {
"Name": "Laughing Bacchus Wine Cellars",
"City": "Vancouver",
"Country": "Canada"
}, {
"Name": "Magazzini Alimentari Riuniti",
"City": "Bergamo",
"Country": "Italy"
}, {
"Name": "North/South",
"City": "London",
"Country": "UK"
}, {
"Name": "Paris spécialités",
"City": "Paris",
"Country": "France"
}, {
"Name": "Rattlesnake Canyon Grocery",
"City": "Albuquerque",
"Country": "USA"
}, {
"Name": "Simons bistro",
"City": "København",
"Country": "Denmark"
}, {
"Name": "The Big Cheese",
"City": "Portland",
"Country": "USA"
}, {
"Name": "Vaffeljernet",
"City": "Århus",
"Country": "Denmark"
}, {
"Name": "Wolski Zajazd",
"City": "Warszawa",
"Country": "Poland"
}]
All the existing (working) answers have one of two problems:
1. Ignored Indices:
For the most part, when a column being searched has a function called on it (including implicitly, like for CAST
), the optimizer must ignore indices on the column and search through every record. Here's a quick example:
We're dealing with timestamps, and most RDBMSs tend to store this information as an increasing value of some sort, usually a long
or BIGINTEGER
count of milli-/nanoseconds. The current time thus looks/is stored like this:
1402401635000000 -- 2014-06-10 12:00:35.000000 GMT
You don't see the 'Year' value ('2014'
) in there, do you? In fact, there's a fair bit of complicated math to translate back and forth. So if you call any of the extraction/date part functions on the searched column, the server has to perform all that math just to figure out if you can include it in the results. On small tables this isn't an issue, but as the percentage of rows selected decreases this becomes a larger and larger drain. Then in this case, you're doing it a second time for asking about MONTH
... well, you get the picture.
2. Unintended data:
Depending on the particular version of SQL Server, and column datatypes, using BETWEEN
(or similar inclusive upper-bound ranges: <=
) can result in the wrong data being selected. Essentially, you potentially end up including data from midnight of the "next" day, or excluding some portion of the "current" day's records.
What you should be doing:
So we need a way that's safe for our data, and will use indices (if viable). The correct way is then of the form:
WHERE date_created >= @startOfPreviousMonth AND date_created < @startOfCurrentMonth
Given that there's only one month, @startOfPreviousMonth
can be easily substituted for/derived by:
DATEADD(month, -1, @startOCurrentfMonth)
If you need to derive the start-of-current-month in the server, you can do it via the following:
DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
A quick word of explanation here. The initial DATEDIFF(...)
will get the difference between the start of the current era (0001-01-01
- AD, CE, whatever), essentially returning a large integer. This is the count of months to the start of the current month. We then add this number to the start of the era, which is at the start of the given month.
So your full script could/should look similar to the following:
DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
SELECT *
FROM Member
WHERE date_created >= DATEADD(month, -1, @startOfCurrentMonth) -- this was originally misspelled
AND date_created < @startOfCurrentMonth
All date operations are thus only performed once, on one value; the optimizer is free to use indices, and no incorrect data will be included.
My rule is simple. If you are using C++ prefer C++ libraries and not C :)
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search → Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:
Find What = (cat|town)
Filters = *.txt
Directory = enter the path of the directory you want to search in. You can check Follow current doc.
to have the path of the current file to be filled.
Search mode = Regular Expression
Here is a simple solution to minimize changes to your code:
from datetime import datetime
import pytz
start_utc = datetime.utcnow()
print ("Time (UTC): %s" % start_utc.strftime("%d-%m-%Y %H:%M:%S"))
Time (UTC): 09-01-2021 03:49:03
tz = pytz.timezone('Africa/Cairo')
start_tz = datetime.now().astimezone(tz)
print ("Time (RSA): %s" % start_tz.strftime("%d-%m-%Y %H:%M:%S"))
Time (RSA): 09-01-2021 05:49:03
In a nutshell, sys.argv
is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0]
, and the second element (first argument, if there is one) is sys.argv[1]
, etc.
The test len(sys.argv) >= 2
simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.
You can use
yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))
And In Swift 3.0
yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)
I was finally able to resolve the "Excel connection issue" in my case it was not a 64 bit issue like some of them had encounterd, I noticed the package worked fine when i didnt enable the package configuration, but i wanted my package to run with the configuration file, digging further into it i noticed i had selected all the properties that were available, I unchecked all and checked only the ones that I needed to store in the package configuration file. and ta dha it works :)
Um, lots.
There are several parameters here. The specific VM, plus there are usually run-time parameters on the VM as well. That's somewhat driven by the operating system: what support does the underlying OS have for threads and what limitations does it put on them? If the VM actually uses OS-level threads at all, the good old red thread/green thread thing.
What "support" means is another question. If you write a Java program that is just something like
class DieLikeADog {
public static void main(String[] argv){
for(;;){
new Thread(new SomeRunaable).start();
}
}
}
(and don't complain about little syntax details, I'm on my first cup of coffee) then you should certainly expect to get hundreds or thousands of threads running. But creating a Thread is relatively expensive, and scheduler overhead can get intense; it's unclear that you could have those threads do anything useful.
Okay, couldn't resist. Here's my little test program, with a couple embellishments:
public class DieLikeADog {
private static Object s = new Object();
private static int count = 0;
public static void main(String[] argv){
for(;;){
new Thread(new Runnable(){
public void run(){
synchronized(s){
count += 1;
System.err.println("New thread #"+count);
}
for(;;){
try {
Thread.sleep(1000);
} catch (Exception e){
System.err.println(e);
}
}
}
}).start();
}
}
}
On OS/X 10.5.6 on Intel, and Java 6 5 (see comments), here's what I got
New thread #2547 New thread #2548 New thread #2549 Can't create thread: 5 New thread #2550 Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:592) at DieLikeADog.main(DieLikeADog.java:6)
I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values = 0:
unsigned int x[] -> int x[]
than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.
Here's a bad solution to a bad question, but one that literally meets the brief:
p {
width : 12ex;
}
p:before {
content: ".";
float: right;
padding-left: 6ex;
visibility: hidden;
}