mToolbar.setNavigationIcon(R.mipmap.ic_launcher);
mToolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.ic_menu));
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
That's easy!
First, give your button an id
such as <input type="button" value="I am a button!" id="myButton" />
Then, for height, and width, use CSS code:
.myButton {
width: 100px;
height: 100px;
}
You could also do this CSS:
input[type="button"] {
width: 100px;
height: 100px;
}
But that would affect all the buttons on the Page.
Working example - JSfiddle
I found this post, which looks a bit old, but I figured I'd update everyone on my new findings.
I am using Oracle SQL Developer 4.0.2.15 on Windows. Our database is Oracle 10g (version 10.2.0.1) running on Windows.
To make a column auto-increment in Oracle -
Your id column (primary key) will now auto-increment, but the sequence will be starting at 1.
If you need to increment the id to a certain point, you'll have to run a few alter statements against the sequence.
This post has some more details and how to overcome this.
I found the solution here
Creating an isolate scope is undesirable. I would avoid using the scope attribute and do something like this. scope:true gives you a new child scope but not isolate. Then use parse to point a local scope variable to the same object the user has supplied to the ngModel attribute.
app.directive('myDir', ['$parse', function ($parse) {
return {
restrict: 'EA',
scope: true,
link: function (scope, elem, attrs) {
if(!attrs.ngModel) {return;}
var model = $parse(attrs.ngModel);
scope.model = model(scope);
}
};
}]);
Assuming getItemNumber()
returns an int
, replace
if (id.equals(list[pos].getItemNumber()))
with
if (id == list[pos].getItemNumber())
When we does not want to own the object:
Ex:
class A
{
shared_ptr<int> sPtr1;
weak_ptr<int> wPtr1;
}
In the above class wPtr1 does not own the resource pointed by wPtr1. If the resource is got deleted then wPtr1 is expired.
To avoid circular dependency:
shard_ptr<A> <----| shared_ptr<B> <------
^ | ^ |
| | | |
| | | |
| | | |
| | | |
class A | class B |
| | | |
| ------------ |
| |
-------------------------------------
Now if we make the shared_ptr of the class B and A, the use_count of the both pointer is two.
When the shared_ptr goes out od scope the count still remains 1 and hence the A and B object does not gets deleted.
class B;
class A
{
shared_ptr<B> sP1; // use weak_ptr instead to avoid CD
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void setShared(shared_ptr<B>& p)
{
sP1 = p;
}
};
class B
{
shared_ptr<A> sP1;
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
void setShared(shared_ptr<A>& p)
{
sP1 = p;
}
};
int main()
{
shared_ptr<A> aPtr(new A);
shared_ptr<B> bPtr(new B);
aPtr->setShared(bPtr);
bPtr->setShared(aPtr);
return 0;
}
output:
A()
B()
As we can see from the output that A and B pointer are never deleted and hence memory leak.
To avoid such issue just use weak_ptr in class A instead of shared_ptr which makes more sense.
For mobiles, it’s better to use it
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
because it will display incorrectly after changing the orientation.The “viewport” will be increased when changing the orientation to portrait.See full example
The good option is to use AdminClient as below before starting to produce or consume the messages
private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;
try (AdminClient client = AdminClient.create(properties)) {
client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
} catch (ExecutionException ex) {
LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
return;
}
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
If you want to add a flag to every link, e.g. -fsanitize=address
then I would not recommend using CMAKE_*_LINKER_FLAGS
. Even with them all set it still doesn't use the flag when linking a framework on OSX, and maybe in other situations. Instead use link_libraries()
:
add_compile_options("-fsanitize=address")
link_libraries("-fsanitize=address")
This works for everything.
I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:
Consider a Article model, a Event model and a Comment model. An article or an event has many comments. A comment belongs to either Article or Event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#return the article with least number of comments
end
end
Event Model
class Event < ActiveRecord::Base
has_many :comments, as: :commentable
def find_first_comment
comments.first(created_at DESC)
end
def self.least_commented
#returns the event with least number of comments
end
end
As we can notice, there is a significant piece of code common to both Event and Article. Using concerns we can extract this common code in a separate module Commentable.
For this create a commentable.rb file in app/models/concerns.
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
# for the given article/event returns the first comment
def find_first_comment
comments.first(created_at DESC)
end
module ClassMethods
def least_commented
#returns the article/event which has the least number of comments
end
end
end
And now your models look like this :
Comment Model:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
include Commentable
end
Event Model:
class Event < ActiveRecord::Base
include Commentable
end
Consider a Event model. A event has many attenders and comments.
Typically, the event model might look like this
class Event < ActiveRecord::Base
has_many :comments
has_many :attenders
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
def self.least_commented
# finds the event which has the least number of comments
end
def self.most_attended
# returns the event with most number of attendes
end
def has_attendee(attendee_id)
# returns true if the event has the mentioned attendee
end
end
Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.
The above model can be refactored using concerns as below:
Create a attendable.rb
and commentable.rb
file in app/models/concerns/event folder
attendable.rb
module Attendable
extend ActiveSupport::Concern
included do
has_many :attenders
end
def has_attender(attender_id)
# returns true if the event has the mentioned attendee
end
module ClassMethods
def most_attended
# returns the event with most number of attendes
end
end
end
commentable.rb
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments
end
def find_first_comment
# for the given article/event returns the first comment
end
def find_comments_with_word(word)
# for the given event returns an array of comments which contain the given word
end
module ClassMethods
def least_commented
# finds the event which has the least number of comments
end
end
end
And now using Concerns, your Event model reduces to
class Event < ActiveRecord::Base
include Commentable
include Attendable
end
* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc
var request = new HttpRequestMessage {
RequestUri = new Uri("[your request url string]"),
Method = HttpMethod.Post,
Headers = {
{ "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
{ HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
{ HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
},
Content = new MultipartContent { // Just example of request sending multipart request
new ObjectContent<[YOUR JSON OBJECT TYPE]>(
new [YOUR JSON OBJECT TYPE INSTANCE](...){...},
new JsonMediaTypeFormatter(),
"application/json"), // this will add 'Content-Type' header for the first part of request
new ByteArrayContent([BINARY DATA]) {
Headers = { // this will add headers for the second part of request
{ "Content-Type", "application/Executable" },
{ "Content-Disposition", "form-data; filename=\"test.pdf\"" },
},
},
},
};
HTML only: use the download
attribute:
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
_x000D_
Javascript only: you can save any data URI with this code:
function saveAs(uri, filename) {_x000D_
var link = document.createElement('a');_x000D_
if (typeof link.download === 'string') {_x000D_
link.href = uri;_x000D_
link.download = filename;_x000D_
_x000D_
//Firefox requires the link to be in the body_x000D_
document.body.appendChild(link);_x000D_
_x000D_
//simulate click_x000D_
link.click();_x000D_
_x000D_
//remove the link when done_x000D_
document.body.removeChild(link);_x000D_
} else {_x000D_
window.open(uri);_x000D_
}_x000D_
}_x000D_
_x000D_
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'_x000D_
saveAs(file, 'logo.gif');
_x000D_
Chrome, Firefox, and Edge 13+ will use the specified filename.
IE11, Edge 12, and Safari 9 (which don't support the download
attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …
Here is something really neat and simple (atleast I believe so :)) and requires no manipulation of date to be cloned or overloading any of browser's native functions like toJSON (reference: How to JSON stringify a javascript Date and preserve timezone, courtsy Shawson)
Pass a replacer function to JSON.stringify that stringifies stuff to your heart's content!!! This way you don't have to do hour and minute diffs or any other manipulations.
I have put in console.logs to see intermediate results so it is clear what is going on and how recursion is working. That reveals something worthy of notice: value param to replacer is already converted to ISO date format :). Use this[key] to work with original data.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
Normally, for every connecting client the server forks a child process that communicates with the client (TCP). The parent server hands off to the child process an established socket that communicates back to the client.
When you send the data to a socket from your child server, the TCP stack in the OS creates a packet going back to the client and sets the "from port" to 80.
This would be helpful for someone like me. Create custom dialog style:
<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowIsFloating">false</item>
</style>
In AndroidManifest.xml
file set theme for wanted activity:
<activity
android:name=".CustomDialog"
...
android:theme="@style/MyDialog"/>
That is all, no need to call methods programaticaly.
With mysqli
you're able to use multiple statements for real using mysqli_multi_query()
.
NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.
You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.
I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.
If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED
, ISOLATION
etc. you'll have to understand the basics of transaction management itself.
Read Trasaction management for more on explanation.
Have a look at this plunker:: this is the simplest example i could think of
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{Data.FirstName}}<!-- How do I automatically updated it here? -->
</div>
</div>
// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
return { FirstName: '' };
});
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data;
});
In my case, I already had a period(.)
and also a comma(,)
, so what worked for me was to replace
the comma(,)
with an empty string like below:
parseFloat('3,000.78'.replace(',', ''))
This is assuming that the amount from the existing database is 3,000.78. The results are: 3000.78
without the initial comma(,)
.
Found the chrome Options class in the Selenium source code.
Usage to create a Chrome driver instance:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)
I created a package that makes this a lot easier to use.
You can handle simple things like and object:
const world = {
locations: {
europe: 'Munich',
usa: 'Indianapolis'
}
};
world.dig('locations', 'usa');
// => 'Indianapolis'
world.dig('locations', 'asia', 'japan');
// => 'null'
or a little more complicated:
const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';
These port assignments are specified by the Internet Assigned Numbers Authority (IANA):
Historically, port 465 was initially planned for the SMTPS encryption and authentication “wrapper” over SMTP, but it was quickly deprecated (within months, and over 15 years ago) in favor of STARTTLS over SMTP (RFC 3207). Despite that fact, there are probably many servers that support the deprecated protocol wrapper, primarily to support older clients that implemented SMTPS. Unless you need to support such older clients, SMTPS and its use on port 465 should remain nothing more than an historical footnote.
The hopelessly confusing and imprecise term, SSL, has often been used to indicate the SMTPS wrapper and TLS to indicate the STARTTLS protocol extension.
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use set dateformat
for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.
Here we go:
update vehicles_vehicle v
set price=s.price_per_vehicle
from shipments_shipment s
where v.shipment_id=s.id;
Simple as I could make it. Thanks guys!
Can also do this:
-- Doesn't work apparently
update vehicles_vehicle
set price=s.price_per_vehicle
from vehicles_vehicle v
join shipments_shipment s on v.shipment_id=s.id;
But then you've got the vehicle table in there twice, and you're only allowed to alias it once, and you can't use the alias in the "set" portion.
When MySQL driver is used you have to set connection param rewriteBatchedStatements
to true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**)
.
With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.
Without this param only advantage is cleaner source code.
Also this issue occurres when the response contenttype is not application/json
. In my case response contenttype was text/html
and i faced this problem. I changed it to application/json
then it worked.
This:
<select style="width: XXXpx;">
XXX = Any Number
Works great in Google Chrome v70.0.3538.110
I ran into this issue after doing a manual react-native link
of a dependency which didn't support auto link on RN 0.59+
The solution was to select the xcodeproj file under the Libraries folder in Xcode and then in Build Settings, change Header Search Paths to add these two (recursive):
$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core
$(SRCROOT)/../../../ios/Pods/Headers/Public
Most memory leaks are the result of not being clear about object ownership and lifetime.
The first thing to do is to allocate on the Stack whenever you can. This deals with most of the cases where you need to allocate a single object for some purpose.
If you do need to 'new' an object then most of the time it will have a single obvious owner for the rest of its lifetime. For this situation I tend to use a bunch of collections templates that are designed for 'owning' objects stored in them by pointer. They are implemented with the STL vector and map containers but have some differences:
My beaf with STL is that it is so focused on Value objects while in most applications objects are unique entities that do not have meaningful copy semantics required for use in those containers.
Instead of
let loginRegisterButton:UIButton = {
//... }()
Try:
lazy var loginRegisterButton:UIButton = {
//... }()
That should fix the compile error!!!
The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
generator = myfunct()
while True:
my_element = generator.next()
make sure to catch the exception thrown after the last element is taken
You want to use a Set
or List
implementation (e.g. HashSet
, TreeSet
, etc, or ArrayList
, LinkedList
, etc..), since Java does not have dynamically sized arrays.
List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");
for (String z : zoom) {
System.err.println(z);
}
Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:
List<String> zoom = Arrays.asList("String 1", "String 2", "String n");
There are at least two ways to solve this.
Solution 1:
If you are okay with using an absolutely positioned element, you can use the top
and bottom
properties instead of height
. By setting both top
and bottom
to 0
you force the element into taking up full height.
#menu
{
position: absolute;
border-right: 1px solid black;
top: 0;
bottom: 0;
}?
Solution 2:
Another way would be to force the HTML and BODY elements into a 100% height, to give room for a menu with 100% height:
body, html { height: 100%; }
#menu
{
border-right: 1px solid black;
height: 100%;
}?
Easiest way:
byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
buffer = new byte[stream.Length - 1];
stream.Read(buffer, 0, buffer.Length);
}
using (Stream stream = new IO.FileStream("newFile.pdf"))
{
stream.Write(buffer, 0, buffer.Length);
}
Or something along these lines...
PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.
For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.
Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.
PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).
Hope this helps.
I also faced same obstacle but not able to find out solution from given answers. Might be it's happening due to project path which is having special characters & space etc... So please try to add this line in your build.gradle
.
compile files('../app/libs/jtwitter.jar')// pass your .jar file name
".." (Double dot)
will find your root directory of your project.
I, for example, use fail()
to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.
This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.
Im using this code instead of the InetAddress :
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PHP provides a function to sanitize a text to different format
How to :
echo filter_var(
"Lorem Ipsum has been the industry's",FILTER_SANITIZE_URL
);
Blockquote
LoremIpsumhasbeentheindustry's
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
You need to use "\n"
not '\n'
in your gsub. The different quote marks behave differently.
Double quotes "
allow character expansion and expression interpolation ie. they let you use escaped control chars like \n
to represent their true value, in this case, newline, and allow the use of #{expression}
so you can weave variables and, well, pretty much any ruby expression you like into the text.
While on the other hand, single quotes '
treat the string literally, so there's no expansion, replacement, interpolation or what have you.
In this particular case, it's better to use either the .delete
or .tr
String method to delete the newlines.
In mij case the ViewController.h/m where in a lib. The projects still builds but since Xcode 6.3 the above error was shown at run-time. Moving both files back into the project solved the issue.
There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:
2020-12-09T16:09:53+00:00
is a date time value that is compliant both both standards.
2020-12-09 16:09:53+00:00
uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.
2020-12-09T16:09:53-00:00
has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.
20201209T160953Z
omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.
ISO 8601 allows for things like ordinal dates such as 2020-344
which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.
For your questions:
Is one just an extension?
No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.
Should I use one over the other?
Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.
Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.
Do I really need to care that bad?
Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.
Basically,
LAZY = fetch when needed
EAGER = fetch immediately
I tried using it and didn't work, guess it's just the modal versioin.
Although, it worked as this:
$("#myModal").on("hide.bs.modal", function () {
// put your default event here
});
Just to update the answer =)
I have encountered the same problem (in my case with Samsung mobile browsers) and therefore I stumbled upon this question.
Thanks to Calsal's answer I found something that I believe will exclude virtually all desktop browsers because it seems to be recognized by the mobile browsers I tried (see screenshot from a compiled table: CSS pointer feature detection table ).
MDN web docs state that
The pointer CSS @media feature can be used to apply styles based on whether the user's primary input mechanism is a pointing device, and if so, how accurate it is
.
What I discovered is that pointer: coarse is something that is unknown to all desktop browsers in the attached table but known to all mobile browsers in the same table. This seems to be most effective choice because all other pointer keyword values give inconsistent results.
Hence you could construct a media query like Calsal described but slightly modified. It makes use of a reversed logic to rule out all touch devices.
Sass mixin:
@mixin hover-supported {
/*
* https://developer.mozilla.org/en-US/docs/Web/CSS/@media/pointer
* coarse: The primary input mechanism includes a pointing device of limited accuracy.
*/
@media not all and (pointer: coarse) {
&:hover {
@content;
}
}
}
a {
color:green;
border-color:blue;
@include hover-supported() {
color:blue;
border-color:green;
}
}
Compiled CSS:
a {
color: green;
border-color: blue;
}
@media not all and (pointer: coarse) {
a:hover {
color: blue;
border-color: green;
}
}
It is also described in this gist I created after researching the problem. Codepen for empirical research.
UPDATE: As of writing this update, 2018-08-23, and pointed out by @DmitriPavlutin this technique no longer seems to work with Firefox desktop.
You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:
Am I using proper dependency injection? Do I possibly needs to move the private methods into a separate class and rather test that? Must these methods be private? ...can't they be default or protected rather?
In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
This should help. Its CSS3 :first-child where you should say that the first tr
of the table you would like to style. http://reference.sitepoint.com/css/pseudoclass-firstchild
I have found a crossbrowser compatible JQuery plugin here.
http://designwithpc.com/Plugins/ddSlick
probably useful in this scenario.
I could figure out the problem. I was getting following warning on startup of eclipse.
The Maven Integration requires that Eclipse be running in a JDK, because a number of Maven core plugins are using jars from the JDk.
Please make sure the -vm option in eclipse.ini is pointing to a JDK and verify that
Installed JRE's are also using JDK installs
I changed eclipse.ini file and added following and restarted eclipse
-vm
C:/Program Files/java/jdk1.6.0_21/bin/javaw.exe
Now I can see "Maven Dependency" library included automatically in java build path.
IOS 14 SDK: you can add action with closure callback:
let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
print("Button tapped!")
}))
Getting a reference to the control sender
let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
let textField = action.sender as! UITextField
print("Text is \(textField.text)")
}), for: .editingChanged)
The property you need is location.hash. For example:
location.hash = 'top'; //would jump to named anchor "top
I don't know how to do the nice scroll animation without the use of dojo or some toolkit like that, but if you just need it to jump to an anchor, location.hash should do it.
(tested on FF3 and Safari 3.1.2)
To write to a file you can use a byte array. The following example creates an empty ZIP file, which you can add files to:
[Byte[]] $zipHeader = 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
[System.IO.File]::WriteAllBytes("C:\My.zip", $zipHeader)
Or use:
[Byte[]] $text = [System.Text.Encoding]::UTF8.getBytes("Enabling feature XYZ.......")
[System.IO.File]::WriteAllBytes("C:\My.zip", $text)
CASE
isn't used for flow control... for this, you would need to use IF
...
But, there's a set-based solution to this problem instead of the procedural approach:
UPDATE tblEmployee
SET
InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID
Note that the ELSE
will preserves the original value if the @NewStatus
condition isn't met.
If you've come from a C-family language, you will be thinking "pointer to object of type X which might be the memory address 0 (NULL)", and if you're coming from a dynamically typed language you'll be thinking "Object which is probably of type X but might be of type undefined". Neither of these is actually correct, although in a roundabout way the first one is close.
The way you should be thinking of it is as if it's an object like:
struct Optional<T> {
var isNil:Boolean
var realObject:T
}
When you're testing your optional value with foo == nil
it's really returning foo.isNil
, and when you say foo!
it's returning foo.realObject
with an assertion that foo.isNil == false
. It's important to note this because if foo
actually is nil when you do foo!
, that's a runtime error, so typically you'd want to use a conditional let instead unless you are very sure that the value will not be nil. This kind of trickery means that the language can be strongly typed without forcing you to test if values are nil everywhere.
In practice, it doesn't truly behave like that because the work is done by the compiler. At a high level there is a type Foo?
which is separate to Foo
, and that prevents funcs which accept type Foo
from receiving a nil value, but at a low level an optional value isn't a true object because it has no properties or methods; it's likely that in fact it is a pointer which may by NULL(0) with the appropriate test when force-unwrapping.
There other situation in which you'd see an exclamation mark is on a type, as in:
func foo(bar: String!) {
print(bar)
}
This is roughly equivalent to accepting an optional with a forced unwrap, i.e.:
func foo(bar: String?) {
print(bar!)
}
You can use this to have a method which technically accepts an optional value but will have a runtime error if it is nil. In the current version of Swift this apparently bypasses the is-not-nil assertion so you'll have a low-level error instead. Generally not a good idea, but it can be useful when converting code from another language.
@ManyToMany
associationsMost often, you will need to use @JoinTable
annotation to specify the mapping of a many-to-many table relationship:
So, assuming you have the following database tables:
In the Post
entity, you would map this relationship, like this:
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
The @JoinTable
annotation is used to specify the table name via the name
attribute, as well as the Foreign Key column that references the post
table (e.g., joinColumns
) and the Foreign Key column in the post_tag
link table that references the Tag
entity via the inverseJoinColumns
attribute.
Notice that the cascade attribute of the
@ManyToMany
annotation is set toPERSIST
andMERGE
only because cascadingREMOVE
is a bad idea since we the DELETE statement will be issued for the other parent record,tag
in our case, not to thepost_tag
record.
@OneToMany
associationsThe unidirectional @OneToMany
associations, that lack a @JoinColumn
mapping, behave like many-to-many table relationships, rather than one-to-many.
So, assuming you have the following entity mappings:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
//Constructors, getters and setters removed for brevity
}
Hibernate will assume the following database schema for the above entity mapping:
As already explained, the unidirectional @OneToMany
JPA mapping behaves like a many-to-many association.
To customize the link table, you can also use the @JoinTable
annotation:
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JoinTable(
name = "post_comment_ref",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();
And now, the link table is going to be called post_comment_ref
and the Foreign Key columns will be post_id
, for the post
table, and post_comment_id
, for the post_comment
table.
Unidirectional
@OneToMany
associations are not efficient, so you are better off using bidirectional@OneToMany
associations or just the@ManyToOne
side.
Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example
All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.
(There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)
In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.
According to: "Event loop from 10,000ft - core concept behind Node.js".
Use .ashx file type and use the same code
If anyone is getting this error after a Phpmyadmin export, using the custom options and adding the "drop tables" statements cleared this right up.
In summary, the most reliable way to have MiniDLNA rescan all media files is by issuing the following set of commands:
$ sudo minidlnad -R
$ sudo service minidlna restart
However, every so often MiniDLNA will be running on a server. Here is a client-side script to request a rescan on such a server:
#!/usr/bin/env bash
ssh -t server.on.lan 'sudo minidlnad -R && sudo service minidlna restart'
Update: 2017-01-10
Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.
http://caniuse.com/#feat=datauri
Data URIs are now supported by the following web browsers:
- Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
- Konqueror, via KDE's KIO slaves input/output system
- Opera (including devices such as the Nintendo DSi or Wii)
- WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
- Trident
- Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
- Data URIs are supported only for the following elements and/or attributes[4]:
- object (images only)
- img
- input type=image
- link
- CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
- Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
- TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme
http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support
I think use drop duplicate
sometimes will not so useful depending dataframe.
I found this:
[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)
And work for me!
https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe
Something like this...
var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;
See also LINQ query on a DataTable
I'm new to SQL, but came across this issue in a course I was taking and found that assigning the query to the project specifically helped to eliminate the multi-part error. For example the project I created was CTU SQL Project so I made sure I started my script with USE [CTU SQL Project] as my first line like below.
USE [CTU SQL Project]
SELECT Advisors.First_Name, Advisors.Last_Name...and so on.
var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');
if(startDate > endDate){
// do your stuff here...
}
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
This does exist, but it's actually a feature of git log
:
git log -p [--follow] [-1] <path>
Note that -p
can also be used to show the inline diff from a single commit:
git log -p -1 <commit>
Options used:
-p
(also -u
or --patch
) is hidden deeeeeeeep in the git-log
man page, and is actually a display option for git-diff
. When used with log
, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>
. (This behavior is described in the paragraph on --full-diff
, which causes the full diff of each commit to be shown.)-1
shows just the most recent change to the specified file (-n 1
can be used instead of -1
); otherwise, all non-zero diffs of that file are shown.--follow
is required to see changes that occurred prior to a rename.As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log
(or similar) to either count the number of intervening revisions or determine the hash of the commit.
To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)
Credit where credit is due:
log -p
thanks to this answer.--follow
option.-n 1
option and atatko for mentioning the -1
variant.-p
"means" semantically.-- CREATE OR ALTER PROCEDURE
ALTER PROCEDURE out (
@age INT,
@salary INT OUTPUT)
AS BEGIN
SELECT @salary = (SELECT SALARY FROM new_testing where AGE = @age ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY);
END
-----------------DECLARE THE OUTPUT VARIABLE---------------------------------
DECLARE @test INT
---------------------THEN EXECUTE THE QUERY---------------------------------
EXECUTE out 25 , @salary = @test OUTPUT
print @test
-------------------same output obtain without procedure------------------------------------------- SELECT * FROM new_testing where AGE = 25 ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Do this:
data = [4, 5, 6]
def print_data():
global data
print(data)
print_data()
Your question about performance is moot—both functions are very fast. The speed of your code will be determined by what you do with the random numbers.
However it's important you understand the difference in behaviour of those two functions. One does random sampling with replacement, the other does random sampling without replacement.
Wow, surprised there are so many overkill answers here...
<div class="firstClass" onclick="this.className='secondClass'">
If in case you are getting the values as undefined
, then you should consider restarting the node server and recompile again.
you can use it.
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
Here's how I download an ad banner. It's best to do it in the background if you're downloading a large image or a bunch of images.
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelectorInBackground:@selector(loadImageIntoMemory) withObject:nil];
}
- (void)loadImageIntoMemory {
NSString *temp_Image_String = [[NSString alloc] initWithFormat:@"http://yourwebsite.com/MyImageName.jpg"];
NSURL *url_For_Ad_Image = [[NSURL alloc] initWithString:temp_Image_String];
NSData *data_For_Ad_Image = [[NSData alloc] initWithContentsOfURL:url_For_Ad_Image];
UIImage *temp_Ad_Image = [[UIImage alloc] initWithData:data_For_Ad_Image];
[self saveImage:temp_Ad_Image];
UIImageView *imageViewForAdImages = [[UIImageView alloc] init];
imageViewForAdImages.frame = CGRectMake(0, 0, 320, 50);
imageViewForAdImages.image = [self loadImage];
[self.view addSubview:imageViewForAdImages];
}
- (void)saveImage: (UIImage*)image {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent: @"MyImageName.jpg" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
- (UIImage*)loadImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:@"MyImageName.jpg" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
As pointed out by others as well, Volley is officially available on Github:
Add this line to your gradle dependencies for volley:
compile 'com.android.volley:volley:1.0.0'
I like to keep the official volley repository in my app. That way I get it from the official source and can get updates without depending on anyone else and mitigating concerns expressed by other people.
Added volley as a submodule alongside app.
git submodule add -b master https://github.com/google/volley.git volley
In my settings.gradle, added the following line to add volley as a module.
include ':volley'
In my app/build.gradle, I added a compile dependency for the volley project
compile project(':volley')
That's all! Volley can now be used in my project.
Everytime I want to sync the volley module with Google's repo, i run this.
git submodule foreach git pull
SQL JOIN
?SQL JOIN
is a method to retrieve data from two or more database tables.
SQL JOIN
s ?There are a total of five JOIN
s. They are :
1. JOIN or INNER JOIN
2. OUTER JOIN
2.1 LEFT OUTER JOIN or LEFT JOIN
2.2 RIGHT OUTER JOIN or RIGHT JOIN
2.3 FULL OUTER JOIN or FULL JOIN
3. NATURAL JOIN
4. CROSS JOIN
5. SELF JOIN
In this kind of a JOIN
, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.
In other words, INNER JOIN
is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.
Note that a JOIN
without any other JOIN
keywords (like INNER
, OUTER
, LEFT
, etc) is an INNER JOIN
. In other words, JOIN
is
a Syntactic sugar for INNER JOIN
(see: Difference between JOIN and INNER JOIN).
OUTER JOIN
retrieves
Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).
There are three kinds of Outer Join :
2.1 LEFT OUTER JOIN or LEFT JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the
right table. If there are no columns matching in the right table, it returns NULL
values.
2.2 RIGHT OUTER JOIN or RIGHT JOIN
This JOIN
returns all the rows from the right table in conjunction with the matching rows from the
left table. If there are no columns matching in the left table, it returns NULL
values.
2.3 FULL OUTER JOIN or FULL JOIN
This JOIN
combines LEFT OUTER JOIN
and RIGHT OUTER JOIN
. It returns rows from either table when the conditions are met and returns NULL
value when there is no match.
In other words, OUTER JOIN
is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.
Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.
It is based on the two conditions :
JOIN
is made on all the columns with the same name for equality.This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.
It is the Cartesian product of the two tables involved. The result of a CROSS JOIN
will not make sense
in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).
It is not a different form of JOIN
, rather it is a JOIN
(INNER
, OUTER
, etc) of a table to itself.
Depending on the operator used for a JOIN
clause, there can be two types of JOIN
s. They are
For whatever JOIN
type (INNER
, OUTER
, etc), if we use ONLY the equality operator (=), then we say that
the JOIN
is an EQUI JOIN
.
This is same as EQUI JOIN
but it allows all other operators like >, <, >= etc.
Many consider both
EQUI JOIN
and ThetaJOIN
similar toINNER
,OUTER
etcJOIN
s. But I strongly believe that its a mistake and makes the ideas vague. BecauseINNER JOIN
,OUTER JOIN
etc are all connected with the tables and their data whereasEQUI JOIN
andTHETA JOIN
are only connected with the operators we use in the former.Again, there are many who consider
NATURAL JOIN
as some sort of "peculiar"EQUI JOIN
. In fact, it is true, because of the first condition I mentioned forNATURAL JOIN
. However, we don't have to restrict that simply toNATURAL JOIN
s alone.INNER JOIN
s,OUTER JOIN
s etc could be anEQUI JOIN
too.
Alternatively, you can use Guava's Resources object:
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);
My solution: I set almost every View as static
. Now my app interacts perfect. Being able to call the static methods from everywhere is maybe not a good style, but why to play around with code that doesn't work? I read a lot of questions and their answers here on SO and no solution brought success (for me).
I know it can leak the memory, and waste heap, and my code will not be fit on other projects, but I don't feel scared about this - I tested the app on different devices and conditions, no problems at all, the Android Platform seems to be able handle this. The UI gets refreshed every second and even on a S2 ICS (4.0.3) device the app is able to handle thousands of geo-markers.
We can use the rank() window function (where you would choose the rank = 1) rank just adds a number for every row of a group (in this case it would be the hour)
here's an example. ( from https://github.com/jaceklaskowski/mastering-apache-spark-book/blob/master/spark-sql-functions.adoc#rank )
val dataset = spark.range(9).withColumn("bucket", 'id % 3)
import org.apache.spark.sql.expressions.Window
val byBucket = Window.partitionBy('bucket).orderBy('id)
scala> dataset.withColumn("rank", rank over byBucket).show
+---+------+----+
| id|bucket|rank|
+---+------+----+
| 0| 0| 1|
| 3| 0| 2|
| 6| 0| 3|
| 1| 1| 1|
| 4| 1| 2|
| 7| 1| 3|
| 2| 2| 1|
| 5| 2| 2|
| 8| 2| 3|
+---+------+----+
I'm surprised no one has suggested using a result filter. This is the cleanest way to globally hook into the action/result pipeline:
public class JsonResultFilter : IResultFilter
{
public int? MaxJsonLength { get; set; }
public int? RecursionLimit { get; set; }
public void OnResultExecuting(ResultExecutingContext filterContext)
{
if (filterContext.Result is JsonResult jsonResult)
{
// override properties only if they're not set
jsonResult.MaxJsonLength = jsonResult.MaxJsonLength ?? MaxJsonLength;
jsonResult.RecursionLimit = jsonResult.RecursionLimit ?? RecursionLimit;
}
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
Then, register an instance of that class using GlobalFilters.Filters
:
GlobalFilters.Filters.Add(new JsonResultFilter { MaxJsonLength = int.MaxValue });
Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push)
, #pragma warning (disable)
and a matching #pragma warning (pop)
, as shown here.
Although there are some other options, including #pramga warning (once)
.
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
Update Gradle
dependencies {
compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}
Locate the FindBugs Report
file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html
Find the specific message
Import the correct version of the annotation
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
Add the annotation directly above the offending code
@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")
See here for more info: findbugs Spring Annotation
Your product
class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.
As a side note: You should use Pascal casing for your class names. That is Product
, and not product
.
Writing JSON Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject
and looping through each json item. Below i am creating an instance of JSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
small remark: I am using modules in webbased application (asp.net). I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session. If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others. Modules is a great way to work but need concentration on how to use it.
To help against mistakes: classes are send to the
CarbageCollector
when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it. I use this to save data that sometimes is lost because of the sessionhandling by IIS.
IIS Form auth
and
IIS_session
are not in sync, and with my module I pull back data that went over de cliff.
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
As stated here: Why use Fragment#setRetainInstance(boolean)?
you can also use fragments method setRetainInstance(true)
like this:
public class MyFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// keep the fragment and all its data across screen rotation
setRetainInstance(true);
}
}
I clicked ‘Cancel Running’, opened the Devices list, unpaired my iPhone, removed my USB cable and reconnected it, paired the iPhone, and then was asked on my iPhone to enter my passcode ("pin code"). Did this and then was finally able to pair my phone correctly.
One more way:
git diff stash@{N}^! -- path/to/file1 path/to/file2 | git apply -R
It is also worth mentioning that localStorage
cannot be used when users browse in "private" mode in some versions of mobile Safari.
Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):
Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.
Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:
<span ng-switch on="interface">
<img ng-switch-when="UP" src='green-checkmark.png'>
<img ng-switch-default src='big-black-X.png'>
</span>
ng-switch will likely be better/easier if you have more than two images.
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:
ALTER USER user SET search_path to 'name_of_schema';
after these changes "INSERT" will work correctly.
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
This helped me:
Posted: 8/12/2011 4:54
Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory
https://forums.oracle.com/forums/thread.jspa?messageID=10020012�
I don't think this has been mentioned yet, but you could also use Powermockito:
Given:
package com.foo.service.impl;
public class FooServiceImpl {
public void doSomeFooStuff() {
System.getenv("FOO_VAR_1");
System.getenv("FOO_VAR_2");
System.getenv("FOO_VAR_3");
// Do the other Foo stuff
}
}
You could do the following:
package com.foo.service.impl;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import org.junit.Beforea;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(FooServiceImpl.class)
public class FooServiceImpTest {
@InjectMocks
private FooServiceImpl service;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockStatic(System.class); // Powermock can mock static and private methods
when(System.getenv("FOO_VAR_1")).thenReturn("test-foo-var-1");
when(System.getenv("FOO_VAR_2")).thenReturn("test-foo-var-2");
when(System.getenv("FOO_VAR_3")).thenReturn("test-foo-var-3");
}
@Test
public void testSomeFooStuff() {
// Test
service.doSomeFooStuff();
verifyStatic();
System.getenv("FOO_VAR_1");
verifyStatic();
System.getenv("FOO_VAR_2");
verifyStatic();
System.getenv("FOO_VAR_3");
}
}
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);
//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
NSLog("File not exist");
} else {
NSLog("File exist");
}
//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
cell.photoImageView.image = image;//Display image
}
result = soup.find('strong', text='text I am looking for').text
I think you're mixing up two different paradigms here.
As you noted, the highly flexible ExternalProject
module runs its commands at build time, so you can't make direct use of Project A's import file since it's only created once Project A has been installed.
If you want to include
Project A's import file, you'll have to install Project A manually before invoking Project B's CMakeLists.txt - just like any other third-party dependency added this way or via find_file
/ find_library
/ find_package
.
If you want to make use of ExternalProject_Add
, you'll need to add something like the following to your CMakeLists.txt:
ExternalProject_Add(project_a
URL ...project_a.tar.gz
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/project_a
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
)
include(${CMAKE_CURRENT_BINARY_DIR}/lib/project_a/project_a-targets.cmake)
ExternalProject_Get_Property(project_a install_dir)
include_directories(${install_dir}/include)
add_dependencies(project_b_exe project_a)
target_link_libraries(project_b_exe ${install_dir}/lib/alib.lib)
To understand get and set, it's all related to how variables are passed between different classes.
The get method is used to obtain or retrieve a particular variable value from a class.
A set value is used to store the variables.
The whole point of the get and set is to retrieve and store the data values accordingly.
What I did in this old project was I had a User class with my get and set methods that I used in my Server class.
The User class's get set methods:
public int getuserID()
{
//getting the userID variable instance
return userID;
}
public String getfirstName()
{
//getting the firstName variable instance
return firstName;
}
public String getlastName()
{
//getting the lastName variable instance
return lastName;
}
public int getage()
{
//getting the age variable instance
return age;
}
public void setuserID(int userID)
{
//setting the userID variable value
this.userID = userID;
}
public void setfirstName(String firstName)
{
//setting the firstName variable text
this.firstName = firstName;
}
public void setlastName(String lastName)
{
//setting the lastName variable text
this.lastName = lastName;
}
public void setage(int age)
{
//setting the age variable value
this.age = age;
}
}
Then this was implemented in the run()
method in my Server class as follows:
//creates user object
User use = new User(userID, firstName, lastName, age);
//Mutator methods to set user objects
use.setuserID(userID);
use.setlastName(lastName);
use.setfirstName(firstName);
use.setage(age);
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".
var link = $(element); var offset = link.offset(); var top = offset.top; var left = offset.left; var bottom = top + link.outerHeight(); var right = left + link.outerWidth();
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
To get an .exe with NASM'compiler and Visual Studio's linker this code works fine:
global WinMain
extern ExitProcess ; external functions in system libraries
extern MessageBoxA
section .data
title: db 'Win64', 0
msg: db 'Hello world!', 0
section .text
WinMain:
sub rsp, 28h
mov rcx, 0 ; hWnd = HWND_DESKTOP
lea rdx,[msg] ; LPCSTR lpText
lea r8,[title] ; LPCSTR lpCaption
mov r9d, 0 ; uType = MB_OK
call MessageBoxA
add rsp, 28h
mov ecx,eax
call ExitProcess
hlt ; never here
If this code is saved on e.g. "test64.asm", then to compile:
nasm -f win64 test64.asm
Produces "test64.obj" Then to link from command prompt:
path_to_link\link.exe test64.obj /subsystem:windows /entry:WinMain /libpath:path_to_libs /nodefaultlib kernel32.lib user32.lib /largeaddressaware:no
where path_to_link could be C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin or wherever is your link.exe program in your machine, path_to_libs could be C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64 or wherever are your libraries (in this case both kernel32.lib and user32.lib are on the same place, otherwise use one option for each path you need) and the /largeaddressaware:no option is necessary to avoid linker's complain about addresses to long (for user32.lib in this case). Also, as it is done here, if Visual's linker is invoked from command prompt, it is necessary to setup the environment previously (run once vcvarsall.bat and/or see MS C++ 2010 and mspdb100.dll).
Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.
Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html
e.g.:
imageView.setImageResource(R.drawable.myimage);
Try these link types actually works for me.
https://www.facebook.com/sharer.php?u=YOUR_URL_HERE
https://twitter.com/intent/tweet?url=YOUR_URL_HERE
https://plus.google.com/share?url=YOUR_URL_HERE
https://www.linkedin.com/shareArticle?mini=true&url=YOUR_URL_HERE
I had exactly same problem (on OS X Maverics 10.9.1 with SQLite3 3.7.13, but I don't think SQLite is related to the cause). I tried to import csv data saved from MS Excel 2011, which btw. uses ';'
as columns separator. I found out that csv file from Excel still uses newline character from Mac OS 9 times, changing it to unix newline solved the problem. AFAIR BBEdit has a command for this, as well as Sublime Text 2.
Beginning with SQL Server 2012, you can use:
SELECT FORMAT(@date, 'yyyyMM')
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
A simple way that solve my problem was:
npm cache clear
npm or a process controlled by it is watching too many files. Updating max_user_watches on the build node can fix it forever. For debian put the following on terminal:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
If you want know how Increase the amount of inotify watchers only click on link.
The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.
You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)
df[['A']][df.B.gt(50) & df.C.ne(900)]
df[['A']]
will give you back column A in DataFrame format.
pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.
Bootstrap 4 (4.0.0-alpha.2) uses the css property column-count
in the card-columns
class to define how many columns of cards would be displayed inside the div
element.
But this property has only two values:
max-width: 34em
)min-width: 34em
)Here's how it is implemented in bootstrap.min.css :
@media (min-width: 34em) {
.card-columns {
-webkit-column-count:3;
-moz-column-count:3;
column-count:3;
?
}
?
}
To make the card stacking responsive, you can add the following media queries to your css file and modify the values for min-width
as per your requirements :
@media (min-width: 34em) {
.card-columns {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
}
}
@media (min-width: 48em) {
.card-columns {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
}
}
@media (min-width: 62em) {
.card-columns {
-webkit-column-count: 4;
-moz-column-count: 4;
column-count: 4;
}
}
@media (min-width: 75em) {
.card-columns {
-webkit-column-count: 5;
-moz-column-count: 5;
column-count: 5;
}
}
In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.
Read more about Array and ArrayList
List<String> aList = new ArrayList<String>();
aList.add("apple");
aList.add("banana");
aList.add("orange");
String result = alist.get(1); //this will retrieve banana
Note: Index starts from 0 i.e. Zero
You can use tic
and toc
from ttictoc
. Install it with
pip install ttictoc
And just import them in your script as follow
from ttictoc import tic,toc
tic()
# Some code
print(toc())
It's quite simple.
All you need to do is:
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, R.drawable.***)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
You can, using CSS variables (more precisely called CSS custom properties).
style="--my-color-var: orange;"
background-color: var(--my-color-var);
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
}
div:after {
background-color: var(--my-color-var);
content: '';
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
.bubble {
position: relative;
width: 30px;
height: 15px;
padding: 0;
background: #FFF;
border: 1px solid #000;
border-radius: 5px;
text-align: center;
background-color: var(--bubble-color);
}
.bubble:after {
content: "";
position: absolute;
top: 4px;
left: -4px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent var(--bubble-color);
display: block;
width: 0;
z-index: 1;
}
.bubble:before {
content: "";
position: absolute;
top: 4px;
left: -5px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #000;
display: block;
width: 0;
z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
In Bootstrap 4 you hide the element:
<p id="insufficient-balance-warning" class="d-none alert alert-danger">Pay me</p>
Then, sure, you could literally show it with:
if (pizzaFundsAreLow) {
$('#insufficient-balance-warning').removeClass('d-none');
}
But if you do it the semantic way, by transferring responsibility from Bootstrap to jQuery, then you can use other jQuery niceties like fading:
if (pizzaFundsAreLow) {
$('#insufficient-balance-warning').hide().removeClass('d-none').fadeIn();
}
Download the Android SDK to the machine. (Suppose that the location is /home/zelong/Android/Sdk) (home/username/Android/Sdk)
Add these lines to the file ~/.bashrc (located at home/username/.bashrc)
export ANDROID_HOME="/home/zelong/Android/Sdk"
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools
This will make it permanent for the current user because every time the machine boots, it will run this script and set the enviroment path.
After making this change, remember to save it.
Then run source ~/.bashrc
to apply the changes or restart your terminal.
Test if it works:
zelong@zelong-ThinkPad-T430:~$ echo $ANDROID_HOME
/home/zelong/Android/Sdk
zelong@zelong-ThinkPad-T430:~$ which android
/home/zelong/Android/Sdk/tools/android
zelong@zelong-ThinkPad-T430:~$ which adb
/home/zelong/Android/Sdk/platform-tools/adb
As we can see,
android
command line locates under tools
adb
command line locates under platform-tools
On Windows, the PGDATA directory that the PostgresSQL docs describe is at somewhere like C:\Program Files\PostgreSQL\8.1\data
. The data for a particular database is under (for example) C:\Program Files\PostgreSQL\8.1\data\base\100929
, where I guess 100929 is the database number.
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
Your application must be compiled as a Windows console application.
Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:
message.max.bytes
and replica.fetch.max.bytes
. message.max.bytes
has to be equal or smaller(*) than replica.fetch.max.bytes
.max.request.size
to send the larger message.max.partition.fetch.bytes
to receive larger messages.(*) Read the comments to learn more about message.max.bytes
<=replica.fetch.max.bytes
After trying multiple things,what really worked was: 1. downloading "poi" and "poi-ooxml" manually 2.Adding these d/w jars into "Maven Dependencies"
Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.
This seemed to have worked for me!
Mat a_image = imread(argv[1]);
cvtColor(a_image, a_image, CV_BGR2GRAY);
GaussianBlur(a_image, a_image, Size(7,7), 1.5, 1.5);
threshold(a_image, a_image, 100, 255, CV_THRESH_BINARY);
The trouble with DateTime.UtcNow
and DateTime.Now
is that, depending on the computer and operating system, it may only be accurate to between 10 and 15 milliseconds. However, on windows computers one can use by using the low level function GetSystemTimePreciseAsFileTime to get microsecond accuracy, see the function GetTimeStamp()
below.
[System.Security.SuppressUnmanagedCodeSecurity, System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern void GetSystemTimePreciseAsFileTime(out FileTime pFileTime);
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct FileTime {
public const long FILETIME_TO_DATETIMETICKS = 504911232000000000; // 146097 = days in 400 year Gregorian calendar cycle. 504911232000000000 = 4 * 146097 * 86400 * 1E7
public uint TimeLow; // least significant digits
public uint TimeHigh; // most sifnificant digits
public long TimeStamp_FileTimeTicks { get { return TimeHigh * 4294967296 + TimeLow; } } // ticks since 1-Jan-1601 (1 tick = 100 nanosecs). 4294967296 = 2^32
public DateTime dateTime { get { return new DateTime(TimeStamp_FileTimeTicks + FILETIME_TO_DATETIMETICKS); } }
}
public static DateTime GetTimeStamp() {
FileTime ft; GetSystemTimePreciseAsFileTime(out ft);
return ft.dateTime;
}
There exists several tools to export/import from SQL Server to Excel.
Google is your friend :-)
We use DbTransfer (which is one of those which can export a complete Database to an Excel file also) here: http://www.dbtransfer.de/Products/DbTransfer.
We have used the openrowset feature of sql server before, but i was never happy with it, becuase it's not very easy to use and lacks of features and speed...
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)
<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
<img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
$(window).load(function() {
var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();
if (window.console) {
console.log($("#imgCat").height());
console.log(heightRate);
console.log(widthRate);
console.log(heightRate > widthRate);
}
if (heightRate <= widthRate) {
$("#imgCat").height($("#imgCat").parent(".imgContainer").height());
} else {
$("#imgCat").width($("#imgCat").parent(".imgContainer").width());
}
});
</script>
ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
If the problem is happening on a specific computer,then please try the following fix provided you have Internet Explorer 11.
Please open regedit.exe as an Administrator. Navigate to the following path/paths:
For 32 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
For 64 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION &
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
And delete the REG_DWORD
value iexplore.exe
.
Please close and relaunch the website using Internet Explorer 11, it will default to Edge as Document Mode.
More IntelliJ 13+ Shortcuts for Terminal
Mac OS X:
alt ?F12
cmd ?shift ?A then type Terminal
then hit Enter
shift ?shift ?shift ?shift ? then type Terminal
then hit Enter
Windows:
altF12 press Enter
ctrlshift ?A start typing Terminal
then hit Enter
shift ?shift ? then type Terminal
then hit Enter
Although this is an old question, I think none has already answered using this approach:
# python 2.7
import os
d='/home/me/test'
filesToRemove = [os.path.join(d,f) for f in os.listdir(d)]
for f in filesToRemove:
os.remove(f)
Note however:
If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.
Ok I figured this out. For anyone else trying to do this you need:
a) heading: your heading from the hardware compass. This is in degrees east of magnetic north
b) bearing: the bearing from your location to the destination location. This is in degrees east of true north.
myLocation.bearingTo(destLocation);
c) declination: the difference between true north and magnetic north
The heading that is returned from the magnetometer + accelermometer is in degrees east of true (magnetic) north (-180 to +180) so you need to get the difference between north and magnetic north for your location. This difference is variable depending where you are on earth. You can obtain by using GeomagneticField class.
GeomagneticField geoField;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
geoField = new GeomagneticField(
Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis()
);
...
}
}
Armed with these you calculate the angle of the arrow to draw on your map to show where you are facing in relation to your destination object rather than true north.
First adjust your heading with the declination:
heading += geoField.getDeclination();
Second, you need to offset the direction in which the phone is facing (heading) from the target destination rather than true north. This is the part that I got stuck on. The heading value returned from the compass gives you a value that describes where magnetic north is (in degrees east of true north) in relation to where the phone is pointing. So e.g. if the value is -10 you know that magnetic north is 10 degrees to your left. The bearing gives you the angle of your destination in degrees east of true north. So after you've compensated for the declination you can use the formula below to get the desired result:
heading = myBearing - (myBearing + heading);
You'll then want to convert from degrees east of true north (-180 to +180) into normal degrees (0 to 360):
Math.round(-heading / 360 + 180)
Update 1 November 2012
My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr()
to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr()
.
Original answer
If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.
I'll summarize the main issues:
prop()
rather than attr()
.prop()
does what attr()
used to do. Replacing calls to attr()
with prop()
in your code will generally work.checked
property is a Boolean, the style
property is an object with individual properties for each style, the size
property is a number.value
and checked
: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue
/ defaultChecked
property).If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.
As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:
<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">
So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:
if ( $("#cb").attr("checked") === true ) {...}
if ( $("#cb").attr("checked") == "checked" ) {...}
if ( $("#cb").is(":checked") ) {...}
This is actually the simplest thing in the world to do with the checked
Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:
if (document.getElementById("cb").checked) {...}
The property also makes checking or unchecking the checkbox trivial:
document.getElementById("cb").checked = false
In jQuery 1.6, this unambiguously becomes
$("#cb").prop("checked", false)
The idea of using the checked
attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.
checked
attributeIt may not be enabled for php-cli, you can enable like this;
sudo phpenmod gd
UPDATE
I guess, you are using ppa:ondrej php package (5.6), which is confusing you with default ubuntu 14.04 php package (5.5.9).
To install php 5.6 gd library from ppa:ondrej, you should use:
sudo apt-get install php5.6-gd
See this post How to execute angular controller function on page load?
For fast lookup:
// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>
// in controller
$scope.init = function () {
// check if there is query in url
// and fire search in case its value is not empty
};
This way, You don't have to wait till document is ready.
If you use .Net 4.5 you can also use standard .Net json serializer:
using System.Runtime.Serialization.Json;
...
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);
In .Net 4.5 and older you can use JavaScriptSerializer class:
using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);
I'm sure there's a more efficient way to do it, but I would probably do this:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.
Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.
So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.
But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.
python compile on the fly when you run it.
Run a .py file by(linux): python abc.py
Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.
> def get_browser():
> """Get the browser (a "driver")."""
> # find the path with 'which chromedriver'
> path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
> 'venv/bin/chromedriver')
> download_dir = "/home/moose/selenium-download/"
> print("Is directory: {}".format(os.path.isdir(download_dir)))
>
> from selenium.webdriver.chrome.options import Options
> chrome_options = Options()
> chrome_options.add_experimental_option('prefs', {
> "plugins.plugins_list": [{"enabled": False,
> "name": "Chrome PDF Viewer"}],
> "download": {
> "prompt_for_download": False,
> "default_directory": download_dir
> }
> })
>
> browser = webdriver.Chrome(path_to_chromedriver,
> chrome_options=chrome_options)
> return browser
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
For excluding one or more library globally add the following to your build.gradle
configurations.all {
exclude group:"org.apache.geronimo.specs", module: "geronimo-servlet_2.5_spec"
exclude group:"ch.qos.logback", module:"logback-core"
}
Now the exclude block has two properties group and module. For those of you coming from maven background, group is same as groupId and module is same as artifactId. Example: To exclude com.mchange:c3p0:0.9.2.1 following should be exclude block
exclude group:"com.mchange", module:"c3p0"
I have faced the same question recently. What I understand is, if the branch you are checking in has a file which you modified and it happens to be also modified and committed by that branch. Then git will stop you from switching to the branch to keep your change safe before you commit or stash.
For Python/Java,
^(.(?!(some text)))*$
http://www.lisnichenko.com/articles/javapython-inverse-regex.html
A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.
As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphonse moves to his right, while Gaston moves to his left. They're still blocking each other, and so on...
The main difference between livelock and deadlock is that threads are not going to be blocked, instead they will try to respond to each other continuously.
In this image, both circles (threads or processes) will try to give space to the other by moving left and right. But they can't move any further.
Generally, this is how you open an OS folder containing a bunch of vdmk files on VMware Player.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Try this:
$r = Page()->getInstanceByName($page);
It worked for me in a similar case.
You can do this via parsing the user-agent header:
http://php.about.com/od/learnphp/p/http_user_agent.htm
Be wary that this is not very reliable and can be trivially spoofed.
As long as your array $phpinfo['PHP Core']['memory_limit']
contains the value of memory_limit
, it does work the following:
Example:
# Memory Limit equal or higher than 64M?
$ok = (int) (bool) setting_to_bytes($phpinfo['PHP Core']['memory_limit']) >= 0x4000000;
/**
* @param string $setting
*
* @return NULL|number
*/
function setting_to_bytes($setting)
{
static $short = array('k' => 0x400,
'm' => 0x100000,
'g' => 0x40000000);
$setting = (string)$setting;
if (!($len = strlen($setting))) return NULL;
$last = strtolower($setting[$len - 1]);
$numeric = (int) $setting;
$numeric *= isset($short[$last]) ? $short[$last] : 1;
return $numeric;
}
Details of the shorthand notation are outline in a PHP manual's FAQ entry and extreme details are part of Protocol of some PHP Memory Stretching Fun.
Take care if the setting is -1
PHP won't limit here, but the system does. So you need to decide how the installer treats that value.
In Kotlin, an E-mail address you can validate by the simple method without writing a lot of code and bother yourself with a regular expression like "^[_A-Za-z0-9-\+]....".
Look how is simple:
fun validateEmail(emailForValidation: String): Boolean{
return Patterns.EMAIL_ADDRESS.matcher(emailForValidation).matches()
}
After you write this method for e-mail validation you just need to input your e-mail which you want to validate. If validateEmail() method returns true e-mail is valid and if false then e-mail is not valid.
Here is example how you can use this method:
val eMail: String = emailEditText.text.toString().trim()
if (!validateEmail(eMail)){ //IF NOT TRUE
Toast.makeText(context, "Please enter valid E-mail address", Toast.LENGTH_LONG).show()
return //RETURNS BACK TO IF STATEMENT
}
You could combine them, use jQuery to bind the function to the click
<div id="myDiv">Some Content</div>
$('#myDiv').click(divFunction);
function divFunction(){
//some code
}
Adding php5.ini doesn't work at all. But see the 'Disable FastCGI' section in this article on GoDaddy: http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions
Add these lines to .htaccess files (webroot & website installation directory):
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
It saves me a day! Cheers! Thanks DragonLord!
I have a simple system that is pure JavaScript. It checks for changes in a simple text file that is never cached. When you upload a new version this file is changed. Just put the following JS at the top of the page.
(function(url, storageName) {_x000D_
var fromStorage = localStorage.getItem(storageName);_x000D_
var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000));_x000D_
getUrl(function(fromUrl) {_x000D_
// first load_x000D_
if (!fromStorage) {_x000D_
localStorage.setItem(storageName, fromUrl);_x000D_
return;_x000D_
}_x000D_
// old file_x000D_
if (fromStorage === fromUrl) {_x000D_
return;_x000D_
}_x000D_
// files updated_x000D_
localStorage.setItem(storageName, fromUrl);_x000D_
location.reload(true);_x000D_
});_x000D_
function getUrl(fn) {_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.open("GET", fullUrl, true);_x000D_
xmlhttp.send();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
if (xmlhttp.readyState === XMLHttpRequest.DONE) {_x000D_
if (xmlhttp.status === 200 || xmlhttp.status === 2) {_x000D_
fn(xmlhttp.responseText);_x000D_
}_x000D_
else if (xmlhttp.status === 400) {_x000D_
throw 'unable to load file for cache check ' + url;_x000D_
}_x000D_
else {_x000D_
throw 'unable to load file for cache check ' + url;_x000D_
}_x000D_
}_x000D_
};_x000D_
}_x000D_
;_x000D_
})("version.txt", "version");
_x000D_
just replace the "version.txt" with your file that is always run and "version" with the name you want to use for your local storage.
The combined answer for writing to a file can be;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
None of this worked for me. I found some documentation on doctrine's site that says to set the value directly to set a default value.
private $default = 0;
This inserted the value I wanted.
Marked answer work!! but Not in my case there's more then one datepicker and only want to implement on particular datepicker
So I use instance of dp and find datepicker Div and add hide class
Here's Code
<style>
.hide-day-calender .ui-datepicker-calendar{
display:none;
}
</style>
<script>
$('#dpMonthYear').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
},
beforeShow: function (elem,dp) {
$(dp.dpDiv).addClass('hide-day-calender'); //here a change
}
});
</script>
Note: You can not target
.ui-datepicker-calendar
and set css, because it will constantly rendering while selection/changes
What you have done is perfect and very good practice.
The reason I say its good practice... For example, if for some reason you are using a "primitive" type of database pooling and you call connection.close()
, the connection will be returned to the pool and the ResultSet
/Statement
will never be closed and then you will run into many different new problems!
So you can't always count on connection.close()
to clean up.
I hope this helps :)
If it's an active code base, you might still want to upgrade the code base. Of course, performing the changes manually isn't feasible but I believe that this problem could be solved once and for all by one single sed
command. I haven't tried it, though, so take the following with a grain of salt.
find . -exec sed -E -i .backup -n \
-e 's/char\s*\*\s*(\w+)\s*= "/char const* \1 = "/g' {} \;
This might not find all places (even not considering function calls) but it would alleviate the problem and make it possible to perform the few remaining changes manually.
Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.
Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.
In Python (modified primes.py):
def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a
def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)
def lcmm(*args):
"""Return lcm of args."""
return reduce(lcm, args)
Usage:
>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560
reduce()
works something like that:
>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> print reduce(f, "abcd")
f(f(f(a,b),c),d)
You can use XDocument.Parse(string)
instead of Load(string)
.
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
Saving cache:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};
The simple way to do so is :
Attr function (since jQuery version 1.0)
$("a").attr("href", "https://stackoverflow.com/")
or
Prop function (since jQuery version 1.6)
$("a").prop("href", "https://stackoverflow.com/")
Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.
Now, there are lot of ways to identify exact anchor or group of anchors:
Quite Simple Ones:
$("a")
$("a:eq(0)")
active
) : $("a.active")
profileLink
ID) : $("a#proileLink")
$("a:first")
More useful ones:
$("[href]")
$("a[href='www.stackoverflow.com']")
$("a[href!='www.stackoverflow.com']")
$("a[href*='www.stackoverflow.com']")
$("a[href^='www.stackoverflow.com']")
$("a[href$='www.stackoverflow.com']")
Now, if you want to amend specific URLs, you can do that as:
For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:
$("a[href^='http://www.google.com']")
.each(function()
{
this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
return "http://proxywebsite.com/?query="+encodeURIComponent(x);
});
});
You could use substr, I guess:
$string2 = substr($string1, 0, 100);
or mb_substr for multi-byte strings:
$string2 = mb_substr($string1, 0, 100);
You could create a function wich uses this function and appends for instance '...'
to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...)
try this
data => {
this.results = [...this.results, ...data.results];
this._next = data.next;
}
There are three states of button
button
button:hover
button:active
Normal:
.button
{
//your css
}
Active
.button:active
{
//your css
}
Hover
.button:hover
{
//your css
}
SNIPPET:
Use :active
to style the active state of button.
button:active{_x000D_
background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
The easiest way without installing msysgit is right click on the Git Bash shortcut icon ? Start in: ? "C:\Program Files (x86)".
Change the Start in entry and point out the Git Bash starting position. If you don't remove the --cd-to-home
part from the Target box, the Start in change gets overridden.
If your button is loading from an AJAX call, you should use
$(document).on("click", ".delegate_update_success", function(){
location.reload(true);
});
instead of
$( ".delegate_update_success" ).click(function() {
location.reload();
});
Also note the true
parameter for the location.reload
function.
The solution would be to use specific type in <>
like ArrayList<File>
.
example:
File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList filename = Arrays.asList(file);
above code generate warning because ArrayList
is not of specific type.
File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList<File> filename = Arrays.asList(file);
above code will do fine. Only change is in third line after ArrayList
.
Coming from the embedded world, where even uclibc is not always available, and code like
uint64_t myval = 0xdeadfacedeadbeef;
printf("%llx", myval);
is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
char* ullx(uint64_t val)
{
static char buf[34] = { [0 ... 33] = 0 };
char* out = &buf[33];
uint64_t hval = val;
unsigned int hbase = 16;
do {
*out = "0123456789abcdef"[hval % hbase];
--out;
hval /= hbase;
} while(hval);
*out-- = 'x', *out = '0';
return out;
}
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
There is no difference in terms of functionality
The addwithvalue
method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add
method requires that you specify the Database type first. This helps to reduce such errors.
For more detail Please click here
I modified my response to include the code for a test app I did.
Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).
First the javascript:
function test()
{
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/Home/SaveList",
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
}
And here's the code in my controller class:
public JsonResult SaveList(List<String> values)
{
return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!
use onmouseup
try something like this
<html>
<head>
<script type="text/javascript">
function hide(){
document.getElementById('span_hide').style.display="none";
}
</script>
</head>
<body>
<a href="page" style="text-decoration:none;display:block;">
<span onmouseup="hide()" id="span_hide">Hide me</span>
</a>
</body>
</html>
EDIT:
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
function hide(){
document.getElementById('span_hide').style.display="none";
}
</script>
</head>
<body>
<a href="page.html" style="text-decoration:none;display:block;" onclick="return false" >
<span onmouseup="hide()" id="span_hide">Hide me</span>
</a>
</body>
</html>