Type g++(or make) on terminal.
This will prompt for you to install the developer tools, if they are missing.
Also the size will be very less when compared to xcode
This is odd I have a similar problem. I downloaded the package for SQL 2012 Express with Tools but the Database Engine was not install.
I donloaded the other one from the MS site and this one installed the database engine. After a reboot the services were listed and ready to go.
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
I did this:
Using -refresh
or -clean
when starting eclipse did not help.
For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):
$('#user_button').toggle(function () {
$("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
$("#user_button").css({borderBottomLeftRadius: "5px"});
});
Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.
$('#user_button').toggle(function () {
$("#user_button").addClass("active");
}, function () {
$("#user_button").removeClass("active");
});
To fetch column name, instead of using readlines() better use readline() to avoid loop & reading the complete file & storing it in the array.
with open(csv_file, 'rb') as csvfile:
# get number of columns
line = csvfile.readline()
first_item = line.split(',')
String path = Server.MapPath("~/MP_Upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
char ch='A';
System.out.println((int)ch);
if you replace in the function SimpleDateFormat("hh") with ("HH") will format the hour in 24 hours instead of 12.
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.
You call writer.close();
in writeToFile
so the writer has been closed the second time you call writeToFile
.
Why don't you merge FileStatus
into writeToFile
?
Using Visual Studio IDE for porting Java to C#:
Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.
For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:
For supporting Android (Java/C++) development, you could try:
An extension to Dilums's answer:
Without changing code, you likely need pursue custom implementations of URL related interfaces as Dilum recommends. To simplify things for you, I can recommend looking at the source for Spring Framework's Resources. While the code is not in the form of a stream handler, it has been designed to do exactly what you are looking to do and is under the ASL 2.0 license, making it friendly enough for re-use in your code with due credit.
This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:
::-webkit-scrollbar {
width: 2em;
height: 2em
}
::-webkit-scrollbar-button {
background: #ccc
}
::-webkit-scrollbar-track-piece {
background: #888
}
::-webkit-scrollbar-thumb {
background: #eee
}?
References:
Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.
When you build a project using Visual Studio or command prompt the compiler creates these symbol files.
Check Microsoft Docs
I recently created tuna for visualizing Python runtime and import profiles; this may be helpful here.
Install with
pip install tuna
Create a runtime profile
python3 -m cProfile -o program.prof yourfile.py
or an import profile (Python 3.7+ required)
python3 -X importprofile yourfile.py 2> import.log
Then just run tuna on the file
tuna program.prof
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
This is cross-browser and fully responsive:
<iframe
src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
">
</iframe>
You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.
Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.
In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.
// Container sizes
// --------------------------------------------------
// Small screen / tablet
@container-tablet: ((720px + @grid-gutter-width));
// Medium screen / desktop
@container-desktop: ((940px + @grid-gutter-width));
// Large screen / wide desktop
@container-lg-desktop: ((1020px + @grid-gutter-width));
Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
PDFs may contain binary data and chances are it's getting mangled when you do ToString. It seems to me that you want this:
FileInputStream inputStream = new FileInputStream(sourcePath);
int numberBytes = inputStream .available();
byte bytearray[] = new byte[numberBytes];
inputStream .read(bytearray);
select price from mobile_sales_details order by price desc limit 5
Note: i have mobile_sales_details table
syntax
select column_name from table_name order by column_name desc limit size.
if you need top low price just remove the keyword desc from order by
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a utc datetime object.
2016-06-29T19:36:29.3453Z
:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
2016-06-29T19:36:29.3453-0400
or 2008-09-03T20:56:35.450686+05:00
use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500
making it more consistent/easier to parse.
import re
# this regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
%z
strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
) then you need to manually offset the time from Z
(UTC). Note %z
may not work on your system in python versions < 3 as it depended on the c library support which varies across system/python build type (i.e. Jython, Cython, etc.).
import re
import datetime
# this regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# split on the offset to remove it. use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# offset datetime with timedelta
output_datetime = output_datetime + offset_delta
If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.
We did it like this:
from p in Products
join bp in BaseProducts on p.BaseProductId equals bp.Id
where !string.IsNullOrEmpty(p.SomeId) && p.LastPublished >= lastDate
group new { p, bp } by new { p.SomeId } into pg
let firstproductgroup = pg.FirstOrDefault()
let product = firstproductgroup.p
let baseproduct = firstproductgroup.bp
let minprice = pg.Min(m => m.p.Price)
let maxprice = pg.Max(m => m.p.Price)
select new ProductPriceMinMax
{
SomeId = product.SomeId,
BaseProductName = baseproduct.Name,
CountryCode = product.CountryCode,
MinPrice = minprice,
MaxPrice = maxprice
};
EDIT: we used the version of AakashM, because it has better performance
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.
The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").
Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:
(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const
HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
I: Integer;
c: AnsiChar;
begin
// percent-encoding, see RFC-3986, p. 2.1
Result := S;
for I := Length(S) downto 1 do
begin
c := S[I];
case c of
'A' .. 'Z', 'a' .. 'z', // alpha
'0' .. '9', // digit
'-', '.', '_', '~':; // rest of unreserved characters as defined in the RFC-3986, p.2.3
else
begin
Result[I] := '%';
Insert('00', Result, I + 1);
Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
Result[I + 2] := HexCharArrA[Byte(C) and $F];
end;
end;
end;
end;
function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
Result := UrlEncodeRfcA(Utf8Encode(S));
end;
Just I have tried in windows
copy con file.txt
then Press Enter Key then Press Ctrl+Z Enter
And its worked for me.
For Ubuntu usually I am creating a file using VI command
vi file.txt
It will open the file then press ESC key then type :wp then press enter key. It will create a new file with empty data.
Write this is the activity you are in:
Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);
In the NextActivity.java
Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));
This works for me, you can try it.
with a little help of math
#include <math.h>
int main(){
int a = -1;
unsigned int b;
b = abs(a);
}
Just an update with Java Generics.
You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.
Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required
public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
final T value = rs.getObject(columnName, clazz);
return rs.wasNull() ? null : value;
}
In this example, your code could look like below:
final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
//null handling
} else {
//use int value of columnValue with autoboxing
}
Happy to get feedback
I think it's first worth noting that without javascript (plain html), the form
element submits when clicking either the <input type="submit" value="submit form">
or <button>submits form too</button>
. In javascript you can prevent that by using an event handler and calling e.preventDefault()
on button click, or form submit. e
is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit
, and the other on the button via onClick
.
Example: http://jsbin.com/vowuley/edit?html,js,console,output
can gridmove be of any assistance?
very handy tool on larger screens...
I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.
https://github.com/ansible/ansible/issues/39389
- hosts: localhost
connection: local
gather_facts: no
tasks:
- name: set_fact
set_fact:
foo: "{{ foo }} + [ '{{ item }}' ]"
with_items:
- "one"
- "two"
- "three"
vars:
foo: []
- name: Print the var
debug:
var: foo
We can do it nicely using Interceptors. You dont have to set options in all your services neither manage all your error responses, just define 2 interceptors (one to do something before sending the request to server and one to do something before sending the server's response to your service)
In your app.module import HTTP_INTERCEPTORS from '@angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.
At login http response (use http service), save the token at localStorage.
Then use httpClient for all your apirest services.
You can check some good practices on my github proyect here
It seems to me that the standard CustomErrors
configuration should just work however, due to the reliance on Server.Transfer
it seems that the internal implementation of ResponseRewrite
isn't compatible with MVC.
This feels like a glaring functionality hole to me, so I decided to re-implement this feature using a HTTP module. The solution below allows you to handle any HTTP status code (including 404) by redirecting to any valid MVC route just as you would do normally.
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="~/MVCErrorPage" />
</customErrors>
This has been tested on the following platforms;
Benefits
The Solution
namespace Foo.Bar.Modules {
/// <summary>
/// Enables support for CustomErrors ResponseRewrite mode in MVC.
/// </summary>
public class ErrorHandler : IHttpModule {
private HttpContext HttpContext { get { return HttpContext.Current; } }
private CustomErrorsSection CustomErrors { get; set; }
public void Init(HttpApplication application) {
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
CustomErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
application.EndRequest += Application_EndRequest;
}
protected void Application_EndRequest(object sender, EventArgs e) {
// only handle rewrite mode, ignore redirect configuration (if it ain't broke don't re-implement it)
if (CustomErrors.RedirectMode == CustomErrorsRedirectMode.ResponseRewrite && HttpContext.IsCustomErrorEnabled) {
int statusCode = HttpContext.Response.StatusCode;
// if this request has thrown an exception then find the real status code
Exception exception = HttpContext.Error;
if (exception != null) {
// set default error status code for application exceptions
statusCode = (int)HttpStatusCode.InternalServerError;
}
HttpException httpException = exception as HttpException;
if (httpException != null) {
statusCode = httpException.GetHttpCode();
}
if ((HttpStatusCode)statusCode != HttpStatusCode.OK) {
Dictionary<int, string> errorPaths = new Dictionary<int, string>();
foreach (CustomError error in CustomErrors.Errors) {
errorPaths.Add(error.StatusCode, error.Redirect);
}
// find a custom error path for this status code
if (errorPaths.Keys.Contains(statusCode)) {
string url = errorPaths[statusCode];
// avoid circular redirects
if (!HttpContext.Request.Url.AbsolutePath.Equals(VirtualPathUtility.ToAbsolute(url))) {
HttpContext.Response.Clear();
HttpContext.Response.TrySkipIisCustomErrors = true;
HttpContext.Server.ClearError();
// do the redirect here
if (HttpRuntime.UsingIntegratedPipeline) {
HttpContext.Server.TransferRequest(url, true);
}
else {
HttpContext.RewritePath(url, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext);
}
// return the original status code to the client
// (this won't work in integrated pipleline mode)
HttpContext.Response.StatusCode = statusCode;
}
}
}
}
}
public void Dispose() {
}
}
}
Usage
Include this as the final HTTP module in your web.config
<system.web>
<httpModules>
<add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
</httpModules>
</system.web>
<!-- IIS7+ -->
<system.webServer>
<modules>
<add name="ErrorHandler" type="Foo.Bar.Modules.ErrorHandler" />
</modules>
</system.webServer>
For those of you paying attention you will notice that in Integrated Pipeline mode this will always respond with HTTP 200 due to the way Server.TransferRequest
works. To return the proper error code I use the following error controller.
public class ErrorController : Controller {
public ErrorController() { }
public ActionResult Index(int id) {
// pass real error code to client
HttpContext.Response.StatusCode = id;
HttpContext.Response.TrySkipIisCustomErrors = true;
return View("Errors/" + id.ToString());
}
}
$('#myDiv').children().each( (index, element) => {
console.log(index); // children's index
console.log(element); // children's element
});
This iterates through all the children and their element with index value can be accessed separately using element and index respectively.
You can't do it with pure HTML, but this jQuery plugin will let you: https://github.com/bradjasper/jQuery-Placeholder-Newlines
a=input()
print(a[::-1])
The above code recieves the input from the user and prints an output that is equal to the reverse of the input by adding [::-1].
OUTPUT:
>>> Happy
>>> yppaH
But when it comes to the case of sentences, view the code output below:
>>> Have a happy day
>>> yad yppah a evaH
But if you want only the characters of the string to be reversed and not the sequence of string, try this:
a=input().split() #Splits the input on the basis of space (" ")
for b in a: #declares that var (b) is any value in the list (a)
print(b[::-1], end=" ") #End declares to print the character in its quotes (" ") without a new line.
In the above code in line 2 in I said that ** variable b is any value in the list (a)** I said var a to be a list because when you use split in an input the variable of the input becomes a list. Also remember that split can't be used in the case of int(input())
OUTPUT:
>>> Have a happy day
>>> evaH a yppah yad
If we don't add end(" ") in the above code then it will print like the following:
>>> Have a happy day
>>> evaH
>>> a
>>> yppah
>>> yad
Below is an example to understand end():
CODE:
for i in range(1,6):
print(i) #Without end()
OUTPUT:
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
Now code with end():
for i in range(1,6):
print(i, end=" || ")
OUTPUT:
>>> 1 || 2 || 3 || 4 || 5 ||
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
<?php
echo date('d - m - Y',strtotime('2013-01-19 01:23:42'));
?>
Out put : 19 - 01 - 2013
In the "Window" menu, open "Open Perspective" -> "Debug".
click On the plus image icon(you see the below image at status bar), and then select "Logcat"....
It is too late but helps someone, I'm using node version v7.9.0
and express version 4.15.0
if your directory structure is something like this:
your-project
uploads
package.json
server.js
server.js code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/uploads'));// you can access image
//using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.
//Or you can change the directory for hiding real directory name:
`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg
app.listen(7000);
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
I only delete my old DB located in my localhost directly from wamp, Stop all services, Go to wamp/bin/mysql/mysql[version]/data and I found the DB with problemas, I delete it and start again wamp all services, create again your database and it is done, Now you can import your tables,
Supopose you want to copy oldList into a new ArrayList object called newList
ArrayList<Object> newList = new ArrayList<>() ;
for (int i = 0 ; i<oldList.size();i++){
newList.add(oldList.get(i)) ;
}
These two lists are indepedant, changes to one are not reflected to the other one.
git add .
git reset main/dontcheckmein.txt
you can use just
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version></version>
</dependency>
Here's the code I put together based on example from this blog: LINK and this source: LINK.
import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
class App2 {
public static void main(String[] args) {
if (args.length != 4 && args.length != 2) {
System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
System.out.println("Usage: App2 <username> <password> <domain> <server>");
System.out.println("Short usage: App2 <username> <password>");
System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
System.exit(1);
}
String domainName;
String serverName;
if (args.length == 4) {
domainName = args[2];
serverName = args[3];
} else {
domainName = "xyz.tld";
serverName = "abc";
}
String username = args[0];
String password = args[1];
System.out
.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
System.out.println("Authentication succeeded!");
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
"(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
if (!renum.hasMore()) {
System.out.println("Cannot locate user information for " + username);
System.exit(1);
}
SearchResult result = renum.next();
List<String> groups = new ArrayList<String>();
Attribute memberOf = result.getAttributes().get("memberOf");
if (memberOf != null) {// null if this user belongs to no group at all
for (int i = 0; i < memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
Attribute att = atts.get("CN");
groups.add(att.get().toString());
}
}
context.close();
System.out.println();
System.out.println("User belongs to: ");
Iterator ig = groups.iterator();
while (ig.hasNext()) {
System.out.println(" " + ig.next());
}
} catch (AuthenticationException a) {
System.out.println("Authentication failed: " + a);
System.exit(1);
} catch (NamingException e) {
System.out.println("Failed to bind to LDAP / get account information: " + e);
System.exit(1);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if (token.length() == 0)
continue; // defensive check
if (buf.length() > 0)
buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
}
You could create a mutable wrapper of the primitive int and create a Set of those:
class MutableInteger
{
private int value;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
class Test
{
public static void main(String[] args)
{
Set<MutableInteger> mySet = new HashSet<MutableInteger>();
// populate the set
// ....
for (MutableInteger integer: mySet)
{
integer.setValue(integer.getValue() + 1);
}
}
}
Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.
Here is how to set token this automatically
On your login/auth request
Then for authenticated page
Simple solution in 2 lines of code. Just use the copy constructor. No need to write TrulyObservableCollection etc.
Example:
speakers.list[0].Status = "offline";
speakers.list[0] = new Speaker(speakers.list[0]);
Another method without copy constructor. You can use serialization.
speakers.list[0].Status = "offline";
//speakers.list[0] = new Speaker(speakers.list[0]);
var tmp = JsonConvert.SerializeObject(speakers.list[0]);
var tmp2 = JsonConvert.DeserializeObject<Speaker>(tmp);
speakers.list[0] = tmp2;
I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.
def get_class(fully_qualified_path, module_name, class_name, *instantiation):
"""
Returns an instantiated class for the given string descriptors
:param fully_qualified_path: The path to the module eg("Utilities.Printer")
:param module_name: The module name eg("Printer")
:param class_name: The class name eg("ScreenPrinter")
:param instantiation: Any fields required to instantiate the class
:return: An instance of the class
"""
p = __import__(fully_qualified_path)
m = getattr(p, module_name)
c = getattr(m, class_name)
instance = c(*instantiation)
return instance
A weak entity is one that can only exist when owned by another one. For example: a ROOM can only exist in a BUILDING. On the other hand, a TIRE might be considered as a strong entity because it also can exist without being attached to a CAR.
Use ?? , 'or' not supported in updated version.
{{ $usersType or '' }} ?
{{ $usersType ?? '' }} ?
MAT, jprofiler,jhat are possible options. since jhat comes with jdk, you can easily launch it to do some basic analysis. check this out
It turned out that TCP/IP was enabled for the IPv4 address, but not for the IPv6 address, of THESERVER
.
Apparently some connection attempts ended up using IPv4 and others used IPv6.
Enabling TCP/IP for both IP versions resolved the issue.
The fact that SSMS worked turned out to be coincidental (the first few attempts presumably used IPv4). Some later attempts to connect through SSMS resulted in the same error message.
To enable TCP/IP for additional IP addresses:
I just discovered sshj, which seems to have a much more concise API than JSCH (but it requires Java 6). The documentation is mostly by examples-in-the-repo at this point, and usually that's enough for me to look elsewhere, but it seems good enough for me to give it a shot on a project I just started.
A very simple solution is to add the database name with your table name like if your DB name is DBMS
and table is info
then it will be DBMS.info
for any query.
If your query is
select * from STUDENTREC where ROLL_NO=1;
it might show an error but
select * from DBMS.STUDENTREC where ROLL_NO=1;
it doesn't because now actually your table is found.
For me works the next command:
find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'
if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.
For example: 's@string/to/replace@new/string@g'
You can use tf.keras API.
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, array_to_img
tf.enable_eager_execution()
img = load_img("example.png")
img = tf.convert_to_tensor(np.asarray(img))
image = tf.image.resize_images(img, (800, 800))
to_img = array_to_img(image)
to_img.show()
Here is another version for Wordpress, original one did not work as intended.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.php$ - [END]
RewriteCond $1 ^(index\.php)?$ [OR]
RewriteCond $1 \.(gif|jpg|png|ico|css|js)$ [NC,OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ - [END]
RewriteRule ^ /index.php [L]
</IfModule>
# END WordPress
Reference from this Github repository, modified a bit. After excessive testing this rule does not solve all problems. We have a Wordpress webshop, which has 40 plugins and somewhere is there a rewrite clash. I sincerely hope next version of Wordpress has no URL rewrites.
RewriteRule ^index\.php$ - [L]
The ^
signifies start of the string, \
escapes .
or it would mean any character, and $
signifies end of the string.
^index\.php$
if http(s)://hostname/index.php -
do nothing [END]
flag can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing.
RewriteCond $1 ^(index\.php)?$ [OR]
In RewriteCond
using $1
as a test string references to captured contents of everything from the start to the end of the url http(s)://hostname/bla/bla.php. If used in substitution or condition it references to captured backreference. RewriteRule (bla)/(ble\.php)$ -
for http(s)://hostname/bla/ble.php captures bla
into $1
and ble.php
into $2
. Multiple capture groups can be accessed via $3..N
.
( )
groups several characters into single unit, ?
forces the match optional.
[OR]
flag allows you to combine rewrite conditions with a logical OR relationship as opposed to the default AND.
In short, if bla/bla.php contains index.php OR next condition
RewriteCond $1 \.(gif|jpg|png|ico|css|js)$ [NC,OR]
( )
groups several characters into single unit, |
separates characters to subgroups and conditions them if any one of.
[NC]
flag causes the RewriteRule to be matched in case-insensitive manner.
In short, if bla/bla.php ends with any of the filetypes OR next condition
RewriteCond %{REQUEST_FILENAME} -f [OR]
Server-Variables are variables of the form %{ NAME_OF_VARIABLE } where NAME_OF_VARIABLE can be a string taken from the following list:
%{REQUEST_FILENAME}
is full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time REQUEST_FILENAME is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI. Depending on the value of AcceptPathInfo, the server may have only used some leading components of the REQUEST_URI to map the request to a file.
-f
check for regular file. Treats the test string as pathname and tests whether or not it exists.
In short, if bla/bla.php is a file OR next condition
RewriteCond %{REQUEST_FILENAME} -d
-d
check for directory. Treats the test string as a pathname and tests whether or not it exists.
In short, if bla/bla.php is a directory
RewriteRule ^(.*)$ - [END] not as in Github [S=1]
This statement is only executed when one of the condition returned true.
.
match any character *
zero or more times.
The [S]
flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N]
, where N
signifies the number of rules to skip (provided the RewriteRule matches). This can be thought of as a goto statement in your rewrite ruleset. In the following example, we only want to run the RewriteRule if the requested URI doesn't correspond with an actual file.
In short, do nothing
RewriteRule ^ /index.php [L]
The [L]
flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.
In short, rewrite every path as http(s)://hostname/index.php
I fetched this little doc together from apaches.org documentation. Links below.
Try This it helped me without changing theme . Put Your AppBarLayout inside any layout.Hope this will help you
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="false"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_height="?attr/actionBarSize"
android:background="@color/white">
<ImageView
android:src="@drawable/go_grocery_logo"
android:layout_width="108dp"
android:layout_height="32dp" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
</RelativeLayout>
Here is the official microsoft VM images for doing IE 6, 7, 8 and 9 testing: http://www.microsoft.com/en-us/download/details.aspx?id=11575
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
This script also work:
#/bin/sh
while true
do
echo "Enter parent process id [type quit for exit]"
read ppid
if [ $ppid -eq "quit" -o $ppid -eq "QUIT" ];then
exit 0
fi
for i in `ps -ef| awk '$3 == '$ppid' { print $2 }'`
do
echo killing $i
kill $i
done
done
for example, if you set other versions (e.g. 3.5) as default and want to install pip for python 2.7:
//you can use the ? operator instead of if
ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";
I don't see much details about performance and optimizer in the other answers.
Sometimes it is good to know that only INNER JOIN
is associative which means the optimizer has the most option to play with it. It can reorder the join order to make it faster keeping the same result. The optimizer can use the most join modes.
Generally it is a good practice to try to use INNER JOIN
instead of the different kind of joins. (Of course if it is possible considering the expected result set.)
There are a couple of good examples and explanation here about this strange associative behavior:
CREATE OR REPLACE PROCEDURE SP_Invoices(p_nameClient IN CHAR)
AS
BEGIN
FOR c_invoice IN
(
SELECT CodeInvoice, NameClient FROM Invoice
WHERE NameClient = p_nameClient
)
LOOP
dbms_output.put_line('Code Invoice: ' || c_invoice.CodeInvoice);
dbms_output.put_line('Name Client : ' || c_invoice.NameClient );
END LOOP;
END;
Executing in SQL Developer:
BEGIN
SP_Invoices('Perico de los palotes');
END;
-- Or:
EXEC SP_Invoices('Perico de los palotes');
Output:
> Code Invoice: 1
> Name Client : Perico de los palotes
> Code Invoice: 2
> Name Client : Perico de los palotes
I have tried changing the google gms services to the latest com.google.gms:google-services:3.2.1
in Android Studio 3.0.1 but the warning still persists.
As recommended by the compiler,I changed all compile
dependencies to implementation
and testCompile
to testImplementation
like this..
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:mediarouter-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.google.firebase:firebase-ads:12.0.1'
implementation 'com.google.firebase:firebase-crash:12.0.1'
implementation 'com.google.firebase:firebase-core:12.0.1'
implementation 'com.google.firebase:firebase-messaging:12.0.1'
implementation 'com.google.firebase:firebase-perf:12.0.1'
implementation 'com.google.firebase:firebase-appindexing:12.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
And finally the warning is removed!
If the file is local as your comment about SITE_PATH
suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :
function print_xml_data_file()
{
include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}
function get_xml_data()
{
ob_start();
print_xml_data_file();
$xml_file = ob_get_contents();
ob_end_clean();
return $xml_file;
}
If it's remote as lot of others said curl
is the way to go. If it isn't present try socket_create
or fsockopen
. If nothing work... change your hosting provider.
I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.
Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.
Yes! Use Powershell:
powershell -Command "Remove-Item 'c:\destination\*' -Recurse -Force"
It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:
#include <algorithm>
#include <map>
#include <ext/functional> // GNU-specific extension for functor classes missing from standard STL
using namespace __gnu_cxx; // for compose1 and select2nd
class MyClass
{
public:
void Method() const;
};
std::map<int, MyClass> Map;
int main(void)
{
std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}
Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.
I had a similar requirement to dump the contents of json file for logging, something quick and easy:
print(json.dumps(json.load(open(os.path.join('<myPath>', '<myjson>'), "r")), indent = 4 ))
if you use it often then put it in a function:
def pp_json_file(path, file):
print(json.dumps(json.load(open(os.path.join(path, file), "r")), indent = 4))
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it
Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.
For Cordova, if you want to add it into your ios.json, do the following:
"NSAppTransportSecurity": [
{
"xml": "<dict><key>NSAllowsArbitraryLoads</key><true /></dict>"
}
]
And it should be inside of:
"*-Info.plist": {
"parents": {
}
}
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
If storing less then 1 mil records, and high performance is not an issue go for varchar(20)/char(20) otherwise I've found that for storing even 100 milion global business phones or personal phones, int is best. Reason : smaller key -> higher read/write speed, also formatting can allow for duplicates.
1 phone in char(20) = 20 bytes vs 8 bytes bigint
(or 10 vs 4 bytes int
for local phones, up to 9 digits) , less entries can enter the index block => more blocks => more searches, see this for more info (writen for Mysql but it should be true for other Relational Databases).
Here is an example of phone tables:
CREATE TABLE `phoneNrs` (
`internationalTelNr` bigint(20) unsigned NOT NULL COMMENT 'full number, no leading 00 or +, up to 19 digits, E164 format',
`format` varchar(40) NOT NULL COMMENT 'ex: (+NN) NNN NNN NNN, optional',
PRIMARY KEY (`internationalTelNr`)
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
or with processing/splitting before insert (2+2+4+1 = 9 bytes)
CREATE TABLE `phoneNrs` (
`countryPrefix` SMALLINT unsigned NOT NULL COMMENT 'countryCode with no leading 00 or +, up to 4 digits',
`countyPrefix` SMALLINT unsigned NOT NULL COMMENT 'countyCode with no leading 0, could be missing for short number format, up to 4 digits',
`localTelNr` int unsigned NOT NULL COMMENT 'local number, up to 9 digits',
`localLeadingZeros` tinyint unsigned NOT NULL COMMENT 'used to reconstruct leading 0, IF(localLeadingZeros>0;LPAD(localTelNr,localLeadingZeros+LENGTH(localTelNr),'0');localTelNr)',
PRIMARY KEY (`countryPrefix`,`countyPrefix`,`localLeadingZeros`,`localTelNr`) -- ordered for fast inserts
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
;
Also "the phone number is not a number", in my opinion is relative to the type of phone numbers. If we're talking of an internal mobile phoneBook, then strings are fine, as the user may wish to store GSM Hash Codes. If storing E164 phones, bigint is the best option.
The problem is with line
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
may or may not be int. Check.
Use Int32.TryParse(value, out number)
instead. That will solve your problem.
int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
Image1.Width= imageWidth;
}
Simple Definition:
npm - Javascript package manager
npx - Execute npm package binaries
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
@columnName varchar(255),
@id int
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @columnVal TABLE (columnVal nvarchar(255));
DECLARE @sql nvarchar(max);
SET @sql = 'SELECT ' + @columnName + ' FROM regUsers WHERE id=' + CAST(@id AS varchar(10));
INSERT @columnVal EXEC sp_executesql @sql;
SELECT * FROM @columnVal;
END
GO
The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:
String decoded = new String(bytes, "UTF-8"); // example for one encoding type
By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte
is signed, it covers the range from -128 to 127.
-109 = 0x93: Control Code "Set Transmit State"
The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.
0x93
in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:
System.out.println(new String(new byte[]{-109}, "Cp1252"));
Agreed with Yuri Tkachenko's answer.
I wanna point this out.
It's a pretty specific scenario. BUT it happens.
When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.
So, make sure it ends with .gif extension
Add this to your dependencies in build.gradle
:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
...
The latest version can be found here
Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project
Take a look at your libraries folder, the library you just added should be in there.
You can write your function to take a const std::string&
:
void print(const std::string& input)
{
cout << input << endl;
}
or a const char*
:
void print(const char* input)
{
cout << input << endl;
}
Both ways allow you to call it like this:
print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
The second version does require c_str()
to be called for std::string
s:
print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
ErrorDocument 403 /maintenance.html
Order Allow,Deny
Allow from #:#:#:#:#:#
For me, this seems to work (Using IPv6 rather than IPv4) I don't know if this is different for some websites but for mine this works.
You can do the following to install java 8 on your machine. First get the link of tar
that you want to install. You can do this by:
- go to java downloads page and find the appropriate download.
- Accept the license agreement and download it.
- In the download page in your browser right click and
copy link address
.
Then in your terminal:
$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java
it stands for your website where your app is running on. like you have made an app www.xyz.pqr then you will type this www.xyz.pqr in App domain the site where your app is running on should be secure and valid
Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e. related objects (child objects) are loaded automatically with its parent object.
When to use:
Lazy Loading: In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.
When to use:
NOTE: Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
Typescript: How to define type for a function callback used in a method parameter?
You can declare the callback as 1) function property or 2) method:
interface ParamFnProp {
callback: (a: Animal) => void; // function property
}
interface ParamMethod {
callback(a: Animal): void; // method
}
There is an important typing difference since TS 2.6:
You get stronger ("sound") types in --strict
or --strictFunctionTypes
mode, when a function property is declared. Let's take an example:
const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { }
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works
// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...
Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes
. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array
.
For unstaging all the files in your last commit -
git reset HEAD~
I like very short, clear, guaranteed code. Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.
Not sure about what guarantees you have and want, so offering anyway.
If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.
Answer from simple to more complex cases of the original question.
P=/home/smith/Desktop/Test ; echo "${P%/*}"
/home/smith/Desktop
P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
/home/smith/Desktop/
for P in \
/home/smith/Desktop/Test \
/home/smith/Desktop/Test/
do
P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
done
/home/smith/Desktop
/home/smith/Desktop
for P in \
/home/smith/Desktop/Test \
/home/smith/Desktop/Test/ \
/home/smith///Desktop////Test//
do
P_NODUPSLASH="${P//\/*(\/)/\/}"
P_ENDNOSLASH="${P_NODUPSLASH%%/}"
echo "${P_ENDNOSLASH%/*}";
done
/home/smith/Desktop
/home/smith/Desktop
/home/smith/Desktop
Actually you need to change your read
to read -r
which will make it ignore backslashes.
Also, you should escape quotes and backslashes. So
while read -r line; do
line="${line//\\/\\\\}"
line="${line//\"/\\\"}"
line="${line//\`/\\\`}"
eval echo "\"$line\""
done > destination.txt < source.txt
Still a terrible way to do expansion though.
It's very easy just in 2 click
That it Happy coding
If you like to count duplicates on particular column(s):
len(df['one'])-len(df['one'].drop_duplicates())
If you want to count duplicates on entire dataframe:
len(df)-len(df.drop_duplicates())
Or simply you can use DataFrame.duplicated(subset=None, keep='first'):
df.duplicated(subset='one', keep='first').sum()
where
subset : column label or sequence of labels(by default use all of the columns)
keep : {‘first’, ‘last’, False}, default ‘first’
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
The children
property returns an array of elements, like so:
parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]
There are alternatives to querySelector
, like document.getElementsByClassName('parent')[0]
if you so desire.
Edit: Now that I think about it, you could just use querySelectorAll
to get decendents of parent
having a class name of child1
:
children = document.querySelectorAll('.parent .child1');
The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.
# \di
The easies and shortest way is \di
, which will list all the indexes in the current database.
$ \di
List of relations
Schema | Name | Type | Owner | Table
--------+-----------------------------+-------+----------+---------------
public | part_delivery_index | index | shipper | part_delivery
public | part_delivery_pkey | index | shipper | part_delivery
public | shipment_by_mandator | index | shipper | shipment_info
public | shipment_by_number_and_size | index | shipper | shipment_info
public | shipment_info_pkey | index | shipper | shipment_info
(5 rows)
\di
is the "small brother" of the \d
command which will list all relations of the current database. Thus \di
certainly stand for "show me this databases indexes".
Typing \diS
will list all indexes used systemwide, which means you get all the pg_catalog indexes as well.
$ \diS
List of relations
Schema | Name | Type | Owner | Table
------------+-------------------------------------------+-------+----------+-------------------------
pg_catalog | pg_aggregate_fnoid_index | index | postgres | pg_aggregate
pg_catalog | pg_am_name_index | index | postgres | pg_am
pg_catalog | pg_am_oid_index | index | postgres | pg_am
pg_catalog | pg_amop_fam_strat_index | index | postgres | pg_amop
pg_catalog | pg_amop_oid_index | index | postgres | pg_amop
pg_catalog | pg_amop_opr_fam_index | index | postgres | pg_amop
pg_catalog | pg_amproc_fam_proc_index | index | postgres | pg_amproc
pg_catalog | pg_amproc_oid_index | index | postgres | pg_amproc
pg_catalog | pg_attrdef_adrelid_adnum_index | index | postgres | pg_attrdef
--More--
With both these commands you can add a +
after it to get even more information like the size the disk space the index needs and a description if available.
$ \di+
List of relations
Schema | Name | Type | Owner | Table | Size | Description
--------+-----------------------------+-------+----------+---------------+-------+-------------
public | part_delivery_index | index | shipper | part_delivery | 16 kB |
public | part_delivery_pkey | index | shipper | part_delivery | 16 kB |
public | shipment_by_mandator | index | shipper | shipment_info | 19 MB |
public | shipment_by_number_and_size | index | shipper | shipment_info | 19 MB |
public | shipment_info_pkey | index | shipper | shipment_info | 53 MB |
(5 rows)
In psql you can easily find help about commands typing \?
.
A common pattern is to use
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.
EDIT: A less common pattern to use which avoids the scope of line
leaking.
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
// process the line.
}
// line is not visible here.
}
UPDATE: In Java 8 you can do
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
}
NOTE: You have to place the Stream in a try-with-resource block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later.
I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';
//when the form is submitted POST Method and must be clicked on submit button
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
$full_Name = $_POST['fullName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$msg = $_POST['message'];
// Form Validation for fullname
if (empty($full_Name)) {
$full_Name_error = "Name is required";
} else {
$full_Name_test = test_input($full_Name);
if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
$full_Name_error = "Only letters and white spaces are allowed";
}
}
//Form Validation for email
if (empty($email)) {
$email_error = "Email is required";
} else {
$email_test = test_input($email);
if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid Email format";
}
}
//Form Validation for message
if (empty($msg)) {
$msg_error = "Say atleast Hello!";
} else {
$msg_test = test_input($msg);
}
if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
// Here starts PHP Mailer
date_default_timezone_set('Etc/UTC');
// Edit this path if PHPMailer is in a different location.
require './PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
/*Server Configuration*/
$mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
$mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
$mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
$mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
$mail->Username = ""; // Your Gmail address.
$mail->Password = ""; // Your Gmail login password or App Specific Password.
/*Message Configuration*/
$mail->setFrom($email, $full_Name); // Set the sender of the message.
$mail->addAddress(''); // Set the recipient of the message.
$mail->Subject = 'Contact form submission from your Website'; // The subject of the message
/*Message Content - Choose simple text or HTML email*/
$mail->isHTML(true);
// Choose to send either a simple text email...
$mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber: ' . $phoneNumber . '<br>' . 'Email: ' . $email . '<br><br>' . 'Message: ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
// ... or send an email with HTML.
//$mail->msgHTML(file_get_contents('contents.html'));
// Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
//$mail->AltBody = 'This is a plain-text message body';
// Optional: attach a file
//$mail->addAttachment('images/phpmailer_mini.png');
if ($mail->send()) {
$result_success = "Your message was sent successfully! " .
//Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
$full_Name;
$full_Name = false;
$email = false;
$phoneNumber = false;
$msg = false;
} else {
$result_error = "Something went wrong. Check your Network connection and Please try again.";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev. Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
An alternative way if you need something more (besides using the keys
method):
hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }
obviously you would only do that if you want to manipulate the array while retrieving it..
Try this one. Hope this is working fine.. :)
@ECHO off
cls
ECHO.
set drvltr=
set /p drvltr=Enter Drive letter:
attrib -s -h -a /s /d %drvltr%:\*.*
ECHO Unhide Completed
pause
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:
import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array
res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])
which can be extended to D dimensions.
The results are:
Prediction:
[[1 2]
[2 0]
[2 0]
[1 2]
[1 2]]
Target:
[[0 1]
[1 0]
[2 0]
[0 0]
[2 1]]
Count of correct prediction for D=1: 1
Count of correct prediction for D=2: 2
If you want to localize string later, then those answers aren't enough, I would suggest something like:
<TextBlock>
<Hyperlink NavigateUri="http://labsii.com/">
<Hyperlink.Inlines>
<Run Text="Click here"/>
</Hyperlink.Inlines>
</Hyperlink>
</TextBlock>
This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.
As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.
So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.
v22.1
of appcompat-v7
introduced some new possibilities. Now it's possible to assign a specific theme only to one view.
Deprecated use of app:theme for styling Toolbar. You can now use android:theme for toolbars on all API level 7 and higher devices and android:theme support for all widgets on API level 11 and higher devices.
So instead of setting the desired color in a global theme, we create a new one and assign it only to the Button
Example:
<style name="MyColorButton" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorButtonNormal">@color/myColor</item>
</style>
And use this style as theme of your Button
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button1"
android:theme="@style/MyColorButton"/>
On Windows you can use win32gui:
import win32gui
import win32con
import subprocess
class HideFox:
def __init__(self, exe='firefox.exe'):
self.exe = exe
self.get_hwnd()
def get_hwnd(self):
win_name = get_win_name(self.exe)
self.hwnd = win32gui.FindWindow(0,win_name)
def hide(self):
win32gui.ShowWindow(self.hwnd, win32con.SW_MINIMIZE)
win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)
def show(self):
win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
win32gui.ShowWindow(self.hwnd, win32con.SW_MAXIMIZE)
def get_win_name(exe):
''' Simple function that gets the window name of the process with the given name'''
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
raw = subprocess.check_output('tasklist /v /fo csv', startupinfo=info).split('\n')[1:-1]
for proc in raw:
try:
proc = eval('[' + proc + ']')
if proc[0] == exe:
return proc[8]
except:
pass
raise ValueError('Could not find a process with name ' + exe)
Example:
hider = HideFox('firefox.exe') # Can be anything, e.q., phantomjs.exe, notepad.exe, etc.
# To hide the window
hider.hide()
# To show again
hider.show()
However, there is one problem with this solution - using send_keys method makes the window show up. You can deal with it by using JavaScript which does not show a window:
def send_keys_without_opening_window(id_of_the_element, keys)
YourWebdriver.execute_script("document.getElementById('" + id_of_the_element + "').value = '" + keys + "';")
To list all of the packages in the active environment, use:
conda list
To list all of the packages in a deactivated environment, use:
conda list -n myenv
Try this:
Edit or create the file :nodesource.list
sudo gedit /etc/apt/sources.list.d/nodesource.list
Insert this text:
deb https://deb.nodesource.com/node_10.x bionic main
deb-src https://deb.nodesource.com/node_10.x bionic main
Run these commands:
curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
sudo sh -c "echo deb https://deb.nodesource.com/node_10.x cosmic main /etc/apt/sources.list.d/nodesource.list"
sudo apt-get update
sudo apt-get install nodejs
Some simple ideas to get you going:
In PHP you can do it like this:
if (!array_key_exists(explode('=', explode('&', $_GET))) {
/* add the view-all bit here */
}
In javascript:
if(!location.search.match(/view\-all=/)) {
location.href = location.href + '&view-all=Yes';
}
If you're using at least Java 8, see my other answer.
If you're already using Google Guava, see Sean Patrick Floyd's answer.
If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat()
using no more than Iterable
and Iterator
:
public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
final Iterable<? extends E> iterable2) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
final Iterator<? extends E> iterator1 = iterable1.iterator();
final Iterator<? extends E> iterator2 = iterable2.iterator();
@Override
public boolean hasNext() {
return iterator1.hasNext() || iterator2.hasNext();
}
@Override
public E next() {
return iterator1.hasNext() ? iterator1.next() : iterator2.next();
}
};
}
};
}
@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
return concat(Arrays.asList(iterables));
}
public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
return new Iterable<E>() {
final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();
@Override
public Iterator<E> iterator() {
return !iterablesIterator.hasNext() ? Collections.emptyIterator()
: new Iterator<E>() {
Iterator<? extends E> iterableIterator = nextIterator();
@Override
public boolean hasNext() {
return iterableIterator.hasNext();
}
@Override
public E next() {
final E next = iterableIterator.next();
findNext();
return next;
}
Iterator<? extends E> nextIterator() {
return iterablesIterator.next().iterator();
}
Iterator<E> findNext() {
while (!iterableIterator.hasNext()) {
if (!iterablesIterator.hasNext()) {
break;
}
iterableIterator = nextIterator();
}
return this;
}
}.findNext();
}
};
}
With the newest API, here's the code I used for it
/*params*/
NSDictionary *params = @{
@"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
@"fields": @"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"me"
parameters:params
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:@"id"]);
Simply set location relative to null after calling pack on the JFrame, that's it.
e.g.,
JFrame frame = new JFrame("FooRendererTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel); // or whatever...
frame.pack();
frame.setLocationRelativeTo(null); // *** this will center your app ***
frame.setVisible(true);
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
I made a Prototype Version of this:
String.prototype.strip = function() {
var translate_re = /[öäüÖÄÜß ]/g;
var translate = {
"ä":"a", "ö":"o", "ü":"u",
"Ä":"A", "Ö":"O", "Ü":"U",
" ":"_", "ß":"ss" // probably more to come
};
return (this.replace(translate_re, function(match){
return translate[match];})
);
};
Use like:
var teststring = 'ä ö ü Ä Ö Ü ß';
teststring.strip();
This will will change the String to a_o_u_A_O_U_ss
You can use .on() to capture multiple events and then test for touch on the screen, e.g.:
$('#selector')
.on('touchstart mousedown', function(e){
e.preventDefault();
var touch = e.touches[0];
if(touch){
// Do some stuff
}
else {
// Do some other stuff
}
});
There's also a drop down menu in the graphical layout window of eclipse. some of the themes in this menu will have ".NoTitleBar" at the end. any of these will do trick.
Use the -L
option to follow redirects:
curl -L https://github.com/pinard/Pymacs/tarball/v0.24-beta2 | tar zx
You could do it easily by using min() function
`def asc(a):
b=[]
l=len(a)
for i in range(l):
x=min(a)
b.append(x)
a.remove(x)
return b
print asc([2,5,8,7,44,54,23])`
You can use groups (indicated with '('
and ')'
) to capture parts of the string. The match object's group()
method then gives you the group's contents:
>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0) # the entire match
'name my_user_name is valid'
>>> match.group(1) # the first parenthesized subgroup
'my_user_name'
In Python 3.6+ you can also index into a match object instead of using group()
:
>>> match[0] # the entire match
'name my_user_name is valid'
>>> match[1] # the first parenthesized subgroup
'my_user_name'
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
My tests with git-2.0.0 today indicate that the --mirror option does not copy hooks, the config file, the description file, the info/exclude file, and at least in my test case a few refs (which I don't understand.) I would not call it a "functionally identical copy, interchangeable with the original."
-bash-3.2$ git --version
git version 2.0.0
-bash-3.2$ git clone --mirror /git/hooks
Cloning into bare repository 'hooks.git'...
done.
-bash-3.2$ diff --brief -r /git/hooks.git hooks.git
Files /git/hooks.git/config and hooks.git/config differ
Files /git/hooks.git/description and hooks.git/description differ
...
Only in hooks.git/hooks: applypatch-msg.sample
...
Only in /git/hooks.git/hooks: post-receive
...
Files /git/hooks.git/info/exclude and hooks.git/info/exclude differ
...
Files /git/hooks.git/packed-refs and hooks.git/packed-refs differ
Only in /git/hooks.git/refs/heads: fake_branch
Only in /git/hooks.git/refs/heads: master
Only in /git/hooks.git/refs: meta
I hope this can help someone who was faced with my same problem.
This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.
Make sure you install Bootstrap DatePicker through NuGet
Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datecontrol").datepicker();
});
}
Set the bundles
bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap-datepicker.js",
"~/Scripts/DatePickerReady.js",
"~/Scripts/respond.js"))
bundles.Add(New StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-datepicker3.css",
"~/Content/site.css"))
Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.
<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing
Your view code should be
@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})
and voila
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
Service
extends ContextWrapper
ContextWrapper
extends Context
So....
Context context = this;
(in Service or Activity Class)
When you already have all the "pieces" you wish to append, there is no point in using StringBuilder
at all. Using StringBuilder
and string concatenation in the same call as per your sample code is even worse.
This would be better:
return "select id1, " + " id2 " + " from " + " table";
In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:
return "select id1, id2 from table";
Using new StringBuilder().append("select id1, ").append(" id2 ")....toString()
will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.
If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.
I have an article on String
/ StringBuffer
which I wrote a while ago - before StringBuilder
came along. The principles apply to StringBuilder
in the same way though.
ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
All you have to do is to post URL encoded username and password inside query string.
/Token/userName=johndoe%40example.com&password=1234&grant_type=password
If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.
Not absolutely what you are asking for, but you may be interested by my plugin vim-notebook which allows the user to keep a background process alive and to make it evaluate part of the current document (and to write the output in the document). It is intended to be used on notebook-style documents containing pieces of code to be evaluated.
C++17 now provides the [[maybe_unused]]
attribute.
http://en.cppreference.com/w/cpp/language/attributes
Quite nice and standard.
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.
To make it work you should change the following variables in your php.ini:
; display_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; display_startup_errors
; Default Value: On
; Development Value: On
; Production Value: Off
; error_reporting
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED
; html_errors
; Default Value: On
; Development Value: On
; Production value: Off
; log_errors
; Default Value: On
; Development Value: On
; Production Value: On
Search for them as they are already defined and put your desired value. Then restart your apache2 server and everything will work fine. Good luck!
Use gsub or delete. The difference is gsub could remove tabs, while delete cannot. Sometimes you do have tabs in files which are added by the editors.
a = "\tI have some whitespaces.\t"
a.gsub!(/\s/, '') #=> "Ihavesomewhitespaces."
a.gsub!(/ /, '') #=> "\tIhavesomewhitespaces.\t"
a.delete!(" ") #=> "\tIhavesomewhitespaces.\t"
a.delete!("/\s/") #=> "\tIhavesomewhitespaces.\t"
a.delete!('/\s/') #=> using single quote is unexpected, and you'll get "\tI have ome whitepace.\t"
file 1:
int x = 50;
file 2:
extern int x;
printf("%d", x);
1) File >>> Project Structure OR press Ctrl+Alt+Shift+S
2) In SDK Location Tab you will find SDK Location:
3) Change your Project SDK location to the one you have installed
4) Sync your project
The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.
If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".
It's a simple Mistake while adding a new file you just have to make sure that \
is added to the file before and the new file remain as it is
eg.
Check Out what to do if i want to add a new file named customer.cc
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
import datetime
def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
# inclusive=False to behave like range by default
if step.days > 0:
while start < stop:
yield start
start = start + step
# not +=! don't modify object passed in if it's mutable
# since this function is not restricted to
# only types from datetime module
elif step.days < 0:
while start > stop:
yield start
start = start + step
if inclusive and start == stop:
yield start
# ...
for date in daterange(start_date, end_date, inclusive=True):
print strftime("%Y-%m-%d", date.timetuple())
This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count
and most importantly the code becomes easier to read as you call the function from multiple places.
OuterClass.this
references the outer class.
To know the package owning (or providing) an already installed file:
rpm -qf myfilename
A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:
since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:
WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).
Improved with input from @a_horse_with_no_name in the comments below.
You could even use an empty SELECT
list:
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
Since the SELECT
list is not relevant to the outcome of EXISTS
. Only the existence of at least one qualifying row matters.
You can try this:
function Get-UrlStatusCode([string] $Url)
{
try
{
(Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
}
catch [Net.WebException]
{
[int]$_.Exception.Response.StatusCode
}
}
$statusCode = Get-UrlStatusCode 'httpstat.us/500'
I tried to manage using the below command. This will write the output in log file as well as print on console.
#!/bin/bash
# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1
echo "Log Location should be: [ $LOG_LOCATION ]"
Please note: This is bash code so if you run it using sh it will through syntax error
I like polymorphism instead of manually checking for something:
use MooseX::Declare;
class Foo {
use MooseX::MultiMethods;
multi method foo (ArrayRef $arg){ say "arg is an array" }
multi method foo (HashRef $arg) { say "arg is a hash" }
multi method foo (Any $arg) { say "arg is something else" }
}
Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else
This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.
Your type library:
package MyApp::Types;
use MooseX::Types -declare => ['EvenNumberLessThan42'];
use MooseX::Types::Moose qw(Num);
subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };
Then make Foo support this (in that class definition):
class Foo {
use MyApp::Types qw(EvenNumberLessThan42);
multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}
Then Foo->new->foo(40)
prints arg is an even number less than 42
instead of arg is something else
.
Maintainable.
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);
pd.datetime.now().strftime("%d/%m/%Y")
this will give output as '11/02/2019'
you can use add time if you want
pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")
this will give output as '11/02/2019 11:08:26'
I already did post this answer somewhere, i will do it here again. This version doesn't use any major inbuilt method. You got the char array, convert it into a String. Hope it helps!
import java.util.Scanner;
public class SentenceToWord
{
public static int getNumberOfWords(String sentence)
{
int counter=0;
for(int i=0;i<sentence.length();i++)
{
if(sentence.charAt(i)==' ')
counter++;
}
return counter+1;
}
public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring()
{
int counter=0;
char charArrayToReturn[]=new char[end-start];
for(int i=start;i<end;i++)
{
charArrayToReturn[counter++]=sentence.charAt(i);
}
return charArrayToReturn;
}
public static char[][] getWordsFromString(String sentence)
{
int wordsCounter=0;
int spaceIndex=0;
int length=sentence.length();
char wordsArray[][]=new char[getNumberOfWords(sentence)][];
for(int i=0;i<length;i++)
{
if(sentence.charAt(i)==' ' || i+1==length)
{
wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
spaceIndex=i+1; //increment space index
}
}
return wordsArray; //return the 2 dimensional char array
}
public static void main(String[] args)
{
System.out.println("Please enter the String");
Scanner input=new Scanner(System.in);
String userInput=input.nextLine().trim();
int numOfWords=getNumberOfWords(userInput);
char words[][]=new char[numOfWords+1][];
words=getWordsFromString(userInput);
System.out.println("Total number of words found in the String is "+(numOfWords));
for(int i=0;i<numOfWords;i++)
{
System.out.println(" ");
for(int j=0;j<words[i].length;j++)
{
System.out.print(words[i][j]);//print out each char one by one
}
}
}
}
I found the solution for this problem:
On Windows 10 the following worked for me. I added the following environment variables using Settings > Edit environment variables for your account:
SPARK_HOME=C:\Programming\spark-2.0.1-bin-hadoop2.7
PYTHONPATH=%SPARK_HOME%\python;%PYTHONPATH%
(change "C:\Programming\..." to the folder in which you have installed spark)
There is no difference, but you should not use either.
In many browsers, the window.onload
event is not triggered until all images have loaded, which is not what you want. Standards based browsers have an event called DOMContentLoaded
which fires earlier, but it is not supported by IE (at the time of writing this answer). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's $(document).ready()
, is a good example.
Updated for pandas
0.20
given that ix
is deprecated. This demonstrates not only how to use loc
, iloc
, at
, iat
, set_value
, but how to accomplish, mixed positional/label based indexing.
loc
- label based
Allows you to pass 1-D arrays as indexers. Arrays can be either slices (subsets) of the index or column, or they can be boolean arrays which are equal in length to the index or columns.
Special Note: when a scalar indexer is passed, loc
can assign a new index or column value that didn't exist before.
# label based, but we can use position values
# to get the labels from the index object
df.loc[df.index[2], 'ColName'] = 3
df.loc[df.index[1:3], 'ColName'] = 3
iloc
- position based
Similar to loc
except with positions rather that index values. However, you cannot assign new columns or indices.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.iloc[2, df.columns.get_loc('ColName')] = 3
df.iloc[2, 4] = 3
df.iloc[:3, 2:4] = 3
at
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns.
Advantage over loc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# label based, but we can use position values
# to get the labels from the index object
df.at[df.index[2], 'ColName'] = 3
df.at['C', 'ColName'] = 3
iat
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage over iloc
is that this is faster.
Disadvantage is that you can't use arrays for indexers.
# position based, but we can get the position
# from the columns object via the `get_loc` method
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3
set_value
- label based
Works very similar to loc
for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# label based, but we can use position values
# to get the labels from the index object
df.set_value(df.index[2], 'ColName', 3)
set_value
with takable=True
- position based
Works similarly to iloc
. Cannot work in array indexers. Cannot! assign new indices and columns.
Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas
is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.
# position based, but we can get the position
# from the columns object via the `get_loc` method
df.set_value(2, df.columns.get_loc('ColName'), 3, takable=True)
SELECT * FROM tablename
WHERE column IN
(select column from tablename
where column like 'M510%'
or column like 'M615%'
OR column like 'M515%'
or column like'M612%'
)
The Problem of auto deintending is caused due to a checkbox being active in the settings of VSCode. Follow these steps:
Try Stretch="UniformToFill" on the Image
Run this:
SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID
using logback 1.1.3 I had to do the following (Scala code):
import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
Since I never can remember that LINQ calls it Where
, Select
and Aggregate
instead of Filter
, Map
and Reduce
so I created a few extension methods you can use:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :
The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. Python documentation explains the difference, but here are some examples:
class Foo:
def __init__(self):
self.num = 1
This binds num
to the Foo instances. Change to this field is not propagated to other instances.
Thus:
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1
class Bar:
num = 1
This binds num
to the Bar class. Changes are propagated!
>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3
If I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?
The code in exhibit B is plain wrong for this: why would you want to bind a class attribute (default value on instance creation) to the single instance?
The code in exhibit A is okay.
If you want to give defaults for instance variables in your constructor I would however do this:
class Foo:
def __init__(self, num = None):
self.num = num if num is not None else 1
...or even:
class Foo:
DEFAULT_NUM = 1
def __init__(self, num = None):
self.num = num if num is not None else DEFAULT_NUM
...or even: (preferrable, but if and only if you are dealing with immutable types!)
class Foo:
def __init__(self, num = 1):
self.num = num
This way you can do:
foo1 = Foo(4)
foo2 = Foo() #use default
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
For hosted repositories you can since svn version 1.7 use svnrdump
, which is analogous to svnadmin dump
for local repositories. This article provides a nice walk-through, which essentially boils down to:
svnrdump dump /URL/to/remote/repository > myRepository.dump
After you have downloaded the dump file you can import it locally
svnadmin load /path/to/local/repository < myRepository.dump
or upload it to the host of your choice.
This is what worked for me on windows:
Edit the pg_hba.conf file locates at C:\Program Files\PostgreSQL\9.3\data.
# IPv4 local connections:
host all all 127.0.0.1/32 trust
Change the method from trust to md5 and restart the postgres service on windows.
After that, you can login using postgres user without password by using pgadmin. You can change password using File->Change password.
If postgres user does not have superuser privileges , then you cannot change the password. In this case , login with another user(pgsql)with superuser access and provide privileges to other users by right clicking on users and selecting properties->Role privileges.
Also, bear in mind that if you need to export multiple functions at once, like actions you can use
export * from './XThingActions';
ifconfig $(netstat -rn | grep -E "^default|^0.0.0.0" | head -1 | awk '{print $NF}') | grep 'inet ' | awk '{print $2}' | grep -Eo '([0-9]*\.){3}[0-9]*'
I'd use months_between
, possibly combined with floor
:
select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;
select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;
floor
makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor
.
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.
Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.
I had a similar error, but it was because I had created a has_one
relationship and subsequently deleted the model that it had_one
of. I just forgot to delete the has_one
relationship from the remaining model.
I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int str_append(char **json, const char *format, ...)
{
char *str = NULL;
char *old_json = NULL, *new_json = NULL;
va_list arg_ptr;
va_start(arg_ptr, format);
vasprintf(&str, format, arg_ptr);
// save old json
asprintf(&old_json, "%s", (*json == NULL ? "" : *json));
// calloc new json memory
new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));
strcat(new_json, old_json);
strcat(new_json, str);
if (*json) free(*json);
*json = new_json;
free(old_json);
free(str);
return 0;
}
int main(int argc, char *argv[])
{
char *json = NULL;
str_append(&json, "name: %d, %d, %d", 1, 2, 3);
str_append(&json, "sex: %s", "male");
str_append(&json, "end");
str_append(&json, "");
str_append(&json, "{\"ret\":true}");
int i;
for (i = 0; i < 10; i++) {
str_append(&json, "id-%d", i);
}
printf("%s\n", json);
if (json) free(json);
return 0;
}
start = datetime.now()
#code for which response time need to be measured.
end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds
Hi , You can use this in your .ts file :
first import your service in this .ts file:
import { Your_Service_Name } from './path_To_Your_Service_Name';
Then in the same file you can add providers: [Your_Service_Name]
:
@Component({
selector: 'my-app',
providers: [Your_Service_Name],
template: `
<h1>Hello World</h1> `
})
Add a key in your info.plist
file UIViewControllerBasedStatusBarAppearance
and set it to YES
.
In viewDidLoad method of your ViewController add a method call:
[self setNeedsStatusBarAppearanceUpdate];
Then paste the following method in viewController
file:
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
I avoid RegExp at all costs. Here is another thing you can do:
"good_luck_buddy".split('_').slice(1).join('_')
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
People gave good answers but forgot to mention the most important part in my opinion:
In the second example the X
of the list comprehension is NOT the same as the X
of the lambda
function, they are totally unrelated.
So the second example is actually the same as:
[Lambda X: X*X for I in range(10)]
The internal iterations on range(10)
are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).
On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X
so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]
Use
table.put(key, val);
to add a new key/value pair or overwrite an existing key's value.
From the Javadocs:
V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
For a more complete list as of 2015:
* html .ie6 {property:value;}
or
.ie6 { _property:value;}
*+html .ie7 {property:value;}
or
*:first-child+html .ie7 {property:value;}
@media screen\9 {
.ie67 {property:value;}
}
or
.ie67 { *property:value;}
or
.ie67 { #property:value;}
@media \0screen\,screen\9 {
.ie678 {property:value;}
}
html>/**/body .ie8 {property:value;}
or
@media \0screen {
.ie8 {property:value;}
}
.ie8 { property /*\**/: value\9 }
@media screen\0 {
.ie8910 {property:value;}
}
@media screen and (min-width:0) and (min-resolution: .001dpcm) {
// IE9 CSS
.ie9{property:value;}
}
@media screen and (min-width:0) and (min-resolution: +72dpi) {
// IE9+ CSS
.ie9up{property:value;}
}
@media screen and (min-width:0) {
.ie910{property:value;}
}
_:-ms-lang(x), .ie10 { property:value\9; }
_:-ms-lang(x), .ie10up { property:value; }
or
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.ie10up{property:value;}
}
_:-ms-fullscreen, :root .ie11up { property:value; }
Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element
The Javascript:
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');
Adds (e.g) the below to the html
element:
data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'
Allowing very targetted CSS selectors, e.g.:
html[data-useragent*='Chrome/13.0'] .nav{
background:url(img/radial_grad.png) center bottom no-repeat;
}
If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.
Since it's the only one I've used, I would suggest the CalendarExtender from http://www.ajaxcontroltoolkit.com/
for bootstrap 4
add classes :
.full_modal-dialog {
width: 98% !important;
height: 92% !important;
min-width: 98% !important;
min-height: 92% !important;
max-width: 98% !important;
max-height: 92% !important;
padding: 0 !important;
}
.full_modal-content {
height: 99% !important;
min-height: 99% !important;
max-height: 99% !important;
}
and in HTML :
<div role="document" class="modal-dialog full_modal-dialog">
<div class="modal-content full_modal-content">
In Pythons <= 3.4 you can, as others suggested, use list(range(10))
in order to make a list out of a range (In general, any iterable).
Another alternative, introduced in Python 3.5
with its unpacking generalizations, is by using *
in a list literal []
:
>>> r = range(10)
>>> l = [*r]
>>> print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Though this is equivalent to list(r)
, it's literal syntax and the fact that no function call is involved does let it execute faster. It's also less characters, if you need to code golf :-)