You may need to know the status and update a ProgressBar during the file download or use credentials before making the request.
Here it is, an example that covers these options. Lambda notation and String interpolation has been used:
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
I just used the following which was quite simple. First open a console then cd to where you've downloaded your file like some-package.whl and use
pip install some-package.whl
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. If pip is not installed, this page can help: How do I install pip on Windows?
Note: for clarification
If you copy the *.whl
file to your local drive (ex. C:\some-dir\some-file.whl) use the following command line parameters --
pip install C:/some-dir/some-file.whl
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose
This works for me in Java 1.5 - I stripped out specific exceptions for readability.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}
What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.
so something
is not a valid JSON but "something"
is.
A valid JSON is -
JSON = null
/* boolean literal */
or true or false
/* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
or JSONNumber
/* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
or JSONString
/* Property names must be double-quoted strings; trailing commas are forbidden. */
or JSONObject
or JSONArray
Examples -
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.parse("'foo'"); // error since string should be wrapped by double quotes
You may want to look JSON.
There is no best way, it depends on your use case.
Person
(you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.Update: As requested examples for the third way.
Dependent properties:
The following does not work as this
does not refer to book
. There is no way to initialize a property with values of other properties in a object literal:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
instead, you could do:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
Dynamic property names:
If the property name is stored in some variable or created through some expression, then you have to use bracket notation:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
With the Multiple SCMs Plugin:
create a different repository entry for each repository you need to checkout (main project or dependancy project.
for each project, in the "advanced" menu (the second "advanced" menu, there are two buttons labeled "advanced" for each repository), find the "Local subdirectory for repo (optional)" textfield. You can specify there the subdirectory in the "workspace" directory where you want to copy the project to. You could map the filesystem of my development computer.
The "second advanced menu" doesn't exist anymore, instead what needs to be done is use the "Add" button (on the "Additional Behaviours" section), and choose "Check out to a sub-directory"
Hope that helps.
Historically, the first extensions used for C++ were .c
and .h
, exactly like for C. This caused practical problems, especially the .c
which didn't allow build systems to easily differentiate C++ and C files.
Unix, on which C++ has been developed, has case sensitive file systems. So some used .C
for C++ files. Other used .c++
, .cc
and .cxx
. .C
and .c++
have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use .cpp
, and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows.
Headers have used the corresponding .H
, .h++
, .hh
, .hxx
and .hpp
. But unlike the main files, .h
remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension at all.
Additionally, some are using .ii
, .ixx
, .ipp
, .inl
for headers providing inline definitions and .txx
, .tpp
and .tpl
for template definitions. Those are either included in the headers providing the definition, or manually in the contexts where they are needed.
Compilers and tools usually don't care about what extensions are used, but using an extension that they associate with C++ prevents the need to track out how to configure them so they correctly recognize the language used.
2017 edit: the experimental module support of Visual Studio recognize .ixx
as a default extension for module interfaces, clang++ is recognizing .c++m
, .cppm
and .cxxm
for the same purpose.
DateFormat.format
only works on Date
values.
You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:
// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);
EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.
Try removing the .
before the .bmp
(it isn't matching BMP
as expected). As you can see from the error, the save_handler
is upper-casing the format
you provided and then looking for a match in SAVE
. However the corresponding key in that object is BMP
(instead of .BMP
).
I don't know a great deal about PIL
, but from some quick searching around it seems that it is a problem with the mode
of the image. Changing the definition of j
to:
j = Image.fromarray(b, mode='RGB')
Seemed to work for me (however note that I have very little knowledge of PIL
, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode
, I used this page - hopefully one of the choices there will work for you.
std::cout << '\7';
By default, Java only supports AES 128 bit (16 bytes) key sizes for encryption. If you do not need more than default supported, you can trim the key to the proper size before using Cipher
. See javadoc for default supported keys.
This is an example of generating a key that would work with any JVM version without modifying the policy files. Use at your own discretion.
Here is a good article on whether key 128 to 256 key sizes matter on AgileBits Blog
SecretKeySpec getKey() {
final pass = "47e7717f0f37ee72cb226278279aebef".getBytes("UTF-8");
final sha = MessageDigest.getInstance("SHA-256");
def key = sha.digest(pass);
// use only first 128 bit (16 bytes). By default Java only supports AES 128 bit key sizes for encryption.
// Updated jvm policies are required for 256 bit.
key = Arrays.copyOf(key, 16);
return new SecretKeySpec(key, AES);
}
the solution that does work is this:
$str = preg_replace('/\\\"/',"\"", $str);
However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).
So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe"
in your DB, php will bring this back as
My name is \\"Joe\\"
.
This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:
$str = preg_replace('/\\\\\"/',"\"", $str);
yeah... it's ugly... but it works.
You're then left with something that vaguely resembles actual JSON.
You are working way too hard. Your entire script should be:
if mkdir "$lockdir" 2> /dev/null; then
echo lock acquired
else
echo could not acquire lock >&2
fi
but even that is probably too verbose. I would code it:
mkdir "$lockdir" || exit 1
but the resulting error message is a bit obscure.
Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. The following works:
(
echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t
For troubleshooting msmtp, which is compatible with sendmail
, see:
i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..
Use getJSON
$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
});
Detail look here http://api.jquery.com/jQuery.getJSON/
... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...
It ought to work.
In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.
Here is what works well for me:
#!/bin/sh
set -m # Enable Job Control
for i in `seq 30`; do # start 30 jobs in parallel
sleep 3 &
done
# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done
The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.
notepad filename.extension will open notepad editor
How are you running the application? Are you just hitting the website or are you building and running from within Visual Studio? If you are building and running you may want to tell it to use the local IIS web server. This would make sure it is using the App Pool you have set up to run with v4.0/integrated.
I am guessing that it is using the Visual Studio Development Server when running. This server is probably trying to run with the 2.0 framework. This then causes your error to be thrown.
Edit: To note, I normally just build my website application and then I attach to process w3wp when I want to debug. I do not use the publishing tool. Of course this means my local working directory is within the web root.
If you get an exception for : Invalid column type
Please use getNamedParameterJdbcTemplate()
instead of getJdbcTemplate()
List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
getRowMapper());
Note that the second two arguments are swapped around.
This could work but I don't know if it's convenient for your case:
@ViewChildren('contentPlaceholder', {read: ViewContainerRef}) viewContainerRefs: QueryList;
ngAfterViewInit() {
this.viewContainerRefs.changes.subscribe(item => {
if(this.viewContainerRefs.toArray().length) {
// shown
}
})
}
Remove removeProperty
var el=document.getElementById("id");
el.style.removeProperty('display')
console.log("display removed"+el.style["display"])
console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
That's the best I guess:
for (int[] row : matrix){
System.out.println(Arrays.toString(row));
}
document.forms
will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.
var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
if(form.id == "wanted_id") {
form = document.forms[i];
}
}
Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name
var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);
This blog explains your problem neatly Async Best Practices.
The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).
Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).
You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.
This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...
Have you tried using?:
left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */
Not sure if it'll work, but it's worth a try...
Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...
Here's an example I found on this blog.
$cn2 = new-object system.data.SqlClient.SQLConnection("Data Source=machine1;Integrated Security=SSPI;Initial Catalog=master");
$cmd = new-object system.data.sqlclient.sqlcommand("dbcc freeproccache", $cn2);
$cn2.Open();
if ($cmd.ExecuteNonQuery() -ne -1)
{
echo "Failed";
}
$cn2.Close();
Presumably you could substitute a different TSQL statement where it says dbcc freeproccache
.
Please try following regex for remove double quotes from string .
$string = "I am here";
$string =~ tr/"//d;
print $string;
exit();
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
SELECT DISTINCT a.StoreID
FROM tableName a
LEFT JOIN tableName b
ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE b.StoreID IS NULL
OUTPUT
+---------+
¦ STOREID ¦
¦---------¦
¦ 3 ¦
+---------+
The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.
SELECT * FROM Call WHERE
NOT EXISTS (SELECT 'x' FROM Phone_book where
Phone_book.phone_number = Call.phone_number)
The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True
block preceding the line root.mainloop()
.
GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.
from tkinter import *
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
t = Entry(root, textvariable = var)
t.pack()
root.mainloop() # the window is now displayed
I like the following reference: tkinter 8.5 reference: a GUI for Python
Here is a working example of what you were trying to do:
from tkinter import *
from time import sleep
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
for i in range(6):
sleep(1) # Need this to slow the changes down
var.set('goodbye' if i%2 else 'hello')
root.update_idletasks()
root.update
Enter event loop until all pending events have been processed by Tcl
.
If this is for debugging purposes, I would advise you use a JavaScript debugger such as Firebug. It will let you view the entire contents of arrays and much more, including modifying array entries and stepping through code.
This is how simply I sort from previous examples:
if my array is items
:
0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}
I thought simply calling items.sort()
would sort it it, but there was two problems:
1. Was sorting them strings
2. Was sorting them first key
This is how I modified the sort function:
for(amount in items){
if(item.hasOwnProperty(amount)){
i.sort((a, b) => a.amount - b.amount);
}
}
Do you mean that the date range of the selected rows should not lie fully within the specified date range? In which case:
select *
from test_table
where start_date < date '2009-12-15'
or end_date > date '2010-01-02';
(Syntax above is for Oracle, yours may differ slightly).
break
will exit the loop completely, continue
will just skip the current iteration.
For example:
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
The break will cause the loop to exit on the first iteration - DoSomeThingWith
will never be executed. This here:
for (int i = 0; i < 10; i++) {
if(i == 0) {
continue;
}
DoSomeThingWith(i);
}
Will not execute DoSomeThingWith
for i = 0
, but the loop will continue and DoSomeThingWith
will be executed for i = 1
to i = 9
.
Since the true Binding URL for the web service is located in the file, you could do these simple steps from your local machine:
1) Save the file to your local computer for example:
C:\Documents and Settings\[user]\Desktop\Webservice1.asmx
2) In Visual Studio Right Click on your project > Choose Add Web Reference, A dialog will open.
3) In the URL Box Copy the local file location above C:\Documents and Settings[user]\Desktop\Webservice1.asmx, Click Next
4) Now you will see the functions appear, choose your name for the reference, Click add reference
5) You are done! you can start using it as a namespace in your application don't worry that you used a local file, because anyway the true URL for the service is located in the file at the Binding section
public void onClick1(View v) {
DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
dialog.show();
}
public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}
Have your Activity
implement OnFocusChangeListener()
if you want a factorized use of this interface,
example:
public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{
In your OnCreate
you can add a listener for example:
editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);
then android studio will prompt you to add the method from the interface, accept it... it will be like:
@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}
and as you've got a factorized code, you'll just have to do that:
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
editTextResearch.setText("");
editTextMyWords.setText("");
editTextPhone.setText("");
}
if (!hasFocus){
editTextResearch.setText("BlaBlaBla");
editTextMyWords.setText(" One Two Tree!");
editTextPhone.setText("\"your phone here:\"");
}
}
anything you code in the !hasFocus
is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!
It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.
Based on the page listed above, the default sizes look something like this:
IE7 IE8 FF2 FF3 Opera Safari 3.1
H1 24pt 2em 32px 32px 32px 32px
H2 18pt 1.5em 24px 24px 24px 24px
H3 13.55pt 1.17em 18.7333px 18.7167px 18px 19px
H4 n/a n/a n/a n/a n/a n/a
H5 10pt 0.83em 13.2667px 13.2833px 13px 13px
H6 7.55pt 0.67em 10.7333px 10.7167px 10px 11px
Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:
h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }
Hope this information is helpful.
The listed answers won't work if the results of the AJAX form submit affects the HTML outside the scope of the modal before the modal finishes closing. In my case, the result was a grayed out (fade) screen where I could see the page update, but could not interact with any of the page elements.
My solution:
$(document).on("click", "#send-email-submit-button", function(e){
$('#send-new-email-modal').modal('hide')
});
$(document).on("submit", "#send-email-form", function(e){
e.preventDefault();
var querystring = $(this).serialize();
$.ajax({
type: "POST",
url: "sendEmailMessage",
data : querystring,
success : function(response) {
$('#send-new-email-modal').on('hidden.bs.modal', function () {
$('#contacts-render-target').html(response);
}
});
return false;
});
Note: My modal form was inside a parent div that was already rendered via AJAX, thus the need to anchor the event listener to document.
I created my own jQuery plugin for this task, you can try it out here:
http://jsfiddle.net/Sk8erPeter/8NF4r/
You can create character counters on-the-fly (and also remaining character counters), you can define whether you want to chop text, you can define the suffix texts and you can also define a short format and its separator.
Here's an example usage:
$(document).ready(function () {
$('#first_textfield').characterCounter();
$('#second_textfield').characterCounter({
maximumCharacters: 20,
chopText: true
});
$('#third_textfield').characterCounter({
maximumCharacters: 20,
shortFormat: true,
shortFormatSeparator: " / ",
positionBefore: true,
chopText: true
});
$('#fourth_textfield').characterCounter({
maximumCharacters: 20,
characterCounterNeeded: true,
charactersRemainingNeeded: true,
chopText: false
});
$('#first_textarea').characterCounter({
maximumCharacters: 50,
characterCounterNeeded: true,
charactersRemainingNeeded: false,
chopText: true
});
$('#second_textarea').characterCounter({
maximumCharacters: 25
});
});
Here's the code of the plugin:
/**
* Character counter and limiter plugin for textfield and textarea form elements
* @author Sk8erPeter
*/
(function ($) {
$.fn.characterCounter = function (params) {
// merge default and user parameters
params = $.extend({
// define maximum characters
maximumCharacters: 1000,
// create typed character counter DOM element on the fly
characterCounterNeeded: true,
// create remaining character counter DOM element on the fly
charactersRemainingNeeded: true,
// chop text to the maximum characters
chopText: false,
// place character counter before input or textarea element
positionBefore: false,
// class for limit excess
limitExceededClass: "character-counter-limit-exceeded",
// suffix text for typed characters
charactersTypedSuffix: " characters typed",
// suffix text for remaining characters
charactersRemainingSuffixText: " characters left",
// whether to use the short format (e.g. 123/1000)
shortFormat: false,
// separator for the short format
shortFormatSeparator: "/"
}, params);
// traverse all nodes
this.each(function () {
var $this = $(this),
$pluginElementsWrapper,
$characterCounterSpan,
$charactersRemainingSpan;
// return if the given element is not a textfield or textarea
if (!$this.is("input[type=text]") && !$this.is("textarea")) {
return this;
}
// create main parent div
if (params.characterCounterNeeded || params.charactersRemainingNeeded) {
// create the character counter element wrapper
$pluginElementsWrapper = $('<div>', {
'class': 'character-counter-main-wrapper'
});
if (params.positionBefore) {
$pluginElementsWrapper.insertBefore($this);
} else {
$pluginElementsWrapper.insertAfter($this);
}
}
if (params.characterCounterNeeded) {
$characterCounterSpan = $('<span>', {
'class': 'counter character-counter',
'text': 0
});
if (params.shortFormat) {
$characterCounterSpan.appendTo($pluginElementsWrapper);
var $shortFormatSeparatorSpan = $('<span>', {
'html': params.shortFormatSeparator
}).appendTo($pluginElementsWrapper);
} else {
// create the character counter element wrapper
var $characterCounterWrapper = $('<div>', {
'class': 'character-counter-wrapper',
'html': params.charactersTypedSuffix
});
$characterCounterWrapper.prepend($characterCounterSpan);
$characterCounterWrapper.appendTo($pluginElementsWrapper);
}
}
if (params.charactersRemainingNeeded) {
$charactersRemainingSpan = $('<span>', {
'class': 'counter characters-remaining',
'text': params.maximumCharacters
});
if (params.shortFormat) {
$charactersRemainingSpan.appendTo($pluginElementsWrapper);
} else {
// create the character counter element wrapper
var $charactersRemainingWrapper = $('<div>', {
'class': 'characters-remaining-wrapper',
'html': params.charactersRemainingSuffixText
});
$charactersRemainingWrapper.prepend($charactersRemainingSpan);
$charactersRemainingWrapper.appendTo($pluginElementsWrapper);
}
}
$this.keyup(function () {
var typedText = $this.val();
var textLength = typedText.length;
var charactersRemaining = params.maximumCharacters - textLength;
// chop the text to the desired length
if (charactersRemaining < 0 && params.chopText) {
$this.val(typedText.substr(0, params.maximumCharacters));
charactersRemaining = 0;
textLength = params.maximumCharacters;
}
if (params.characterCounterNeeded) {
$characterCounterSpan.text(textLength);
}
if (params.charactersRemainingNeeded) {
$charactersRemainingSpan.text(charactersRemaining);
if (charactersRemaining <= 0) {
if (!$charactersRemainingSpan.hasClass(params.limitExceededClass)) {
$charactersRemainingSpan.addClass(params.limitExceededClass);
}
} else {
$charactersRemainingSpan.removeClass(params.limitExceededClass);
}
}
});
});
// allow jQuery chaining
return this;
};
})(jQuery);
When I was facing this issue I used to install OpenCV in pycharm installed package panel where we can find under the settings tab. Search "OpenCV-python" and install it in the installed package panel of right interpreter.
There is an issue with downloading npm dependencies due to network which you have. try to download the npm dependencies in open network . you won't get any issue. i am also faced this similar issue and resolved finally.
use below commands: npm install (it will download all depedencies) npm start to start the angular application
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
The accepted answer in Swift 3:
let screenSize: CGRect = UIScreen.main.bounds
image.frame = CGRect(x: 0, y: 0, width: 50, height: screenSize.height * 0.2)
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
Or a 1-liner:
perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself
long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization
long start2 = System.nanoTime();
myCall();
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;
System.out.println(diff + " ns");
By the way, you will measure different values for the same call due to
CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');
Explanation on practice. If you try to save your object, e.g.:
Set<Folder> folders = message.getFolders();
folders.remove(inputFolder);
folders.add(trashFolder);
message.setFiles(folders);
MESSAGESDAO.getMessageDAO().save(message);
you don't need to set updated object to a parent object:
message.setFiles(folders);
Simple save your parent object like:
Set<Folder> folders = message.getFolders();
folders.remove(inputFolder);
folders.add(trashFolder);
// Not set updated object here
MESSAGESDAO.getMessageDAO().save(message);
Find end position of file:
f = open("file.txt","r")
f.seek(0,2) #Jumps to the end
f.tell() #Give you the end location (characters from start)
f.seek(0) #Jump to the beginning of the file again
Then you can to:
if line == '' and f.tell() == endLocation:
break
You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class
I did it in a simple way:
<a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>
It'll open runningrss in a new window and virtual-doctor in same window.
As of May 2018, it seems that a workspace in Visual Studio Code allows you to have quick access to different but related projects. All without having to open a different folder.
And you can have multiple workspaces too. See references here and you will get the full picture of it:
df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1
new gi ptt
0 0 232 342
1 1 66 56
2 2 34 662
3 3 43 123
ALTER DATABASE MyDatabase SET RECOVERY SIMPLE
GO
DBCC SHRINKFILE (MyDatabase_Log, 5)
GO
ALTER DATABASE MyDatabase SET RECOVERY FULL
GO
If you must work with raw arrays and not ArrayList
then Arrays
has what you need. If you look at the source code, these are the absolutely best ways to get a copy of an array. They do have a good bit of defensive programming because the System.arraycopy()
method throws lots of unchecked exceptions if you feed it illogical parameters.
You can use either Arrays.copyOf()
which will copy from the first to Nth
element to the new shorter array.
public static <T> T[] copyOf(T[] original, int newLength)
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
2770
2771 public static <T,U> T[] More ...copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
2772 T[] copy = ((Object)newType == (Object)Object[].class)
2773 ? (T[]) new Object[newLength]
2774 : (T[]) Array.newInstance(newType.getComponentType(), newLength);
2775 System.arraycopy(original, 0, copy, 0,
2776 Math.min(original.length, newLength));
2777 return copy;
2778 }
or Arrays.copyOfRange()
will also do the trick:
public static <T> T[] copyOfRange(T[] original, int from, int to)
Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. The resulting array is of exactly the same class as the original array.
3035 public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3036 int newLength = to - from;
3037 if (newLength < 0)
3038 throw new IllegalArgumentException(from + " > " + to);
3039 T[] copy = ((Object)newType == (Object)Object[].class)
3040 ? (T[]) new Object[newLength]
3041 : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3042 System.arraycopy(original, from, copy, 0,
3043 Math.min(original.length - from, newLength));
3044 return copy;
3045 }
As you can see, both of these are just wrapper functions over System.arraycopy
with defensive logic that what you are trying to do is valid.
System.arraycopy
is the absolute fastest way to copy arrays.
You're interested in the collation. You could build something based on this snippet:
SELECT DATABASEPROPERTYEX('master', 'Collation');
Update
Based on your edit — If @test
and @TEST
can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL
, because NULL = NULL
returns `false.
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
I faced a similar situation:
I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.
However, when reading the response using GetResponseStream()
, got the error:
Stream not readable
So, this code worked for me:
try
{
response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
var webException = exception.InnerException as WebException;
var rawResponse = string.Empty;
var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
using (var reader = new StreamReader(brandNewStream))
rawResponse = reader.ReadToEnd();
}
EDIT: As pointed out in recent comments, this solution may BREAK your system.
You most likely don't want to remove python3.
Please refer to the other answers for possible solutions.
Outdated answer (not recommended)
sudo apt-get remove 'python3.*'
I made a simple function, in which you give the key, the new value and the dictionary as input, and it recursively updates it with the value:
def update(key,value,dictionary):
if key in dictionary.keys():
dictionary[key] = value
return
dic_aux = []
for val_aux in dictionary.values():
if isinstance(val_aux,dict):
dic_aux.append(val_aux)
for i in dic_aux:
update(key,value,i)
for [key2,val_aux2] in dictionary.items():
if isinstance(val_aux2,dict):
dictionary[key2] = val_aux2
dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}}}
update('levelB',10,dictionary1)
print(dictionary1)
#output: {'level1': {'level2': {'levelA': 0, 'levelB': 10}}}
Hope it answers.
As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec
needs to understand it. If you don't want to convert the key using openssl pkcs8
or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:
static final Base64.Decoder DECODER = Base64.getMimeDecoder();
private static byte[] buildPKCS8Key(File privateKey) throws IOException {
final String s = new String(Files.readAllBytes(privateKey.toPath()));
if (s.contains("--BEGIN PRIVATE KEY--")) {
return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
}
if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
throw new RuntimeException("Invalid cert format: "+ s);
}
final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
final byte[] result = new byte[innerKey.length + 26];
System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
System.arraycopy(innerKey, 0, result, 26, innerKey.length);
return result;
}
Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec
constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));
Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.
Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).
If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
HashMap<String, MyOwnObject> map = mapper.readValue(new StringReader(hashTable.toString()), mapType);
Instead of having the android:actionMenuTextAppearance
item under your action bar style, move it under your app theme.
One requirement for remote debugging is that the windows account used to run SSMS be part of the sysadmin role. See this MSDN link: http://msdn.microsoft.com/en-us/library/cc646024%28v=sql.105%29.aspx
You can also return all selected checkboxes value in comma separated string. This will also make it easier for you when you send it as a parameter to SQL
Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string
And here is the javascript
function showSelectedValues()
{
alert($("input[name=chkboxName]:checked").map(function () {
return this.value;
}).get().join(","));
}
Here is the HTML sample
<html>
<head>
</head>
<body>
<div>
<input name="chkboxName" type="checkbox" value="one_name" checked>
<input name="chkboxName" type="checkbox" value="one_name1">
<input name="chkboxName" type="checkbox" value="one_name2">
</div>
</body>
</html>
For the special case of existing Windows Forms applications:
There is a way - though I don't know how well it works.
It goes like this:
Take the Windows Forms implementation from Mono.
Port it to .NET Core or NetStandard.
Recompile your Windows Forms applications against the new System.Windows.Forms.
Fix anything that may be broken by .NET Core.
Pray that mono implements the parts you need flawlessly.
(If it doesn't, you can always stop praying, and send the Mono project a pull request with your fix/patch/feature.)
Here's my CoreFX Windows Forms repository:
https://github.com/ststeiger/System.CoreFX.Forms
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
A nice way to achieve this "if you have an office 365 account" is to use Office 365 outlook connector integrated with Azure Logic App,
Hope this helps someone!
Using a range loop feels the most natural to me:
for (var child of node.childNodes) {
child.remove();
}
According to my measurements in Chrome and Firefox, it is about 1.3x slower. In normal circumstances, this will perhaps not matter.
Try this JavaScript code:
function printout() {
var newWindow = window.open();
newWindow.document.write(document.getElementById("output").innerHTML);
newWindow.print();
}
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.
You can Start the android Service by this command.
adb shell am startservice -n packageName/.ServiceClass
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
Happen to have a task on pivot. Below works for me as tested just now on 11g:
select * from
(
select ID, COUNTRY_NAME, TOTAL_COUNT from ONE_TABLE
)
pivot(
SUM(TOTAL_COUNT) for COUNTRY_NAME in (
'Canada', 'USA', 'Mexico'
)
);
theharshest answered the question but here is another way to do the same thing. Also, In your example you have NAME in caps and in your code you have name in lowercase.
s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)
attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}
print attributes_dictionary['class'][0]
# prints: question
print soup.find('div').get_text()
# prints: Hello World
If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.
For those who come from the Python world, JSX Spread Attributes are equivalent to
Unpacking Argument Lists (the Python **
-operator).
I'm aware this is a JSX question, but working with analogies sometimes helps to get it faster.
I would think it could still be quite RESTful to have query arguments that identify the resource on the URL while keeping the content payload confined to the POST body. This would seem to separate the considerations of "What am I sending?" versus "Who am I sending it to?".
You can create the ordered dict from old dict in one line:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())
The default sorting key is by dictionary key, so the new ordered_dict
is sorted by old dict's keys.
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
to create a compressed archive you can use the utility MAKECAB.EXE
Just set minDate: 0
Here is my script:
$("#valid_from")
.datepicker({
minDate: 0,
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
$(document).ready(function(){
$('#TextBoxId').keypress(function(e){
if(e.keyCode==13)
$('#linkadd').click();
});
});
first of all check your internet its connect!
second is turn on WP_DEBUG and write this codes in wp-config.php
define('WP_DEBUG',true);
error_reporting('E_ALL');
ini_set('display_errors',1);
third is rename themes and plugins folder that in wp-content folder to other name sush as
pluginss , themess
S F my english!
Target build x64 Target Server Hosting IIS 64 Bit
If the application build is targeting 64-Bit OS then on the 64-Bit server hosting the IIS,Set the enable 32 bit application on the app pool running the website/web application to false.
In my case, all modules were correctly set up (https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension is a good starter) & I had the redirection working for a base url, let's say /mysite/
but I got the errors for any child ULR, let's say /mysite/login/
http://reverse-proxy.dns.com/mysite/
was properly redirected to the remote servers while http://reverse-proxy.dns.com/mysite/login/
failed at the Apache2 reverse proxying with OP's error message.
The issue was the ending /
character in the proxypass directive "/mysite/". Working configuration for child URL is :
<Proxy balancer://mysite_cluster>
BalancerMember http://192.x.x.10:8080/mysite
BalancerMember http://192.x.x.11:8080/mysite
</Proxy>
<VirtualHost *:80>
[...]
ProxyRequests Off
ProxyPreserveHost On
ProxyPass "/mysite" "balancer://mysite_cluster"
ProxyPassReverse "/mysite" "balancer://mysite_cluster"
</VirtualHost>
Trailing /
truly are tricky.
How about:
if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}
To get the first match, use #find()
. After that, you can use #group(1)
to refer to this first match, and replace all matches by the first maches value multiplied by 3.
And in case you want to replace each match with that match's value multiplied by 3:
Pattern p = Pattern.compile("(\\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());
You may want to look through Matcher
's documentation, where this and a lot more stuff is covered in detail.
Or try this ;)
try {
this.setContentPane(
new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};
If you haven't pushed that change yet, git reset --hard HEAD^
Otherwise, reverting the revert is perfectly fine.
Another way is to git checkout HEAD^^ -- .
and then git add -A && git commit
.
You don't need the CELL() part of your formulas:
=INDIRECT(ADDRESS(B1,B2))
or
=OFFSET($A$1, B1-1,B2-1)
will both work. Note that both INDIRECT
and OFFSET
are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.
jars use zip compression so you can use any unzip utility.
Example:
$ unzip myJar.jar -d ./directoryToExtractTo
Late, but to be completed with options here: A handy tool to install any apk via gui to a running emulator is: http://apkinstaller.com
This can directly connect to a running instance via adb and can successfully install any kind of apk packages.
Maybe this is also helpful for other people. ;)
The Cause
Lion comes with a version of postgres already installed and uses those binaries by default. In general you can get around this by using the full path to the homebrew postgres binaries but there may be still issues with other programs.
The Solution
curl http://nextmarvel.net/blog/downloads/fixBrewLionPostgres.sh | sh
Via
http://nextmarvel.net/blog/2011/09/brew-install-postgresql-on-os-x-lion/
Looking my projects:
If you're using SQL Server, you can set the value of bit fields with 0 and 1
or
'true' and 'false'
(yes, using strings)
...your_bit_field='false'... => equivalent to 0
Get the hash code of last commit.
git log
git revert <hash_code_from_git_log>
git push
check out in the GHR. you might get what ever you need, hope you this is useful
check this code from MainActivity
// Check location permission is granted - if it is, start
// the service, otherwise request the permission
fun checkOrAskLocationPermission(callback: () -> Unit) {
// Check GPS is enabled
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show()
buildAlertMessageNoGps(this)
return
}
// Check location permission is granted - if it is, start
// the service, otherwise request the permission
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
if (permission == PackageManager.PERMISSION_GRANTED) {
callback.invoke()
} else {
// callback will be inside the activity's onRequestPermissionsResult(
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSIONS_REQUEST
)
}
}
plus
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSIONS_REQUEST) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
// Permission ok. Do work.
}
}
}
plus
fun buildAlertMessageNoGps(context: Context) {
val builder = AlertDialog.Builder(context);
builder.setMessage("Your GPS is disabled. Do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes") { _, _ -> context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
.setNegativeButton("No") { dialog, _ -> dialog.cancel(); }
val alert = builder.create();
alert.show();
}
usage
checkOrAskLocationPermission() {
// Permission ok. Do work.
}
I have just found this site – http://unused-css.com/
Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.
Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.
The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:
Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.
Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.
Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.
Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.
Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.
Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.
UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.
CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.
Jeremy Keith (@adactio) has a good solution for this on his blog Orientation and scale
Keep the Markup scalable by not setting a maximum-scale in markup.
<meta name="viewport" content="width=device-width, initial-scale=1">
Then disable scalability with javascript on load until gesturestart when you allow scalability again with this script:
if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
var viewportmeta = document.querySelector('meta[name="viewport"]');
if (viewportmeta) {
viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0';
document.body.addEventListener('gesturestart', function () {
viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
}, false);
}
}
Update 22-12-2014:
On an iPad 1 this doesnt work, it fails on the eventlistener. I've found that removing .body
fixes that:
document.addEventListener('gesturestart', function() { /* */ });
Did you supply your select-element with an id?
<select id='dropDownId'> ...
Your first statement should work!
Have look at WebLookAndFeel at https://github.com/mgarin/weblaf/
WebTextField txtName = new com.alee.laf.text.WebTextField();
txtName.setHideInputPromptOnFocus(false);
txtName.setInputPrompt("Name");
txtName.setInputPromptFont(new java.awt.Font("Ubuntu", 0, 18));
txtName.setInputPromptForeground(new java.awt.Color(102, 102, 102));
txtName.setInputPromptPosition(0);
Use load
instead of ready
:
$(document).load(function () {
// code here
});
Update
You need to use .on()
since jQuery 1.8. (http://api.jquery.com/on/)
$(window).on('load', function() {
// code here
});
From this answer:
According to http://blog.jquery.com/2016/06/09/jquery-3-0-final-released/:
Removed deprecated event aliases
.load
,.unload
, and.error
, deprecated since jQuery 1.8, are no more. Use.on()
to register listeners.
If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :
FDOPEN(P)
NAME
fdopen - associate a stream with a file descriptor
SYNOPSIS
#include <stdio.h>
FILE *fdopen(int fildes, const char *mode);
You can use useHistory
hook since react-router v5.1.0.
The
useHistory
hook gives you access to the history instance that you may use to navigate.
import React from 'react'
import { useHistory } from 'react-router-dom'
export default function SomeComponent() {
const { push } = useHistory()
...
<button
type="button"
onClick={() => push('/some-link')}
>
Some link
</button>
...
}
In C99 the length modifier for long double
seems to be L
and not l
. man fprintf
(or equivalent for windows) should tell you for your particular platform.
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton
. The second line can be modified to get the value of as many cells as you wish.
Here is my solution:
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();
String dt = Date.Now.ToString("yyyy-MM-dd");
Now you got this for dt, 2010-09-09
You can use pseudo element to get the effect you want like I did in that Fiddle.
CSS:
.title a {
display: block;
width: 340px;
height: 338px;
color: black;
position: relative;
}
.title a:after {
background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
content: "";
opacity: 0;
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0;
/* TRANSISITION */
transition: opacity 1s ease-in-out;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{
opacity: 1;
}
HTML:
<div class="title">
<a href="#">HYPERLINK</a>
</div>
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
The above will only allow strings consisting entirely of characters on the ranges a-z
, A-Z
, 0-9
, plus the hyphen an space characters. A string containing any other character will cause the alert
.
I think you might be looking for an "anchor" given the example you have.
<a href="#jump">This link will jump to the anchor named jump</a>
<a name="jump">This is where the link will jump to</a>
The focus jQuery method does something different from what you're trying to achieve.
You can use FormData API https://developer.mozilla.org/en-US/docs/Web/API/FormData
var data = new FormData;
data.append('from', from);
data.append('to', to);
$http({
url: '/path',
method: 'POST',
data: data,
transformRequest: false,
headers: { 'Content-Type': undefined }
})
This solution from http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
I know it's coming late but for those people who want to implement it purely using the JavaScript
, here's how you can do it:
tr
which is clicked.tr
DOM element.tr
parent node.HTML:
<table>
<tr>
<td>
<button id="0" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="1" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="2" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
In JavaScript:
function addRow() {
var evt = event.srcElement.id;
var btn_clicked = document.getElementById(evt);
var tr_referred = btn_clicked.parentNode.parentNode;
var td = document.createElement('td');
td.innerHTML = 'abc';
var tr = document.createElement('tr');
tr.appendChild(td);
tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
return tr;
}
This will add the new table row exactly below the row on which the button is clicked.
I did this way: Create a XML file, called Colors in res/values folder.
My Colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="vermelho_debito">#cc0000</color>
<color name="azul_credito">#4c4cff</color>
<color name="preto_bloqueado">#000000</color>
<color name="verde_claro_fundo_lista">#CFDBC5</color>
<color name="branco">#ffffff</color>
<color name="amarelo_corrige">#cccc00</color>
<color name="verde_confirma">#66b266</color>
</resources>
To get this colors from the xml file, I've used this code: valor it's a TextView, and ctx it's a Context object. I'm not using it from an Activity, but a BaseAdapter to a ListView. That's why I've used this Context Object.
valor.setTextColor(ctx.getResources().getColor(R.color.azul_credito));
Hope it helps.
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
Did you declare the jobparameters as map properly as bean?
Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?
For more on expression language you can find information in Spring documentation here.
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
In a Colab notebook you can do:
from IPython.display import Audio
Audio(waveform, Rate=16000)
I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.
As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:
const FOO = 4 * 3;
doesn't work, but define('CONST', 4 * 3);
does. define
must include the namespace to be defined within that namespace.The code below should illustrate the differences.
namespace foo
{
const BAR = 1;
define('BAZ', 2);
define(__NAMESPACE__ . '\\BAZ', 3);
}
namespace {
var_dump(get_defined_constants(true));
}
The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3]
.
=== UPDATE ===
The upcoming PHP 5.6 will allow a bit more flexibility with const
. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:
const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;
You still won't be able to define consts in terms of variables or function returns though, so
const RND = mt_rand();
const CONSTVAR = $var;
will still be out.
Fancy C# extension method based on previous answers:
public static IWebElement SetAttribute(this IWebElement element, string name, string value)
{
var driver = ((IWrapsDriver)element).WrappedDriver;
var jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, name, value);
return element;
}
Usage:
driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");
the thing that work for me was to set /etc/hosts to point the hostname to the ip and not to the loopback interface and than restart my application.
cat /etc/hosts
127.0.0.1 localhost.localdomain localhost
192.168.0.1 myservername
This is my configuration:
-Dcom.sun.management.jmxremote.port=1617
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
this is you need and all people
string date = textBox1.Text;
DateTime date2 = Convert.ToDateTime(date);
var date3 = date2.Date;
var D = date3.Day;
var M = date3.Month;
var y = date3.Year;
string monthStr = M.ToString("00");
string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();
textBox1.Text = date4;
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.
I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.
There are a few listed (at the end of the post) in on this java learning resources article too
For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.
mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/
And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
After mid-2018:
1:) Invite @getidsbot or @RawDataBot
to your group and get your group id from the chat id field.
Message
+ message_id: 338
+ from
? + id: *****
? + is_bot: false
? + first_name: ???
? + username: ******
? + language_code: en
+ chat
? + id: -1001118554477 // This is Your Group id
? + title: Test Group
? + type: supergroup
+ date: 1544948900
+ text: A
2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.
Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup
bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
df[df['Value']==df['Value'].max()]
This will return the entire row with max value
PyParsing does a great job. The PyParsing wiki was killed so here is another location where there are examples of the use of PyParsing (example link). One reason for investing a little time with pyparsing is that he has also written a very brief very well organized O'Reilly Short Cut manual that is also inexpensive.
Having said that, I use BeautifulSoup a lot and it is not that hard to deal with the entities issues, you can convert them before you run BeautifulSoup.
Goodluck
create LOGIN guest WITH PASSWORD='guest@123', CHECK_POLICY = OFF;
Be sure when you want to exceute the following
DENY VIEW ANY DATABASE TO guest;
ALTER AUTHORIZATION ON DATABASE::BiddingSystemDB TO guest
Selected Database should be Master
add
compile 'com.mcxiaoke.volley:library:1.0.19'
compile project('volley')
in the dependencies, under build.gradle file of your app
DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER
For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.
// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------
import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
def class zxing {
def static main(def args) {
def filename = "./qrcode.png"
def data = "This is a test to see if I can encode and decode this data..."
def charset = "UTF-8" //"ISO-8859-1"
def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])
writeQrCode(filename, data, charset, hints, 100, 100)
assert data == readQrCode(filename, charset, hints)
}
def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
}
def static readQrCode(def filename, def charset, def hints) {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
Result result = new MultiFormatReader().decode(binaryBitmap, hints)
result.getText()
}
}
WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).
The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same
No, it is not.
The one that is new to the N Developer Preview has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
The one that is supported by all Android versions, including N, has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, String url)
So why should I do to make it work on all versions?
Override the deprecated one, the one that takes a String
as the second parameter.
to get list of data from src/main/resources/data folder --
first of all mention your folder location in properties file as -
resourceLoader.file.location=data
inside class declare your location.
@Value("${resourceLoader.file.location}")
@Setter
private String location;
private final ResourceLoader resourceLoader;
public void readallfilesfromresources() {
Resource[] resources;
try {
resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
for (int i = 0; i < resources.length; i++) {
try {
InputStream is = resources[i].getInputStream();
byte[] encoded = IOUtils.toByteArray(is);
String content = new String(encoded, Charset.forName("UTF-8"));
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa
With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '
I was used Total Commander for taking file from Internal storage
Remove the () from your expressions that are not working will get the desired results you need.
but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
Try FileUtils
from Apache commons-io (listFiles
and iterateFiles
methods):
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
To solve your issue with the TestX
folders, I would first iterate through the list of folders:
File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
File dir = dirs[i];
if (dir.isDirectory()) {
File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
}
}
Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.
In case of a number you can try to convert to string:
var stringValue = str.toString();
return stringValue.replace(/^\s+|\s+$/g,'');
If your url looks something like this:
somesite.com/something/123
Where '123' is a parameter named 'id' (url like /something/:id), try with:
this.$route.params.id
Try:
echo quit | telnet IP 22 2>/dev/null | grep Connected
Yes you can.
You don't have to download both Anaconda.
Only you need to download one of the version of Anaconda and need activate other version of Anaconda python.
If you have Python 3, you can set up a Python 2 kernel like this;
python2 -m pip install ipykernel
python2 -m ipykernel install --user
If you have Python 2,
python3 -m pip install ipykernel
python3 -m ipykernel install --user
Then you will be able to see both version of Python!
If you are using Anaconda Spyder then you should swap version here:
If you are using Jupiter then check here:
Note: If your Jupiter or Anaconda already open after installation you need to restart again. Then you will be able to see.
Most basic and general explanation: cryptography is all about number theory, and all integer numbers (except 0 and 1) are made up of primes, so you deal with primes a lot in number theory.
More specifically, some important cryptographic algorithms such as RSA critically depend on the fact that prime factorization of large numbers takes a long time. Basically you have a "public key" consisting of a product of two large primes used to encrypt a message, and a "secret key" consisting of those two primes used to decrypt the message. You can make the public key public, and everyone can use it to encrypt messages to you, but only you know the prime factors and can decrypt the messages. Everyone else would have to factor the number, which takes too long to be practical, given the current state of the art of number theory.
Yes, you can use find_elements_by_
to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html
Example HTML:
<ul class="bar">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
You can use the find_elements_by_
like so:
parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")
If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
For completeness, since no-one has suggested it yet. .git/refs/heads/master
is a file that contains only one line: the hash of the latest commit on master
. So you could just read it from there.
Or, as as command:
cat .git/refs/heads/master
Update:
Note that git now supports storing some head refs in the pack-ref file instead of as a file in the /refs/heads/ folder. https://www.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
Italian version:
=CONCATENA(
DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;42949);4);"-";
DECIMALE.HEX(CASUALE.TRA(0;4294967295);8);
DECIMALE.HEX(CASUALE.TRA(0;42949);4))
Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...
I usually use online DNS lookup tools for that, e.g. http://network-tools.com/
It can check your HTTP header as well. Only a proxy located in Europe would be better.
So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.
For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.
My original answer was this:
// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.
A more correct answer (but not perfect) is:
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name
Using the :text
, :radio
, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text
which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input
part of the selector, plus the cache of the form element, this should make it the best performing answer here.
This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.
Both of them have the same function, but people generally prefer while(true)
. It feels easy to read and understand...
For Mapping Composite primary key using Entity framework we can use two approaches.
1) By Overriding the OnModelCreating() Method
For ex: I have the model class named VehicleFeature as shown below.
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
The Code in my DBContext would be like ,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2) By Data Annotations.
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
Please refer the below links for the more information.
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
I was getting this crash only on Samsung Lollipop devices and this solution worked for me.
dexOptions {
preDexLibraries false
}
I'm posting this answer here because this question is currently the highest ranked search result on Google for this crash and none of the above answers worked for me.
These JavaScript solutions give you the milliseconds or the seconds since the midnight, January 1st, 1970.
The IE 9+ solution(IE 8 or the older version doesn't support this.):
var timestampInMilliseconds = Date.now();
var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.
To get more information about Date.now()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
The generic solution:
// ‘+’ operator makes the operand numeric.
// And ‘new’ operator can be used without the arguments ‘(……)’.
var timestampInMilliseconds = +new Date;
var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.
Be careful to use, if you don't want something like this case.
if(1000000 < Math.round(1000000.2)) // false.
In app.module.ts
add this:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [FormsModule],
})
The Python Tutorial simply calls it 'the *
-operator'. It performs unpacking of arbitrary argument lists.
As of Java 8 you now can do it with a stream using a lambda:
list.stream().sorted(Comparator.comparing(customObject::getId))
.foreach(object -> System.out.println(object));
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
In linux server try dos2unix script_name
(remove all (if there is any) pyc
files with command find . -name '*.pyc' -delete
)
and re run in the case if you worked on script on windows
SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;
I think this will do it
I'm hoping you are having the same problem that I had... my issue was simple: Make a fixed textarea with locked percentages inside the container (I'm new to CSS/JS/HTML, so bear with me, if I don't get the lingo correct) so that no matter the device it's displaying on, the box filling the container (the table cell) takes up the correct amount of space. Here's how I solved it:
<table width=100%>
<tr class="idbbs">
B.S.:
</tr></br>
<tr>
<textarea id="bsinpt"></textarea>
</tr>
</table>
Then CSS Looks like this...
#bsinpt
{
color: gainsboro;
float: none;
background: black;
text-align: left;
font-family: "Helvetica", "Tahoma", "Verdana", "Arial Black", sans-serif;
font-size: 100%;
position: absolute;
min-height: 60%;
min-width: 88%;
max-height: 60%;
max-width: 88%;
resize: none;
border-top-color: lightsteelblue;
border-top-width: 1px;
border-left-color: lightsteelblue;
border-left-width: 1px;
border-right-color: lightsteelblue;
border-right-width: 1px;
border-bottom-color: lightsteelblue;
border-bottom-width: 1px;
}
Sorry for the sloppy code block here, but I had to show you what's important and I don't know how to insert quoted CSS code on this website. In any case, to ensure you see what I'm talking about, the important CSS is less indented here...
What I then did (as shown here) is very specifically tweak the percentages until I found the ones that worked perfectly to fit display, no matter what device screen is used.
Granted, I think the "resize: none;" is overkill, but better safe than sorry and now the consumers will not have anyway to resize the box, nor will it matter what device they are viewing it from.
It works great.
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format>
(here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd
. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff')
.
For parsing weird formatted dates on C# you can use DateTime.ParseExact()
method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture)
. Here you have the DateTime.ParseExact() explanation on MSDN)
I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: color 0.3s linear;
-webkit-transition: color 0.3s linear;
-moz-transition: color 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the above code!
Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: all 0.3s linear;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
padding-left: 10px;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the "all" example!
JConsole is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the NetBeans Profiler for this.
Just go to Publish -> Application File -> And change the effected dll publish status from prerequisite to include! This worked for me!
timeout 5
to delay
timeout 5 >nul
to delay without asking you to press any key to cancel
May also be called, "rename" by tortoise, but svn move, is the command in the barebones svn client.
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
Bash script to convert each page of a PDF into its own SVG file.
#!/bin/bash
#
# Make one PDF per page using PDF toolkit.
# Convert this PDF to SVG using inkscape
#
inputPdf=$1
pageCnt=$(pdftk $inputPdf dump_data | grep NumberOfPages | cut -d " " -f 2)
for i in $(seq 1 $pageCnt); do
echo "converting page $i..."
pdftk ${inputPdf} cat $i output ${inputPdf%%.*}_${i}.pdf
inkscape --without-gui "--file=${inputPdf%%.*}_${i}.pdf" "--export-plain-svg=${inputPdf%%.*}_${i}.svg"
done
To generate in png, use --export-png
, etc...
Correct syntax:
[System.Runtime.InteropServices.RuntimeEnvironment]::GetSystemVersion()
#or
$PSVersionTable.CLRVersion
The GetSystemVersion
function returns a string like this:
v2.0.50727 #PowerShell v2.0 in Win 7 SP1
or like this
v4.0.30319 #PowerShell v3.0 (Windows Management Framework 3.0) in Win 7 SP1
$PSVersionTable
is a read-only object. The CLRVersion property is a structured version number like this:
Major Minor Build Revision
----- ----- ----- --------
4 0 30319 18444
From MSDN:
If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2.
In your example, path2 is absolute.
OFFLINE SOLUTION - Haversine Algorithm
In Javascript
var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);
function HaversineInM(lat1, long1, lat2, long2)
{
return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}
function HaversineInKM(lat1, long1, lat2, long2)
{
var dlong = (long2 - long1) * _d2r;
var dlat = (lat2 - lat1) * _d2r;
var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
var d = _eQuatorialEarthRadius * c;
return d;
}
var meLat = -33.922982;
var meLong = 151.083853;
var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);
C#
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var meLat = -33.922982;
double meLong = 151.083853;
var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
static double _eQuatorialEarthRadius = 6378.1370D;
static double _d2r = (Math.PI / 180D);
private static int HaversineInM(double lat1, double long1, double lat2, double long2)
{
return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
}
private static double HaversineInKM(double lat1, double long1, double lat2, double long2)
{
double dlong = (long2 - long1) * _d2r;
double dlat = (lat2 - lat1) * _d2r;
double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
double d = _eQuatorialEarthRadius * c;
return d;
}
}
Reference: https://en.wikipedia.org/wiki/Great-circle_distance
Try this solution.
$mainModelData = mainModel::where('column', $value)
->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
->orderBy('relation_table.title', 'ASC')
->with(['relationModal' => function ($q) {
$q->where('column', 'value');
}])->get();
Example:
$user = User::where('city', 'kullu')
->join('salaries', 'users.id', '=', 'salaries.user_id')
->orderBy('salaries.amount', 'ASC')
->with(['salaries' => function ($q) {
$q->where('amount', '>', '500000');
}])->get();
You can change the column name in join()
as per your database structure.
Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. You can abstract away entire control using static resources.
Static resources are used under following circumstances:
Dynamic resources:
I'm using iReport 2.0.2 to generate the jasper file.
I didn't found the hammer logo, but I have a menu create > compile
in the menu bar who create the the jasper file in the iReport program files folder :
IReport Logs :"Compilation vers le fichier... .\SalesOrderItemsSubreportA4.jasper -> C:\Program Files\JasperSoft\iReport-2.0.2\SalesOrderItemsSubreportA4.java"
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
Here it is:
def put4ChannelImageOn4ChannelImage(back, fore, x, y):
rows, cols, channels = fore.shape
trans_indices = fore[...,3] != 0 # Where not transparent
overlay_copy = back[y:y+rows, x:x+cols]
overlay_copy[trans_indices] = fore[trans_indices]
back[y:y+rows, x:x+cols] = overlay_copy
#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)
If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:
Here is another function that works great for me, returns distance in kilometers:
function distance(lat1, lng1, lat2, lng2) {
var radlat1 = Math.PI * lat1 / 180;
var radlat2 = Math.PI * lat2 / 180;
var radlon1 = Math.PI * lng1 / 180;
var radlon2 = Math.PI * lng2 / 180;
var theta = lng1 - lng2;
var radtheta = Math.PI * theta / 180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
//Get in in kilometers
dist = dist * 1.609344;
return dist;
}
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
Select the lines you want to comment out. Then press:
Ctrl + #
In the manifest:
<activity android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize">
In your activity:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.your_activity_layout);
You can obtain all of the parameters from the confusion matrix. The structure of the confusion matrix(which is 2X2 matrix) is as follows (assuming the first index is related to the positive label, and the rows are related to the true labels):
TP|FN
FP|TN
So
TP = cm[0][0]
FN = cm[0][1]
FP = cm[1][0]
TN = cm[1][1]
More details at https://en.wikipedia.org/wiki/Confusion_matrix
same as a normal modulo 3.14 % 6.28 = 3.14
, just like 3.14%4 =3.14
3.14%2 = 1.14
(the remainder...)
None of the above was my solution: in my case the issue is that [ApiController] was not added to the controller so it is giving Null value
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController] // This was my problem, make sure that it is there!
public class OrderController : Controller
...
Some reasons are:
1) C++ grammar is more complex than C# or Java and takes more time to parse.
2) (More important) C++ compiler produces machine code and does all optimizations during compilation. C# and Java go just half way and leave these steps to JIT.
My simple fix it turned out to be calling the form's Activate()
method, so there's no need to use TopMost
(which is what I was aiming at).
The best use would be
echo $_SERVER['HTTP_HOST'];
And it can be used like this:
if (strpos($_SERVER['HTTP_HOST'], 'banana.com') !== false) {
echo "Yes this is indeed the banana.com domain";
}
This code below is a good way to see all the variables in $_SERVER in a structured HTML output with your keywords highlighted that halts directly after execution. Since I do sometimes forget which one to use myself - I think this can be nifty.
<?php
// Change banana.com to the domain you were looking for..
$wordToHighlight = "banana.com";
$serverVarHighlighted = str_replace( $wordToHighlight, '<span style=\'background-color:#883399; color: #FFFFFF;\'>'. $wordToHighlight .'</span>', $_SERVER );
echo "<pre>";
print_r($serverVarHighlighted);
echo "</pre>";
exit();
?>
select
@selectoneCount = case @Temp
when 1 then (@selectoneCount+1)
when 2 then (@selectoneCount+1)
end
select @selectoneCount
For this the System.Timers.Timer
works best
// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it
myTimer.Enabled = true;
// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }
See Timer Class (.NET 4.6 and 4.5) for details