You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
curl_getinfo()
must be added before closing the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
curl_close($ch);
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
Your best bet is probably to simply re-clone from the remote repo (ie. Github or other). Unfortunately you will lose any unpushed commits and stashed changes, however your working copy should remain intact.
First make a backup copy of your local files. Then do this from the root of your working tree:
rm -fr .git
git init
git remote add origin [your-git-remote-url]
git fetch
git reset --mixed origin/master
git branch --set-upstream-to=origin/master master
Then commit any changed files as necessary.
If you have more then 1 dimension array
with open("file.txt", 'w') as output:
for row in values:
output.write(str(row) + '\n')
Code to write without '[' and ']'
with open("file.txt", 'w') as file:
for row in values:
s = " ".join(map(str, row))
file.write(s+'\n')
Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:
string folder;
AuthorizationRuleCollection rules;
try {
rules = Directory.GetAccessControl(folder)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
} catch(Exception ex) { //Posible UnauthorizedAccessException
throw new Exception("No permission", ex);
}
var rulesCast = rules.Cast<FileSystemAccessRule>();
if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)
|| !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))
throw new Exception("No permission");
//Here I have permission, ole!
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
You can cast List<> to ArrayList<> if you understand what you doing. Java compiler won't block it.
But:
if (list instanceof ArrayList<Task>) {
ArrayList<Task> arraylist = (ArrayList<Task>) list;
}
ArrayList<Task> arraylist = Lists.newArrayList(list);
Taking into account that getRunningTasks()
is deprecated and getRunningAppProcesses()
is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:
private boolean isAppInForeground(Context context)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
{
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
}
else
{
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(appProcessInfo);
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
{
return true;
}
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();
}
}
just do it as follows in your html write:
<button ng-click="going()">goto</button>
And in your controller, add $state as follows:
.controller('homeCTRL', function($scope, **$state**) {
$scope.going = function(){
$state.go('your route');
}
})
Code to display current date in element input or datepicker with ID="mydate"
Don't forget add reference to jquery-ui-*.js
$(document).ready(function () {
var dateNewFormat, onlyDate, today = new Date();
dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);
onlyDate = today.getDate();
if (onlyDate.toString().length == 2) {
dateNewFormat += '-' + onlyDate;
}
else {
dateNewFormat += '-0' + onlyDate;
}
$('#mydate').val(dateNewFormat);
});
I usually just type:
gcm notepad
or
gcm note*
gcm is the default alias for Get-Command.
On my system, gcm note* outputs:
[27] » gcm note*
CommandType Name Definition
----------- ---- ----------
Application notepad.exe C:\WINDOWS\notepad.exe
Application notepad.exe C:\WINDOWS\system32\notepad.exe
Application Notepad2.exe C:\Utils\Notepad2.exe
Application Notepad2.ini C:\Utils\Notepad2.ini
You get the directory and the command that matches what you're looking for.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
Here's a general solution:
def get_text_excluding_children(driver, element):
return driver.execute_script("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element)
The element passed to the function can be something obtained from the find_element...()
methods (i.e. it can be a WebElement
object).
Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:
return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
ret += child.textContent;
child = child.nextSibling;
}
return ret;
""", element)
I'm actually using this code in a test suite.
I find it easier using this formula
=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")
Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.
Hope it helps
Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's answer is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.
The basic answer.
The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.
So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.
So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).
If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.
So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.
Here's a blog post with far more detail and an example app.
Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.
In the meantime, there is a follow up blog post:
Also checkout the fork by 2point0 of the previously mentioned locking example:
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
Telerik today released a Beta of their own decompilation tool, JustDecompile. Closed source, but free and looks promising.
$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
left = 37,up = 38, right = 39,down = 40
$(document).keydown(function(e) {
switch(e.which) {
case 37:
$( "#prev" ).click();
break;
case 38:
$( "#prev" ).click();
break;
case 39:
$( "#next" ).click();
break;
case 40:
$( "#next" ).click();
break;
default: return;
}
e.preventDefault();
});
I'd like to add another reason that "catalina.sh" won't be able to connect to port 8005, apart from a firewall or a change in "server.xml": It takes Tomcat time to start listening on port 8005.
It's easy to reproduce this scenario If you start Tomcat and try to stop it immediately. Wait a few minutes and you'll see that the problem disappears because the port has opened.
DELETE is for deleting the request resource:
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …
PUT is for putting or updating a resource on the server:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …
For the full specification visit:
Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance
POST http://example.com/order/1/delete
or even worse
POST http://example.com/deleteOrder/id/1
effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.
So to delete a Resource on the webserver, you'd call
DELETE http://example.com/order/1
and to update it you'd call
PUT http://example.com/order/1
and provide the updated Resource Representation in the PUT body for the webserver to apply then.
So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.
For some more details visit:
NestedScrollView
as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.
This is where NestedScrollView
comes in.
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
cursor:url('http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif'), auto
NOTE 1: In some cases you should consider setting the offset (anchor):
cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif) 10 3, auto;
in this exmple, we set offsetx to 10 and offsety to 3 (from top left), so the pointer finger will be anchor. fiddle: http://jsfiddle.net/5kxt1j98/ (you can see the difference by moving cursor to top left of container)
NOTE 2: THE MAX CURSOR SIZE IS 128*128, recommended one is below 32*32.
If you're storing the object as type object
, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:
Type t = o.GetType();
Then from that you look up a property:
PropertyInfo p = t.GetProperty("Foo");
Then from that you can get a value:
object v = p.GetValue(o, null);
This answer is long overdue for an update for C# 4:
dynamic d = o;
object v = d.Foo;
And now another alternative in C# 6:
object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);
Note that by using ?.
we cause the resulting v
to be null
in three different situations!
o
is null
, so there is no object at allo
is non-null
but doesn't have a property Foo
o
has a property Foo
but its real value happens to be null
.So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.
Tested Code:
$("input").css("background","red");
Complete:
$('input:text').focus(function () {
$(this).css({ 'background': 'Black' });
});
$('input:text').blur(function () {
$(this).css({ 'background': 'red' });
});
Tested in version:
jquery-1.9.1.js
jquery-ui-1.10.3.js
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
Updated 2019
The basic difference is that container
is scales responsively, while container-fluid
is always width:100%
. Therefore in the root CSS definitions, they appear the same, but if you look further you'll see that .container
is bound to media queries.
Bootstrap 4
The container
has 5 widths...
.container {
width: 100%;
}
@media (min-width: 576px) {
.container {
max-width: 540px;
}
}
@media (min-width: 768px) {
.container {
max-width: 720px;
}
}
@media (min-width: 992px) {
.container {
max-width: 960px;
}
}
@media (min-width: 1200px) {
.container {
max-width: 1140px;
}
}
Bootstrap 3
The container
has 4 sizes. Full width on xs
screens, and then it's width varies based on the following media queries..
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
There are a couple of possibilities. One I like uses a stringstream as a go-between:
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
Now the contents of "file.txt" are available in a string as buffer.str()
.
Another possibility (though I certainly don't like it as well) is much more like your original:
std::ifstream t("file.txt");
t.seekg(0, std::ios::end);
size_t size = t.tellg();
std::string buffer(size, ' ');
t.seekg(0);
t.read(&buffer[0], size);
Officially, this isn't required to work under the C++98 or 03 standard (string isn't required to store data contiguously) but in fact it works with all known implementations, and C++11 and later do require contiguous storage, so it's guaranteed to work with them.
As to why I don't like the latter as well: first, because it's longer and harder to read. Second, because it requires that you initialize the contents of the string with data you don't care about, then immediately write over that data (yes, the time to initialize is usually trivial compared to the reading, so it probably doesn't matter, but to me it still feels kind of wrong). Third, in a text file, position X in the file doesn't necessarily mean you'll have read X characters to reach that point -- it's not required to take into account things like line-end translations. On real systems that do such translations (e.g., Windows) the translated form is shorter than what's in the file (i.e., "\r\n" in the file becomes "\n" in the translated string) so all you've done is reserved a little extra space you never use. Again, doesn't really cause a major problem but feels a little wrong anyway.
This is all I needed:
<meta name="viewport" content="user-scalable=no"/>
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction
block and select_for_update()
@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.select_for_update().get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not obj.some_field == instance.some_field: # Field has changed
# do something
It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. The technical name for it is an Immediately Invoked Function Expression (IIFE). jQuery plugins are usually written like this.
In Javascript, you can nest functions. So, the following is legal:
function outerFunction() {
function innerFunction() {
// code
}
}
Now you can call outerFunction()
, but the visiblity of innerFunction()
is limited to the scope of outerFunction()
, meaning it is private to outerFunction()
. It basically follows the same principle as variables in Javascript:
var globalVariable;
function someFunction() {
var localVariable;
}
Correspondingly:
function globalFunction() {
var localFunction1 = function() {
//I'm anonymous! But localFunction1 is a reference to me!
};
function localFunction2() {
//I'm named!
}
}
In the above scenario, you can call globalFunction()
from anywhere, but you cannot call localFunction1
or localFunction2
.
What you're doing when you write (function() { ... })()
, is you're making the code inside the first set of parentheses a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()
) that you just defined. So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:
(function() {
var private_var;
function private_function() {
//code
}
})();
In the first example, you would explicitly invoke globalFunction
by name to run it. That is, you would just do globalFunction()
to run it. But in the above example, you're not just defining a function; you're defining and invoking it in one go. This means that when the your JavaScript file is loaded, it is immediately executed. Of course, you could do:
function globalFunction() {
// code
}
globalFunction();
The behavior would largely be the same except for one significant difference: you avoid polluting the global scope when you use an IIFE (as a consequence it also means that you cannot invoke the function multiple times since it doesn't have a name, but since this function is only meant to be executed once it really isn't an issue).
The neat thing with IIFEs is that you can also define things inside and only expose the parts that you want to the outside world so (an example of namespacing so you can basically create your own library/plugin):
var myPlugin = (function() {
var private_var;
function private_function() {
}
return {
public_function1: function() {
},
public_function2: function() {
}
}
})()
Now you can call myPlugin.public_function1()
, but you cannot access private_function()
! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:
EDIT
I forgot to mention. In that final ()
, you can pass anything you want inside. For example, when you create jQuery plugins, you pass in jQuery
or $
like so:
(function(jQ) { ... code ... })(jQuery)
So what you're doing here is defining a function that takes in one parameter (called jQ
, a local variable, and known only to that function). Then you're self-invoking the function and passing in a parameter (also called jQuery
, but this one is from the outside world and a reference to the actual jQuery itself). There is no pressing need to do this, but there are some advantages:
Earlier I described how these functions run automatically at startup, but if they run automatically who is passing in the arguments? This technique assumes that all the parameters you need are already defined as global variables. So if jQuery wasn't already defined as a global variable this example would not work. As you might guess, one things jquery.js does during its initialization is define a 'jQuery' global variable, as well as its more famous '$' global variable, which allows this code to work after jQuery has been included.
You have to enable auto return in your PayPal account, otherwise it will ignore the return
field.
From the documentation (updated to reflect new layout Jan 2019):
Auto Return is turned off by default. To turn on Auto Return:
- Log in to your PayPal account at https://www.paypal.com or https://www.sandbox.paypal.com The My Account Overview page appears.
- Click the gear icon top right. The Profile Summary page appears.
- Click the My Selling Preferences link in the left column.
- Under the Selling Online section, click the Update link in the row for Website Preferences. The Website Payment Preferences page appears
- Under Auto Return for Website Payments, click the On radio button to enable Auto Return.
- In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments. NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.
- Scroll to the bottom of the page, and click the Save button.
IPN is for instant payment notification. It will give you more reliable/useful information than what you'll get from auto-return.
Documentation for IPN is here: https://www.x.com/sites/default/files/ipnguide.pdf
Online Documentation for IPN: https://developer.paypal.com/docs/classic/ipn/gs_IPN/
The general procedure is that you pass a notify_url
parameter with the request, and set up a page which handles and validates IPN notifications, and PayPal will send requests to that page to notify you when payments/refunds/etc. go through. That IPN handler page would then be the correct place to update the database to mark orders as having been paid.
Enum.valueOf()
only checks the constant name, so you need to pass it "COLUMN_HEADINGS"
instead of "columnHeadings". Your name
property has nothing to do with Enum internals.
To address the questions/concerns in the comments:
The enum's "builtin" (implicitly declared) valueOf(String name)
method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:
enum PropName { contents, columnHeadings, ...}
. This is obviously the most convenient.valueOf
, if you're really fond of naming conventions.valueOf
to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.The getElementById
method returns an Element object that you can use to interact with the element. If the element is not found, null
is returned. In case of an input element, the value
property of the object contains the string in the value attribute.
By using the fact that the &&
operator short circuits, and that both null
and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:
var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
alert("My input has a value!");
}
.disabledLink.disabled {pointer-events:none;}
That should do it hope I helped!
For the new emulator:
http://developer.android.com/tools/devices/emulator.html#extended
Basically, click on the three dots button in the emulator controls (to the right of the emulator) and it will open up a menu which will allow you to control the emulator including location
I was upgrading a legacy instance of jQuery UI and found that there was an extension to the dialog widget and it was simply using "center"
instead of the position
object. Implementing the position
object or removing the parameter entirely worked for me (because center is the default).
You could get the keys/values and index
<?php
$a = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>'value4',
'key5'=>'value5'
);
$keys = array_keys($a);
foreach(array_keys($keys) as $index ){
$current_key = current($keys); // or $current_key = $keys[$index];
$current_value = $a[$current_key]; // or $current_value = $a[$keys[$index]];
$next_key = next($keys);
$next_value = $a[$next_key] ?? null; // for php version >= 7.0
echo "{$index}: current = ({$current_key} => {$current_value}); next = ({$next_key} => {$next_value})\n";
}
result:
0: current = (key1 => value1); next = (key2 => value2)
1: current = (key2 => value2); next = (key3 => value3)
2: current = (key3 => value3); next = (key4 => value4)
3: current = (key4 => value4); next = (key5 => value5)
4: current = (key5 => value5); next = ( => )
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
You can use pd.to_datetime()
to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.
>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
Date Symbol
0 02/20/2015 A
1 01/15/2016 A
2 08/21/2015 A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
For future search, you can change the sort statement:
>>> df.sort_values(by='Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
Sed has up to nine remembered patterns but you need to use escaped parentheses to remember portions of the regular expression.
See here for examples and more detail
if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php
select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
from ...
or
select to_char(date_field,'mon dd, yyyy')
from ...
I did all of this in Windows 10 and still had a problem. In the end it turned out that the path to the Maven home folder was not exactly what was expected in many of these answers as it turned out to be /apache-maven-3.6.3-bin/apache-maven-3.6.3. Once I corrected this for both the system variables and the PATH variable, it worked. In short, if you have set the environment variables up as directed and it still won't work, I would double check to make sure the variables really point to the exact path to the Maven home folder and the bin folder on your machine.
I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command
Dism /Online /Cleanup-Image /RestoreHealth
Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.
Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
As pointed out by Aaron Hall's comment:
Since you can't subclass
NoneType
and sinceNone
is a singleton,isinstance
should not be used to detectNone
- instead you should do as the accepted answer says, and useis None
oris not None
.
Original Answer:
The simplest way however, without the extra line in addition to cardamom's answer is probably:
isinstance(x, type(None))
So how can I question a variable that is a NoneType? I need to use if method
Using isinstance()
does not require an is
within the if
-statement:
if isinstance(x, type(None)):
#do stuff
Additional information
You can also check for multiple types in one isinstance()
statement as mentioned in the documentation. Just write the types as a tuple.
isinstance(x, (type(None), bytes))
There are possible solutions here: http://forums.mysql.com/read.php?35,64808,254785#msg-254785 and here: http://forums.mysql.com/read.php?35,23138,254786#msg-254786
All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.
Finally, more or less by accident, I bumped into the file:
...path_to_XAMPP\XAMPP...\mysql\bin\mysqld-debug.exe
Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.
resolve the url like this href="<%=ResolveUrl("~/favicon.ico")%>"
Regarding #2, according to the JSR-330 spec:
This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.
So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.
@Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.Name.ToString(),
Selected = "select" == item.RecordID.ToString()
}))
there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.
One way is to setup a chroot environment. Debian has a number of tools for that, for example debootstrap
left:auto;
This will default the left
back to the browser default.
So if you have your Markup/CSS as:
<div class="myClass"></div>
.myClass
{
position:absolute;
left:0;
}
When setting RTL, you could change to:
<div class="myClass rtl"></div>
.myClass
{
position:absolute;
left:0;
}
.myClass.rtl
{
left:auto;
right:0;
}
It works for me in Oxygen.
1) Go to Help > Eclipse Marketplace... and search for "DLTK". You'll find something like "Shell Script (DLTK) 5.8.0". Install it and reboot Eclipse.
(Or drag'n'drop "Install" button from this web page to your Eclipse: https://marketplace.eclipse.org/content/shell-script-dltk)
2) Right-click on the shell/batch file in Project Explorer > Open With > Other... and select Shell Script Editor. You can also associate the editor with all files of that extension.
You can use GROUP BY SalesOrderID
. The difference is, with GROUP BY you can only have the aggregated values for the columns that are not included in GROUP BY.
In contrast, using windowed aggregate functions instead of GROUP BY, you can retrieve both aggregated and non-aggregated values. That is, although you are not doing that in your example query, you could retrieve both individual OrderQty
values and their sums, counts, averages etc. over groups of same SalesOrderID
s.
Here's a practical example of why windowed aggregates are great. Suppose you need to calculate what percent of a total every value is. Without windowed aggregates you'd have to first derive a list of aggregated values and then join it back to the original rowset, i.e. like this:
SELECT
orig.[Partition],
orig.Value,
orig.Value * 100.0 / agg.TotalValue AS ValuePercent
FROM OriginalRowset orig
INNER JOIN (
SELECT
[Partition],
SUM(Value) AS TotalValue
FROM OriginalRowset
GROUP BY [Partition]
) agg ON orig.[Partition] = agg.[Partition]
Now look how you can do the same with a windowed aggregate:
SELECT
[Partition],
Value,
Value * 100.0 / SUM(Value) OVER (PARTITION BY [Partition]) AS ValuePercent
FROM OriginalRowset orig
Much easier and cleaner, isn't it?
Follow the steps below:
1) Select your VM Instance. Go to Settings->Storage
2) Under the storage tree select the default image or "Empty"
(which ever is present)
3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file
"
4) Browse and select the image file(iso or what ever format) from the system
5) Select OK.
Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
For Windows user, please note to use "
instead of '
Also added -f
to force the command if another backup is already there.
git filter-branch -f --tree-filter "rm -rf FOLDERNAME" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo FOLDERNAME/ >> .gitignore
git add .gitignore
git commit -m "Removing FOLDERNAME from git history"
git gc
git push origin master --force
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.
For example, if you have a string class with constructor String(const char* s)
, that's probably exactly what you want. You can pass a const char*
to a function expecting a String
, and the compiler will automatically construct a temporary String
object for you.
On the other hand, if you have a buffer class whose constructor Buffer(int size)
takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn int
s into Buffer
s. To prevent that, you declare the constructor with the explicit
keyword:
class Buffer { explicit Buffer(int size); ... }
That way,
void useBuffer(Buffer& buf);
useBuffer(4);
becomes a compile-time error. If you want to pass a temporary Buffer
object, you have to do so explicitly:
useBuffer(Buffer(4));
In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit
keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit
to prevent the compiler from surprising you with unexpected conversions.
After some research I was able to find a good solution for converting UTC to local time, have a a look at the fiddle. Hope it help
https://jsfiddle.net/way2ajay19/2kramzng/20/
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
{{date | date:'yyyy-mm-dd hh:mm:ss' }}
</div>
<script>
function MyCtrl($scope) {
$scope.d = "2017-07-21 19:47:00";
$scope.d = $scope.d.replace(" ", 'T') + 'Z';
$scope.date = new Date($scope.d);
}
</script>
For me, this simple trick worked:
I actually enabled and disabled the listed USB Adapter for android in the device manager (Control Panel -> Hardware & Sound -> Device Manager). And holy moly it's working! :D
In your LocationListener
, implement onProviderEnabled
and onProviderDisabled
event handlers. When you call requestLocationUpdates(...)
, if GPS is disabled on the phone, onProviderDisabled
will be called; if user enables GPS, onProviderEnabled
will be called.
X=foo
Y=X
eval "Z=\$$Y"
sets Z to "foo"
Take care using eval
since this may allow accidential excution of code through values in ${Y}
. This may cause harm through code injection.
For example
Y="\`touch /tmp/eval-is-evil\`"
would create /tmp/eval-is-evil
. This could also be some rm -rf /
, of course.
word
is on the stack and goes out of scope as soon as getStr()
returns. You are invoking undefined behavior.
The full URL is available as request.url
, and the query string is available as request.query_string.decode()
.
Here's an example:
from flask import request
@app.route('/adhoc_test/')
def adhoc_test():
return request.query_string
To access an individual known param passed in the query string, you can use request.args.get('param')
. This is the "right" way to do it, as far as I know.
ETA: Before you go further, you should ask yourself why you want the query string. I've never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.
Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:
git push origin HEAD: <My-remote-branch>
Then
git checkout <My-remote-branch>
Then
git pull
I finally got my all changes in my branch that I made in detach HEAD.
One follow up to this. I had installed SQL Server 2014 with only Windows Authentication. After enabling Mixed Mode, I couldn't log in with a SQL user and got the same error message as the original poster. I verified that named pipes were enabled but still couldn't log in after several restarts. Using 127.0.0.1 instead of the hostname allowed me to log in, but interestingly, required a password reset prompt on first login:
Once I reset the password the account worked. What's odd, is I specifically disabled password policy and expiration.
I have a solution. Check this:
Error
<link href="assets/css/bootstrap.min.css" rel="text/css" type="stylesheet">
Correct
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
For Xamarin Users:
[Activity(MainLauncher = true,
ScreenOrientation = ScreenOrientation.Portrait,
WindowSoftInputMode = SoftInput.StateHidden)] //SoftInput.StateHidden - disables keyboard autopop
If dump file contains:
CREATE DATABASE mydatabasename;
USE mydatabasename;
You may just use in CLI:
mysql -uroot –pmypassword < mydatabase.sql
It works.
Extending answer of @MichaelLaCroix when a scenario is that the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.
In the case of <Filters />
and <TopBar />
don't have any of the above relationship, a simple global emitter could be used like this:
componentDidMount
- Subscribe to event
componentWillUnmount
- Unsubscribe from event
EventSystem.js
class EventSystem{
constructor() {
this.queue = {};
this.maxNamespaceSize = 50;
}
publish(/** namespace **/ /** arguments **/) {
if(arguments.length < 1) {
throw "Invalid namespace to publish";
}
var namespace = arguments[0];
var queue = this.queue[namespace];
if (typeof queue === 'undefined' || queue.length < 1) {
console.log('did not find queue for %s', namespace);
return false;
}
var valueArgs = Array.prototype.slice.call(arguments);
valueArgs.shift(); // remove namespace value from value args
queue.forEach(function(callback) {
callback.apply(null, valueArgs);
});
return true;
}
subscribe(/** namespace **/ /** callback **/) {
const namespace = arguments[0];
if(!namespace) throw "Invalid namespace";
const callback = arguments[arguments.length - 1];
if(typeof callback !== 'function') throw "Invalid callback method";
if (typeof this.queue[namespace] === 'undefined') {
this.queue[namespace] = [];
}
const queue = this.queue[namespace];
if(queue.length === this.maxNamespaceSize) {
console.warn('Shifting first element in queue: `%s` since it reached max namespace queue count : %d', namespace, this.maxNamespaceSize);
queue.shift();
}
// Check if this callback already exists for this namespace
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
throw ("The exact same callback exists on this namespace: " + namespace);
}
}
this.queue[namespace].push(callback);
return [namespace, callback];
}
unsubscribe(/** array or topic, method **/) {
let namespace;
let callback;
if(arguments.length === 1) {
let arg = arguments[0];
if(!arg || !Array.isArray(arg)) throw "Unsubscribe argument must be an array";
namespace = arg[0];
callback = arg[1];
}
else if(arguments.length === 2) {
namespace = arguments[0];
callback = arguments[1];
}
if(!namespace || typeof callback !== 'function') throw "Namespace must exist or callback must be a function";
const queue = this.queue[namespace];
if(queue) {
for(var i = 0; i < queue.length; i++) {
if(queue[i] === callback) {
queue.splice(i, 1); // only unique callbacks can be pushed to same namespace queue
return;
}
}
}
}
setNamespaceSize(size) {
if(!this.isNumber(size)) throw "Queue size must be a number";
this.maxNamespaceSize = size;
return true;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
NotificationComponent.js
class NotificationComponent extends React.Component {
getInitialState() {
return {
// optional. see alternative below
subscriber: null
};
}
errorHandler() {
const topic = arguments[0];
const label = arguments[1];
console.log('Topic %s label %s', topic, label);
}
componentDidMount() {
var subscriber = EventSystem.subscribe('error.http', this.errorHandler);
this.state.subscriber = subscriber;
}
componentWillUnmount() {
EventSystem.unsubscribe('error.http', this.errorHandler);
// alternatively
// EventSystem.unsubscribe(this.state.subscriber);
}
render() {
}
}
Another possibility I came up with, inspired by using grep, is:
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
It doesn't need to save an extra file, so I prefer this method.
I apologize for promoting myself, but I have a jQuery plugin to launch native apps from web links https://github.com/eusonlito/jquery.applink
You can use it easy:
<script>
$('a[data-applink]').applink();
</script>
<a href="https://facebook.com/me" data-applink="fb://profile">My Facebook Profile</a>
I did trial and error and got the conclusion that, you only have to use either of both @XMLElement
or @XmlAccessorType(XmlAccessType.FIELD)
.
When to use which?
case 1 : If your field names and element name you want to use in xml file are different then you have to use @XMLElement(name="elementName")
. As this will bind fields with that element name and display in XML file.
case 2 : If fields names and respective element name in xml both are same then you can simply use @XmlAccessorType(XmlAccessType.FIELD)
If the class is declared static, all of the members must be static too.
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
Are you sure you want your employee class to be static? You almost certainly don't want that behaviour. You'd probably be better off removing the static constraint from the class and the members.
In Python 3.8, we can use threading.excepthook to hook the uncaught exceptions in all the child threads! For example,
threading.excepthook = thread_exception_handler
You're looking for iotop
(assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.
This is the simplest method. Only one step.
It has significant impact on speed. In my case, time taken for a training step almost halved.
The Response
API consumes a (immutable) Blob
from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer
, and here's a demonstration of it.
var blob = GetABlobSomehow();
// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
await new Response(blob).arrayBuffer(); //=> <ArrayBuffer>
alternatively you could use this:
new Response(blob).arrayBuffer()
.then(/* <function> */);
Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)
While in insert mode, you can use Ctrl-R {register}
, where register can be:
+
for the clipboard,*
for the X clipboard (last selected text in X), "
for the unnamed register (last delete or yank in Vim),:h registers
).Ctrl-R {register}
inserts the text as if it were typed.
Ctrl-R Ctrl-O {register}
inserts the text with the original indentation.
Ctrl-R Ctrl-P {register}
inserts the text and auto-indents it.
Ctrl-O
can be used to run any normal mode command before returning to insert mode, so
Ctrl-O "+p
can also be used, for example.
For more information, view the documentation with :h i_ctrl-r
I have this code:
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() { _x000D_
document.getElementById("boton").style.display = 'none';_x000D_
document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando..."; _x000D_
return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
<input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
it depends on how you trigger the event. the key you are looking is textbox.clientid.
x.aspx code
<script type="text/javascript">
function disable_textbox(tid) {
var mytextbox = document.getElementById(tid);
mytextbox.disabled=false
}
</script>
code behind x.aspx.cs
string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID ");</script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
You can validate point a and b compactly by doing something like the following:
#!/bin/sh
MYVAL=$(echo ${1} | awk '/^[0-9]+$/')
MYVAL=${MYVAL:?"Usage - testparms <number>"}
echo ${MYVAL}
Which gives us ...
$ ./testparams.sh
Usage - testparms <number>
$ ./testparams.sh 1234
1234
$ ./testparams.sh abcd
Usage - testparms <number>
This method should work fine in sh.
int wantedPosition = 25; // Whatever position you're looking for
int firstPosition = linearLayoutManager.findFirstVisibleItemPosition(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
if (wantedChild < 0 || wantedChild >= linearLayoutManager.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
return;
}
View wantedView = linearLayoutManager.getChildAt(wantedChild);
mlayoutOver =(LinearLayout)wantedView.findViewById(R.id.layout_over);
mlayoutPopup = (LinearLayout)wantedView.findViewById(R.id.layout_popup);
mlayoutOver.setVisibility(View.INVISIBLE);
mlayoutPopup.setVisibility(View.VISIBLE);
For RecycleView please use this code
How about:
/resource/
(not /resource
)
/resource/
means it's a folder contains something called "resource", it's a "resouce" folder.
And also I think the naming convention of database tables is the same, for example, a table called 'user' is a "user table", it contains something called "user".
In addition to others' proposals, there is another option to handle that issue.
If your application should behave the same in case of lack of "href
" attribute, as in case of it being empty, just replace this:
var theHref = $(obj.mainImg_select).attr('href');
with this:
var theHref = $(obj.mainImg_select).attr('href') || '';
which will treat empty string (''
) as the default, if the attribute has not been found.
But it really depends, on how you want to handle undefined "href
" attribute. This answer assumes you will want to handle it as if it was empty string.
Fore readability sake in the code use an array and implode it to a comma separated string:-
$recipients = array(
"[email protected]",
// more emails
);
$email_to = implode(',', $recipients); // your email address
$email_subject = "Contact Form Message"; // email subject line
$thankyou = "thankyou.htm"; // thank you page
You can use animate insted of show/hide
Something like this:
function switch_tabs(obj)
{
$('.tab-content').animate({opacity:0},3000);
$('.tabs a').removeClass("selected");
var id = obj.attr("rel");
$('#'+id).animate({opacity:1},3000);
obj.addClass("selected");
}
sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1
SOAP Web services:
RestWeb services:
Using the scatter
method of the matplotlib.pyplot
module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1
rather than numpoints=1
in the legend call to have only one point for each legend entry.
In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).
import matplotlib.pyplot as plt
from numpy.random import random
colors = ['b', 'c', 'y', 'm', 'r']
lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])
plt.legend((lo, ll, l, a, h, hh, ho),
('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
scatterpoints=1,
loc='lower left',
ncol=3,
fontsize=8)
plt.show()
To plot a scatter in 3D, use the plot
method, as the legend does not support Patch3DCollection
as is returned by the scatter
method of an Axes3D
instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle
and marker
parameters.
import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D
colors=['b', 'c', 'y', 'm', 'r']
ax = plt.subplot(111, projection='3d')
ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')
plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))
plt.show()
use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable
import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64)
json.dumps(arr,cls=NumpyEncoder)
As Joey pointed out, TortoiseSVN has a commandline syntax of its own. Unfortunately it is quite ugly, if you are used to svn
commands, and it ignores the current working directory, thus it is not very usable - except for scripting.
I have created a little Python program (tsvn
) which mimics the svn
commandline syntax as closely as possible and calls TortoiseSVN accordingly. Thus, the difference between calling the normal commandline tools and calling TortoiseSVN is reduced to a little letter t
at the beginning.
My tsvn
program is not yet complete but already useful. It can be found in the cheeseshop (https://pypi.python.org/pypi/tsvn/)
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
There is actually a really simple way to do this when you just want to print
the output:
import subprocess
import sys
def execute(command):
subprocess.check_call(command, stdout=sys.stdout, stderr=subprocess.STDOUT)
Here we're simply pointing the subprocess to our own stdout
, and using existing succeed or exception api.
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Webspeed and SpeedScript.. Just terrible, no explanation :)
Add the following function in your code with its callback.
# Starting of the function
def divide(number_one, number_two, decimal_place = 4):
quotient = number_one/number_two
remainder = number_one % number_two
if remainder != 0:
quotient_str = str(quotient)
for loop in range(0, decimal_place):
if loop == 0:
quotient_str += "."
surplus_quotient = (remainder * 10) / number_two
quotient_str += str(surplus_quotient)
remainder = (remainder * 10) % number_two
if remainder == 0:
break
return float(quotient_str)
else:
return quotient
#Ending of the function
# Calling back the above function
# Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
divide(1, 7, 10) # Output : 0.1428571428
# OR
divide(1, 7) # Output : 0.1428
This function works on the basis of "Euclid Division Algorithm". This function is very useful if you don't want to import any external header files in your project.
Syntex : divide([divident], [divisor], [decimal place(optional))
Code : divide(1, 7, 10)
OR divide(1, 7)
Comment below for any queries.
The background color of the Visual Studio text editor in a Theme Editor is accessed by:
Text Editor ? Plain Text ? Background
Since Chrome 32 you have the CSS media
option in the Screen
section of the drawer Emulation
tab.
Just enable it, select print
as the target media type, and - behold - your page is rendered [almost] the way it will be printed.
Use Esc to bring up the drawer if it's not visible.
If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:
It is assumed that you are running with publish command like below.
docker run -it -p 8080:8080 demo
With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.
Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost
how many records do you have? are there any indexes on the table? try this:
;with a as (
select distinct Status
from MyTable
where MemberType=6
)
select count(Status)
from a
Check out our jQuery-ClearSearch plugin. It's a configurable jQuery plugin - adapting it to your needs by styling the input field is straightforward. Just use it as follows:
<input class="clearable" type="text" placeholder="search">
<script type="text/javascript">
$('.clearable').clearSearch();
</script>
? Example: http://jsfiddle.net/wldaunfr/FERw3/
I had this problem and it turns out I had a a second node_modules folder in my project that wasn't supposed to be there :-(
try something like :
var focusout = false;
$("#Button1").click(function () {
if (focusout == true) {
focusout = false;
return;
}
else {
GetInfo();
}
});
$("#Text1").focusout(function () {
focusout = true;
GetInfo();
});
i think in the svn browser in tortoisesvn you can just drag it from one place to another.
You can use the server variables for this, for example $_SERVER['REQUEST_URI']
, or even better: $_SERVER['PHP_SELF']
.
As mentioned by others in the comments, a really simple solution to this issue is to declare the database 'host' within the database configuration. Adding this answer just to make it a little more clear for anyone reading this.
In a Ruby on Rails app for example, edit /config/database.yml:
development:
adapter: postgresql
encoding: unicode
database: database_name
pool: 5
host: localhost
Note: the last line added to specify the host. Prior to updating to Yosemite I never needed to specify the host in this way.
Hope this helps someone.
Cheers
You can traverse the offsetParent
up to the top level of the DOM.
function getOffsetLeft( elem )
{
var offsetLeft = 0;
do {
if ( !isNaN( elem.offsetLeft ) )
{
offsetLeft += elem.offsetLeft;
}
} while( elem = elem.offsetParent );
return offsetLeft;
}
You need to separate the arguments from the file path:
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"
Another option that may ease the syntax using the File parameter and positional parameters:
powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"
new(): Specifying the new() constraint means type T must use a parameterless constructor, so an object can be instantiated from it - see Default constructors.
class: Means T must be a reference type so it can't be an int, float, double, DateTime or other struct (value type).
public void MakeCars()
{
//This won't compile as researchEngine doesn't have a public constructor and so can't be instantiated.
CarFactory<ResearchEngine> researchLine = new CarFactory<ResearchEngine>();
var researchEngine = researchLine.MakeEngine();
//Can instantiate new object of class with default public constructor
CarFactory<ProductionEngine> productionLine = new CarFactory<ProductionEngine>();
var productionEngine = productionLine.MakeEngine();
}
public class ProductionEngine { }
public class ResearchEngine
{
private ResearchEngine() { }
}
public class CarFactory<TEngine> where TEngine : class, new()
{
public TEngine MakeEngine()
{
return new TEngine();
}
}
Use extension methods. Replace NameOfContext with the name of your object context.
public static class Extensions{
public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country") ;
}
public static Company CompanyById(this NameOfContext context, int companyID){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country")
.FirstOrDefault(c => c.Id == companyID) ;
}
}
Then your code becomes
Company company =
context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);
//or if you want even more
Company company =
context.CompanyById(companyID);
You have done it correctly. The pull request will automatically update. The process is:
The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)
With Joda-Time , maybe it's better:
LocalDate dateStart = new LocalDate("2012-01-15");
LocalDate dateEnd = new LocalDate("2012-05-23");
// day by day:
while(dateStart.isBefore(dateEnd)){
System.out.println(dateStart);
dateStart = dateStart.plusDays(1);
}
It's my solution.... very easy :)
If you are using a mac and sublime text 3, this is what you do.
Go to your /Packages/User/
and create a file called Python.sublime-settings
.
Typically /Packages/User
is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings
if you are using mac os x.
Then you put this in the Python.sublime-settings
.
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.
This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.
I had the same issue. Tried all the solutions mentioned here but nothing worked. So i rebooted my device and suddenly the issue solved.
If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:
Super Super compact
var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }
All 3 possible combinations together (ES6)
var t
window.onresize = () => {
resizing(this, this.innerWidth, this.innerHeight) //1
if (typeof t == 'undefined') resStarted() //2
clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}
function resizing(target, w, h) {
console.log(`Youre resizing: width ${w} height ${h}`)
}
function resStarted() {
console.log('Resize Started')
}
function resEnded() {
console.log('Resize Ended')
}
to show which conda env a notebook is using just type in a cell:
!conda info
if you have grep, a more direct way:
!conda info | grep 'active env'
For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1)
geometrical lines, there is the below minimal solution (uses the shapely
module, but can be easily modified not to):
from shapely.geometry import LineString
import numpy as np
ninety_degrees_rad = 90.0 * np.pi / 180.0
def angle_between(line1, line2):
coords_1 = line1.coords
coords_2 = line2.coords
line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0
# Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
if line1_vertical and line2_vertical:
# Perpendicular vertical lines
return 0.0
if line1_vertical or line2_vertical:
# 90° - angle of non-vertical line
non_vertical_line = line2 if line1_vertical else line1
return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))
m1 = slope(line1)
m2 = slope(line2)
return np.arctan((m1 - m2)/(1 + m1*m2))
def slope(line):
# Assignments made purely for readability. One could opt to just one-line return them
x0 = line.coords[0][0]
y0 = line.coords[0][1]
x1 = line.coords[1][0]
y1 = line.coords[1][1]
return (y1 - y0) / (x1 - x0)
And the use would be
>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0
Mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option.
In case your php version is 7.0:
sudo apt-get install php7.0-mbstring
sudo service apache2 restart
In case your php version is 5.6:
sudo apt-get install php5.6-mbstring
sudo service apache2 restart
Yes, you can do this.
The VM registration process should finish with the cloned VM usable in the new vCenter!
Good luck!
Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow()
.
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
I think your problem was a typo:
<a th:href="@{'/category/edit/' + ${category.id}}">view</a>
You are using category.id
, but in your code is idCategory
, as Eddie already pointed out.
This would work for you:
<a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
Try adding ?wmode=transparent
to the end of the URL. Worked for me.
I don't know if I am late or out of scope but in my opinion I could do it like:
String orgName = "anyParamValue";
Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");
q.setParameter("orgName", orgName);
You can also add 'active' class to the selected item.
$('.dropdown').on( 'click', '.dropdown-menu li a', function() {
var target = $(this).html();
//Adds active class to selected item
$(this).parents('.dropdown-menu').find('li').removeClass('active');
$(this).parent('li').addClass('active');
//Displays selected text on dropdown-toggle button
$(this).parents('.dropdown').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
});
See the jsfiddle example
You can use either lower or upper function on both sides of the where condition
MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]
I'm using this to initialise the reusable custom views I have.
Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.
Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}
Normally, in the TopArea.xib
, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib
, you can drag controls to those outlets.
Don't forget that in TopArea.xib
, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)
I fixed this on my PC, on my environment iReport was iReport-5.1.0 , both jdk 7 and jdk 8 had been installed.
but iReport did not load
fix:- 1. Find the iReport.conf //C:\Program Files (x86)\Jaspersoft\iReport-5.1.0\etc
Open it on text editor
copy your jdk installation path //C:\Program Files (x86)\Java\jdk1.8.0_60
add jdkhome= into the ireport.conf file jdkhome="C:/Program Files (x86)/Java/jdk1.8.0_60"
Now iReport will work
6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc
from
DateTime dt = DateTime.Now;
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);
Use os.path.getsize(path)
which will
Return the size, in bytes, of path. Raise
OSError
if the file does not exist or is inaccessible.
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')
Or use os.stat(path).st_size
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
Or use Path(path).stat().st_size
(Python 3.4+)
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
use the className
property:
document.getElementById('your_element_s_id').className = 'cssClass';
I tried to store properties by using objc_getAssociatedObject, objc_setAssociatedObject, without any luck. My goal was create extension for UITextField, to validate text input characters length. Following code works fine for me. Hope this will help someone.
private var _min: Int?
private var _max: Int?
extension UITextField {
@IBInspectable var minLength: Int {
get {
return _min ?? 0
}
set {
_min = newValue
}
}
@IBInspectable var maxLength: Int {
get {
return _max ?? 1000
}
set {
_max = newValue
}
}
func validation() -> (valid: Bool, error: String) {
var valid: Bool = true
var error: String = ""
guard let text = self.text else { return (true, "") }
if text.characters.count < minLength {
valid = false
error = "Textfield should contain at least \(minLength) characters"
}
if text.characters.count > maxLength {
valid = false
error = "Textfield should not contain more then \(maxLength) characters"
}
if (text.characters.count < minLength) && (text.characters.count > maxLength) {
valid = false
error = "Textfield should contain at least \(minLength) characters\n"
error = "Textfield should not contain more then \(maxLength) characters"
}
return (valid, error)
}
}
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
2 from decimal numbering system in binary is as follows
10
now if you do
2 << 11
it would be , 11 zeros would be padded on the right side
1000000000000
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension [..]
left shifting results in multiplication by 2 (*2) in terms or arithmetic
For example
2 in binary 10
, if you do <<1
that would be 100
which is 4
4 in binary 100
, if you do <<1
that would be 1000
which is 8
Also See
The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion
(INNER) JOIN: Returns records that have matching values in both tables.
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table.
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table.
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
For example, lets suppose we have two table with following records:
Table A
id firstname lastname
___________________________
1 Ram Thapa
2 sam Koirala
3 abc xyz
6 sruthy abc
Table B
id2 place
_____________
1 Nepal
2 USA
3 Lumbini
5 Kathmandu
Inner Join
Note: It give the intersection of two table.
Syntax
SELECT column_name FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your sample table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA INNER JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
_____________________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
Left Join
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your sample table
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
sruthy abc Null
Right Join
Note:will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your samole table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA RIGHT JOIN TableB ON TableA.id = TableB.id2;
Result will bw:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
Null Null Kathmandu
Full Join
Note : It is same as union operation, it will return all selected values from both tables.
Syntax:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
Apply it in your samp[le table:
SELECT TableA.firstName,TableA.lastName,TableB.Place FROM TableA FULL JOIN TableB ON TableA.id = TableB.id2;
Result will be:
firstName lastName Place
______________________________
Ram Thapa Nepal
sam Koirala USA
abc xyz Lumbini
sruthy abc Null
Null Null Kathmandu
Some facts
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Find More at w3schools
Another easy way to clean builds is by adding the Discard Old Plugin at the end of your jobs. Set a maximum number of builds to save and then run the job again:
https://wiki.jenkins-ci.org/display/JENKINS/Discard+Old+Build+plugin
Here's another view using collections.abc
. This view may be useful the second time around or later.
From collections.abc
we can see the following hierarchy:
builtins.object
Iterable
Iterator
Generator
i.e. Generator is derived from Iterator is derived from Iterable is derived from the base object.
Hence,
[1, 2, 3]
and range(10)
are iterables, but not iterators. x = iter([1, 2, 3])
is an iterator and an iterable.iter()
on an iterator or a generator returns itself. Thus, if it
is an iterator, then iter(it) is it
is True.[2 * x for x in nums]
or a for loop like for x in nums:
, acts as though iter()
is called on the iterable (nums
) and then iterates over nums
using that iterator. Hence, all of the following are functionally equivalent (with, say, nums=[1, 2, 3]
):
for x in nums:
for x in iter(nums):
for x in iter(iter(nums))
:for x in iter(iter(iter(iter(iter(nums))))):
I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create()
but don't close the FileStream
that it returns.
Doing it that way is unnecessary, StreamWriter
already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:
string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
using (StreamWriter sw = new StreamWriter(filePath, true)) {
//write my text
}
Which uses this StreamWriter
constructor.
Update: Nowadays I would use JSON.
I also prefer to go with serialization to file. XML files fits mostly all requirements. You can use the ApplicationSettings
build in but those have some restrictions and a defined but (for me) very strange behavior where they stored. I used them a lot and they work. But if you want to have full control how and where they stored I use another approach.
MySettings
Advantages:
Disadvantages: - You have to think about where to store your settings files. (But you can just use your installation folder)
Here is a simple example (not tested)-
public class MySettings
{
public string Setting1 { get; set; }
public List<string> Setting2 { get; set; }
public void Save(string filename)
{
using (StreamWriter sw = new StreamWriter(filename))
{
XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
xmls.Serialize(sw, this);
}
}
public MySettings Read(string filename)
{
using (StreamReader sw = new StreamReader(filename))
{
XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
return xmls.Deserialize(sw) as MySettings;
}
}
}
And here is how to use it. It's possible to load default values or override them with the user's settings by just checking if user settings exist:
public class MyApplicationLogic
{
public const string UserSettingsFilename = "settings.xml";
public string _DefaultSettingspath =
Assembly.GetEntryAssembly().Location +
"\\Settings\\" + UserSettingsFilename;
public string _UserSettingsPath =
Assembly.GetEntryAssembly().Location +
"\\Settings\\UserSettings\\" +
UserSettingsFilename;
public MyApplicationLogic()
{
// if default settings exist
if (File.Exists(_UserSettingsPath))
this.Settings = Settings.Read(_UserSettingsPath);
else
this.Settings = Settings.Read(_DefaultSettingspath);
}
public MySettings Settings { get; private set; }
public void SaveUserSettings()
{
Settings.Save(_UserSettingsPath);
}
}
maybe someone get's inspired by this approach. This is how I do it now for many years and I'm quite happy with that.
I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
Which you can then use as
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)
I received a IllegalMonitorStateException
while trying to wake up a thread in / from a different class
/ thread. In java 8
you can use the lock
features of the new Concurrency API instead of synchronized
functions.
I was already storing objects for asynchronous
websocket transactions in a WeakHashMap
. The solution in my case was to also store a lock
object in a ConcurrentHashMap
for synchronous
replies. Note the condition.await
(not .wait
).
To handle the multi threading I used a Executors.newCachedThreadPool()
to create a thread pool.
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
It's wrong. Use a span.
Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64
But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value
C:\Program Files\Java\jre1.8.0_171\bin\server
for Java's path, and put it on top of the Path items.
This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.
C:\Program Files\Java\jre1.8.0_181\bin\server
Float everything.
If you have a floated div
inside a non-floated div
, everything gets all screwy. That's why most CSS frameworks like Blueprint and 960.gs all use floated containers and divs
.
To answer your particular question,
<div class="container">
<!--
.container {
float: left;
width: 100%;
}
-->
<div class="sidebar">
<!--
.sidebar {
float: left;
width: 20%;
height: auto;
}
-->
</div>
<div class="content">
<!--
.sidebar {
float: left;
width: 20%;
height: auto;
}
-->
</div>
</div>
should work just fine, as long as you float:left;
all of your <div>
s.
Although there are already excellent answers are provided by users such as encouraging use of GSON etc. I would like to suggest use of org.json. It includes most of GSON functionalities. It also allows you to pass json string as an argument to it's JSONObject and it will take care of rest e.g:
JSONObject json = new JSONObject("some random json string");
This functionality make it my personal favorite.
In the very right bottom corner, left to the smiley there was the icon saying "Plain Text". When you click it, the menu with all languages appears where you can choose your desired language.
Most of the propertis is showing invalid when I am going to apply such as
page-break-inside: avoid-column;
break-inside: avoid-column;
-webkit-column-break-inside: avoid-column;
and when I am checking is responsiveness it not working fine for me...
Anyone can provide me a solution for the same...
I used the built-in rstrip function to do it like follow:
string = "test.com"
suffix = ".com"
newstring = string.rstrip(suffix)
print(newstring)
test
Swift 4 - GET request
var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let jsonDecoder = JSONDecoder()
let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
print(responseModel)
} catch {
print("JSON Serialization error")
}
}).resume()
Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.
You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.
My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:
SELECT Table.date
FROM Table
WHERE date > current_date - interval '10 day';
Demonstrated here (you should be able to run this on any Postgres db):
SELECT DISTINCT current_date,
current_date - interval '10' day,
current_date - interval '10 days'
FROM pg_language;
Result:
2013-03-01 2013-03-01 00:00:00 2013-02-19 00:00:00
.cut_text {_x000D_
white-space: nowrap; _x000D_
width: 200px; _x000D_
border: 1px solid #000000;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<div class="cut_text">_x000D_
_x000D_
very long text_x000D_
</div>
_x000D_
You don't have any error in either of your queries. My guess is the following:
Using the time.h library, try something like this:
long start_time, end_time, elapsed;
start_time = clock();
// Do something
end_time = clock();
elapsed = (end_time - start_time) / CLOCKS_PER_SEC * 1000;
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
Here is also the code to handle the result:
def foo (a):
x=a
y=a*2
return (x,y)
(x,y) = foo(50)
Typically, no.
Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.
For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".
As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.
You can do this in any program other than Explorer
, e.g. Notepad
, cmd.exe
etc.
You just can't do it in Explorer, and Raymond Chen has offered an explanation as to why not.
Try This!
I have added 5 circles you can add more. And instead of RaisedButton use InkResponse.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(home: new ExampleWidget()));
}
class ExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget bigCircle = new Container(
width: 300.0,
height: 300.0,
decoration: new BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
);
return new Material(
color: Colors.black,
child: new Center(
child: new Stack(
children: <Widget>[
bigCircle,
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.favorite_border),
top: 10.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.timer),
top: 120.0,
left: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.place),
top: 120.0,
right: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.local_pizza),
top: 240.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.satellite),
top: 120.0,
left: 130.0,
),
],
),
),
);
}
}
class CircleButton extends StatelessWidget {
final GestureTapCallback onTap;
final IconData iconData;
const CircleButton({Key key, this.onTap, this.iconData}) : super(key: key);
@override
Widget build(BuildContext context) {
double size = 50.0;
return new InkResponse(
onTap: onTap,
child: new Container(
width: size,
height: size,
decoration: new BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: new Icon(
iconData,
color: Colors.black,
),
),
);
}
}
I am willing to bet some of my reputation that there is no such thing.
Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.
Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.
Check these steps.
You can add parameters to the request from a middleware by doing:
public function handle($request, Closure $next)
{
$request->route()->setParameter('foo', 'bar');
return $next($request);
}
Have you tried escaping the dot? like this:
String[] words = line.split("\\.");
To change the title for each different activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pizza);
setTitle(getResources().getText(R.string.title));
}
'JavaType' works !!
I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution.
Code:
JsonMarshallerUnmarshaller<T> {
T targetClass;
public ArrayList<T> unmarshal(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig()
.withAnnotationIntrospector(introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(
ArrayList.class,
targetclass.getClass());
try {
Class c1 = this.targetclass.getClass();
Class c2 = this.targetclass1.getClass();
ArrayList<T> temp = (ArrayList<T>)
mapper.readValue(jsonString, type);
return temp ;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
Use:
UPDATE table1
SET col1 = othertable.col2,
col2 = othertable.col3
FROM othertable
WHERE othertable.col1 = 123;
Use:
INSERT INTO table1 (col1, col2)
SELECT col1, col2
FROM othertable
You don't need the VALUES
syntax if you are using a SELECT to populate the INSERT values.
Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.
Another solution: You can use percentage units for margins as well as sizes. For example:
.fullWidthPlusMargin {
width: 98%;
margin: 1%;
}
The main issue here is that the margins will increase/decrease slightly with the size of the parent element. Presumably the functionality you would prefer is for the margins to stay constant and the child element to grow/shrink to fill changes in spacing. So, depending on how tight you need your display to be, that could be problematic. (I'd also go for a smaller margin, like 0.3%).
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
I have tried all of the answers above but none of them work. After so many attempts I've finally found a reliable way to set WKWebview cookie.
First you have to create an instance of WKProcessPool and set it to the WKWebViewConfiguration that is to be used to initialize the WkWebview itself:
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
Setting WKProcessPool is the most important step here. WKWebview makes use of process isolation - which means it runs on a different process than the process of your app. This can sometimes cause conflict and prevent your cookie from being synced properly with the WKWebview.
Now let's look at the definition of WKProcessPool
The process pool associated with a web view is specified by its web view configuration. Each web view is given its own Web Content process until an implementation-defined process limit is reached; after that, web views with the same process pool end up sharing Web Content processes.
Pay attention to the last sentence if you plan to use the same WKWebview for subsequence requests
web views with the same process pool end up sharing Web Content processes
what I means is that if you don't use the same instance of WKProcessPool each time you configure a WKWebView for the same domain (maybe you have a VC A that contains a WKWebView and you want to create different instances of VC A in different places), there can be conflict setting cookies. To solve the problem, after the first creation of the WKProcessPool for a WKWebView that loads domain B, I save it in a singleton and use that same WKProcessPool every time I have to create a WKWebView that loads the same domain B
private lazy var mainWebView: WKWebView = {
let webConfiguration = WKWebViewConfiguration()
if Enviroment.shared.processPool == nil {
Enviroment.shared.processPool = WKProcessPool()
}
webConfiguration.processPool = Enviroment.shared.processPool!
webConfiguration.processPool = WKProcessPool()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
return webView
}()
After the initialization process, you can load an URLRequest inside the completion block of httpCookieStore.setCookie
. Here, you have to attach the cookie to the request header otherwise it won't work.
P/s: I stole the extension from the fantastic answer above by Dan Loewenherz
mainWebView.configuration.websiteDataStore.httpCookieStore.setCookie(your_cookie) {
self.mainWebView.load(your_request, with: [your_cookie])
}
extension WKWebView {
func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
var request = request
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for (name, value) in headers {
request.addValue(value, forHTTPHeaderField: name)
}
load(request)
}
}
Start your Emulator from Android Studio Tools->Android-> AVD Manager
then select an emulator image and start it.
After emulator is started just drag and drop the APK Very simple.
Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:
=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")
If you wanted to use match, you'd have to use INDEX
as well, like so:
=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")
but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR
works)!
Note: =IFERROR()
can be a substitute of =IF()
and =ISERROR()
in some cases :)
I realize this question is old and has been answered to death, but here's my stab at it. I'm trying to reinvent the wheel here because I was using the currently accepted answer and the mishandling of URL fragments recently bit me in a project.
The function is below. It's quite long, but it was made to be as resilient as possible. I would love suggestions for shortening/improving it. I put together a small jsFiddle test suite for it (or other similar functions). If a function can pass every one of the tests there, I say it's probably good to go.
Update: I came across a cool function for using the DOM to parse URLs, so I incorporated that technique here. It makes the function shorter and more reliable. Props to the author of that function.
/**
* Add or update a query string parameter. If no URI is given, we use the current
* window.location.href value for the URI.
*
* Based on the DOM URL parser described here:
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @param (string) uri Optional: The URI to add or update a parameter in
* @param (string) key The key to add or update
* @param (string) value The new value to set for key
*
* Tested on Chrome 34, Firefox 29, IE 7 and 11
*/
function update_query_string( uri, key, value ) {
// Use window URL if no query string is provided
if ( ! uri ) { uri = window.location.href; }
// Create a dummy element to parse the URI with
var a = document.createElement( 'a' ),
// match the key, optional square brackets, an equals sign or end of string, the optional value
reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),
// Setup some additional variables
qs,
qs_len,
key_found = false;
// Use the JS API to parse the URI
a.href = uri;
// If the URI doesn't have a query string, add it and return
if ( ! a.search ) {
a.search = '?' + key + '=' + value;
return a.href;
}
// Split the query string by ampersands
qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
qs_len = qs.length;
// Loop through each query string part
while ( qs_len > 0 ) {
qs_len--;
// Remove empty elements to prevent double ampersands
if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }
// Check if the current part matches our key
if ( reg_ex.test( qs[qs_len] ) ) {
// Replace the current value
qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;
key_found = true;
}
}
// If we haven't replaced any occurrences above, add the new parameter and value
if ( ! key_found ) { qs.push( key + '=' + value ); }
// Set the new query string
a.search = '?' + qs.join( '&' );
return a.href;
}
I've been bashing my head for a whole day with this exact problem. I've just fixed it. Here's how...
The service had to run over SSL (i.e. it's at https://mydomain.com/MyService.svc)
Adding a service reference to the WCF service on a development server worked just fine.
Deploying the exact same build of the WCF service on the live production server, then switching to the client application and configuring the service reference to point to the live service displayed no errors but the app wouldn't build: It turns out that the service reference's Reference.cs file was completely empty! Updating the service reference made no difference. Cleaning the solution didn't help. Restarting VS2010 made no difference. Creating a new blank solution, starting a console project and adding a service reference to the live service exhibited exactly the same problem.
I didn't think it was due to conflicting types or anything, but what the heck - I reconfigured the WCF service reference by unchecking "Reuse types in all referenced assemblies". No joy; I put the check mark back.
Next step was to try svcutil on the reference URL to see if that would help uncover the problem. Here's the command:
svcutil /t:code https://mydomain.com/MyService.svc /d:D:\test
This produced the following:
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation. All rights reserved.
Attempting to download metadata from 'https://mydomain.com/MyService.svc' using WS-Metadata Exchange or DISCO.
Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Schema with target namespace 'http://mynamespace.com//' could not be found.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']
Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']
Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:service[@name='MyService']/wsdl:port[@name='WSHttpBinding_IMyService']
Generating files...
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.
Warning: If you would like to generate data contracts from schemas make sure to use the /dataContractOnly option.
That had me completely stumped. Despite heavy googling and getting really rather cross, and reconsidering a career as a bus driver, I finally considered why it worked OK on the development box. Could it be an IIS configuration issue?
I remoted simultaneously into both the development and live boxes, and on each I fired up the IIS Manager (running IIS 7.5). Next, I went through each configuration setting on each box, comparing the values on each server.
And there's the problem: Under "SSL Settings" for the site, make sure "Require SSL" is checked, and check the Client Certificates radio button for "Accept". Problem fixed!
<?php
echo '<p>Hello World</p>'
?>
As simple as placing something along those lines within your HTML assuming your server is set-up to execute PHP in files with the HTML extension.
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library
Sample below shows how to convert
string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter()
step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
1- Login as default PostgreSQL user (postgres)
sudo -u postgres -i
2- As postgres user. Add a new database user using the createuser
command
[postgres]$ createuser --interactive
3-exit
[postgres]$ exit
You can pass vector by reference just like this:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).
In order to achieve exactly the same result you should write:
void do_something(int el, std::vector<int> &arr){
if (arr.size() == 0) { // can't modify value of non-existent element
arr.push_back(el);
} else {
arr[0] = el;
}
}
In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).
you can try this
<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
- To make this answer work with Python 3.x as well, print
is called as a function: in 3.x, only print('foo')
works, whereas 2.x also accepts print 'foo'
.
- For a cross-platform perspective that includes Windows, see kxr's helpful answer.
In bash
, ksh
, or zsh
:
Use an ANSI C-quoted string ($'...'
), which allows using \n
to represent newlines that are expanded to actual newlines before the string is passed to python
:
python -c $'import sys\nfor r in range(10): print("rob")'
Note the \n
between the import
and for
statements to effect a line break.
To pass shell-variable values to such a command, it is safest to use arguments and access them via sys.argv
inside the Python script:
name='rob' # value to pass to the Python script
python -c $'import sys\nfor r in range(10): print(sys.argv[1])' "$name"
See below for a discussion of the pros and cons of using an (escape sequence-preprocessed) double-quoted command string with embedded shell-variable references.
To work safely with $'...'
strings:
\
instances in your original source code.
\<char>
sequences - such as \n
in this case, but also the usual suspects such as \t
, \r
, \b
- are expanded by $'...'
(see man printf
for the supported escapes)'
instances as \'
.If you must remain POSIX-compliant:
Use printf
with a command substitution:
python -c "$(printf %b 'import sys\nfor r in range(10): print("rob")')"
To work safely with this type of string:
\
instances in your original source code.
\<char>
sequences - such as \n
in this case, but also the usual suspects such as \t
, \r
, \b
- are expanded by printf
(see man printf
for the supported escape sequences).Pass a single-quoted string to printf %b
and escape embedded single quotes as '\''
(sic).
Using single quotes protects the string's contents from interpretation by the shell.
That said, for short Python scripts (as in this case) you can use a double-quoted string to incorporate shell variable values into your scripts - as long as you're aware of the associated pitfalls (see next point); e.g., the shell expands $HOME
to the current user's home dir. in the following command:
python -c "$(printf %b "import sys\nfor r in range(10): print('rob is $HOME')")"
However, the generally preferred approach is to pass values from the shell via arguments, and access them via sys.argv
in Python; the equivalent of the above command is:
python -c "$(printf %b 'import sys\nfor r in range(10): print("rob is " + sys.argv[1])')" "$HOME"
While using a double-quoted string is more convenient - it allows you to use embedded single quotes unescaped and embedded double quotes as \"
- it also makes the string subject to interpretation by the shell, which may or may not be the intent; $
and `
characters in your source code that are not meant for the shell may cause a syntax error or alter the string unexpectedly.
\
processing in double-quoted strings can get in the way; for instance, to get Python to produce literal output ro\b
, you must pass ro\\b
to it; with a '...'
shell string and doubled \
instances, we get:python -c "$(printf %b 'import sys\nprint("ro\\\\bs")')" # ok: 'ro\bs'
"..."
shell string:python -c "$(printf %b "import sys\nprint('ro\\\\bs')")" # !! INCORRECT: 'rs'
"\b"
and "\\b"
as literal \b
, requiring a dizzying number of additional \
instances to achieve the desired effect:python -c "$(printf %b "import sys\nprint('ro\\\\\\\\bs')")"
To pass the code via stdin
rather than -c
:
Note: I'm focusing on single-line solutions here; xorho's answer shows how to use a multi-line here-document - be sure to quote the delimiter, however; e.g., <<'EOF'
, unless you explicitly want the shell to expand the string up front (which comes with the caveats noted above).
In bash
, ksh
, or zsh
:
Combine an ANSI C-quoted string ($'...'
) with a here-string (<<<...
):
python - <<<$'import sys\nfor r in range(10): print("rob")'
-
tells python
explicitly to read from stdin (which it does by default).
-
is optional in this case, but if you also want to pass arguments to the scripts, you do need it to disambiguate the argument from a script filename:
python - 'rob' <<<$'import sys\nfor r in range(10): print(sys.argv[1])'
If you must remain POSIX-compliant:
Use printf
as above, but with a pipeline so as to pass its output via stdin:
printf %b 'import sys\nfor r in range(10): print("rob")' | python
With an argument:
printf %b 'import sys\nfor r in range(10): print(sys.argv[1])' | python - 'rob'
It's possible, use the structure below:
<li><a><span></span></a></li>
<li><a><span></span></a></li>
etc...
Where the <li>
contains an <a>
anchor tag that contains a span as shown above. Then insert the following css:
position: relative;
<a>
tag a height
, width
<span>
width
& height
to 100%, so that both <a>
and <span>
have same dimensions<a>
and <span>
get position: relative;
.<a>
tag will have the 'OFF' background-position
, and the <span>
will have the 'ON' background-poisiton
.<span>
:hover
state use opacity 1 for <span>
-webkit
or -moz
transition on the <span>
elementYou'll have the ability to use the transition effect while still defaulting to the old background-position
swap. Don't forget to insert IE alpha filter.
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
First check the default-jdk
package, good chance it already provide you an OpenJDK >= 11
.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all§ion=all
So starting from Ubuntu 18.04 LTS it should be ok.
sudo apt update -qq
sudo apt install -yq default-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version
For Ubuntu 16.04 LTS, only openjdk-8-jdk
is provided in the official repos so you need to find it in a ppa:
sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.