There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.
To modify a remote system's global environment variables, you would use
setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere
This does not require restarting Windows Explorer.
Here's what's working for me
on windows
1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)
Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.
Click Start -> All Programs -> Accessories
Right click Notepad and select Run as administrator
Click Continue on the "Windows needs your permission" UAC window.
When Notepad opens Click File -> Open
In the filename field type C:\Windows\System32\Drivers\etc\hosts
Click Open
Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net
Save
Close and restart browsers
On Mac or Linux:
su
permission127.0.0.1 localdev.YOURSITE.net
When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.
Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.
2) create the certificate using that localdev.url
TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.
3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
You can index and use a negative sign to drop the 3rd column:
data[,-3]
Or you can list only the first 2 columns:
data[,c("c1", "c2")]
data[,1:2]
Don't forget the comma and referencing data frames works like this: data[row,column]
While this question is targeted for Linux/Unix instances of Mongo, it's one of the first search results regardless of the operating system used, so for future Windows users that find this:
If MongoDB is set up as a Windows Service in the default manner, you can usually find it by looking at the 'Path to executable' entry in the MongoDB Service's Properties:
This has happened to my because of proxy-authntication, so I did this to resolve it
export http_proxy=http://uname:[email protected]:8080
export https_proxy=http://uname:[email protected]:8080
export ftp_proxy=http://uname:[email protected]:8080
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods
Please try this
(function ($) {
$(document).ready(function(){
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if($('.submitclass').length){
$('.submitclass').click(function(){
$email_id = $('.custom-email-field').val();
if (validateEmail($email_id)) {
var url= $(this).attr('pdf_url');
var link = document.createElement('a');
link.href = url;
link.download = url.split("/").pop();
link.dispatchEvent(new MouseEvent('click'));
}
});
}
});
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<div class="form-item form-type-textfield form-item-email-id form-group">
<input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
</div>
<button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
Or use download attribute to tag in HTML5
On Linux or Ubuntu you need to use the complete path.
For example
/home/ubuntu/.android/keystorname.keystore
In my case I was using ~
instead of /home/user/
. Using shorthands like the below does not work
~/.android/keystorname.keystore
./keystorename.keystore
var a = [23, 45, 12, 67];_x000D_
a.unshift(34);_x000D_
console.log(a); // [34, 23, 45, 12, 67]
_x000D_
I have on several projects.
The biggest difference in my opinion
jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old
Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding
jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)
So what to choose?
That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?
I always end up using both, so I can use the best of both worlds.
Here are the links to both frameworks, if you decide to use them.
Here is my working code :
<!DOCTYPE html>
<html>
<head>
<style>
ul#proList{list-style-position: inside}
li.item{list-style:none; padding:5px;}
</style>
</head>
<body>
<div id="renderList"></div>
</body>
<script>
(function(){
var ul = document.createElement('ul');
ul.setAttribute('id','proList');
productList = ['Electronics Watch','House wear Items','Kids wear','Women Fashion'];
document.getElementById('renderList').appendChild(ul);
productList.forEach(renderProductList);
function renderProductList(element, index, arr) {
var li = document.createElement('li');
li.setAttribute('class','item');
ul.appendChild(li);
li.innerHTML=li.innerHTML + element;
}
})();
</script>
</html>
working jsfiddle example here
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key == 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
};
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem('getSessionStorage', 'foobar');
localStorage.removeItem('getSessionStorage', 'foobar');
};
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.
I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc()
. But here, in my case, it is absolutely crucial. Weird? YES!
finally
{
try
{
in.close();
in = null;
out.flush();
out.close();
out = null;
System.gc();
}
catch (IOException e)
{
logger.error(e.getMessage());
e.printStackTrace();
}
}
There are several ways to simulate optional parameters in Java:
Method overloading.
void foo(String a, Integer b) {
//...
}
void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
}
foo("a", 2);
foo("a");
One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.
Varargs.
a) All optional parameters are of the same type:
void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
b) Types of optional parameters may be different:
void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.
Nulls. To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:
void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
//...
}
foo("a", null, 2);
Now all arguments values must be provided, but the default ones may be null.
Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:
void foo(String a, Optional<Integer> bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
//...
}
foo("a", Optional.of(2));
foo("a", Optional.<Integer>absent());
Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.
Update: Java 8 includes the class java.util.Optional
out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.
Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:
class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
//...
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();
Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:
void foo(Map<String, Object> parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
}
a = (Integer)parameters.get("a");
}
if (parameters.containsKey("b")) {
//...
}
//...
}
foo(ImmutableMap.<String, Object>of(
"a", "a",
"b", 2,
"d", "value"));
In Java 9, this approach became easier:
@SuppressWarnings("unchecked")
static <T> T getParm(Map<String, Object> map, String key, T defaultValue)
{
return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
}
void foo(Map<String, Object> parameters) {
String a = getParm(parameters, "a", "");
int b = getParm(parameters, "b", 0);
// d = ...
}
foo(Map.of("a","a", "b",2, "d","value"));
Please note that you can combine any of these approaches to achieve a desirable result.
declare Regione int;
set Regione=(select id from users
where id=1) ;
select Regione ;
You would naturally use Integer#to_s(2)
, String#to_i(2)
or "%b"
in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:
def int_to_binary(x)
p = 0
two_p = 0
output = ""
while two_p * 2 <= x do
two_p = 2 ** p
output << ((two_p & x == two_p) ? "1" : "0")
p += 1
end
#Reverse output to match the endianness of %b
output.reverse
end
To check it works:
1.upto(1000) do |n|
built_in, custom = ("%b" % n), int_to_binary(n)
if built_in != custom
puts "I expected #{built_in} but got #{custom}!"
exit 1
end
puts custom
end
Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch()
elsewhere. More like repeatedly creating the stubs of the same method.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.
Consider the below Test Class for example:
@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
@Mock
Service1 svc1Mock1;
@Mock
Service2 svc2Mock2;
@InjectMock
TestClass class;
//Assume you have many dependencies and you want to set up all the stubs
//in one place assuming that all your tests need these stubs.
//I know that any initialization code for the test can/should be in a
//@Before method. Lets assume there is another method just to create
//your stubs.
public void setUpRequiredStubs() {
when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
}
@Test
public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
// You forget that you defined the stub for svcMock1.someMethod or
//thought you could redefine it. Well you cannot. That's going to be
//a problem and would throw your UnnecessaryStubbingException.
when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
setUpRequiredStubs();
}
}
I would rather considering refactoring your tests to stub where necessary.
I had a similar issue. It is caused due the dependent package 'rJava'. This problem can be overcome by re-directing the R to use a different JAVA_HOME
.
if(Sys.getenv("JAVA_HOME")!=""){
Sys.setenv(JAVA_HOME="")
}
library(rJava)
This worked for me.
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.
I decided to update the entire URL using window.history.replaceState
rather than using the window.location.hash
method. Thus circumventing the hashChange event fired by the browser.
// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {
// Prevent default anchor handling (which causes the page-jumping)
event.preventDefault();
if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if ( target.length ) {
// Smooth scrolling to anchor
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
// Update URL
window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
}
}
});
This is the most simple, and it worked for me:
In the values-21:
<resources>
<style name="AppTheme" parent="AppTheme.Base">
...
<item name="android:windowTranslucentStatus">true</item>
</style>
<dimen name="topMargin">25dp</dimen>
</resources>
In the values:
<resources>
<dimen name="topMargin">0dp</dimen>
</resources>
And set to your toolbar
android:layout_marginTop="@dimen/topMargin"
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
You can implement routerOnActivate()
method on your route class, it will provide information about previous route.
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
Then you can use router.navigateByUrl()
and pass data generated from ComponentInstruction
. For example:
this._router.navigateByUrl(prevInstruction.urlPath);
There are two ways, one httpCookies
element in web.config
allows you to turn on requireSSL
which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />
NUMERIC(3,2)
means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.
Try NUMERIC(5,2)
- three before, two after the decimal point.
In general case you need to compare DateTimes
with the same Kind
:
if (date1.ToUniversalTime() < date2.ToUniversalTime())
Console.WriteLine("date1 is earlier than date2");
Explanation from MSDN about DateTime.Compare
(This is also relevant for operators like >
, <
, ==
and etc.):
To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.
Thus, a simple comparison may give an unexpected result when dealing with DateTimes
that are represented in different timezones.
This is my test. Hope it is useful.
# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"
# Is the tunnel up? Perform two tests:
# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
> /dev/null 2>&1
if [ $? -ne 0 ] ; then
pkill -f -x "$COMMAND"
$COMMAND
fi
Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.
If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)
So:
var stringArray = str.split(/(\s+)/);
^ ^
//
Output:
["my", " ", "car", " ", "is", " ", "red"]
This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.
You can change this in your CSS with the property padding
:
.navbar-nav > li{
padding-left:30px;
padding-right:30px;
}
Also you can set margin
.navbar-nav > li{
margin-left:30px;
margin-right:30px;
}
Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.
The Range object has both width and height properties, which are measured in points.
Today I created a jQuery plugin called jQuery Responsive Headlines that does exactly what you want: it adjusts the font size of a headline to fit inside its containing element (a div, the body or whatever). There are some nice options that you can set to customize the behavior of the plugin and I have also taken the precaution to add support for Ben Altmans Throttle/Debounce functionality to increase performance and ease the load on the browser/computer when the user resizes the window. In it's most simple use case the code would look like this:
$('h1').responsiveHeadlines();
...which would turn all h1 on the page elements into responsive one-line headlines that adjust their sizes to the parent/container element.
You'll find the source code and a longer description of the plugin on this GitHub page.
Good luck!
Swift 3:
extension URL {
func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name.lowercased() == key.lowercased()
}.first?.value
}
}
I used it to get the image name for UIImagePickerController
in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
:
var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
originalFilename = imageIdentifier + ".png"
print("file name : \(originalFilename)")
}
I've created a jQuery plugin that provides 4 additonal placements: topLeft, topRight, bottomLeft, bottomRight
You just include either the minified js or unminified js and have the matching css (minified vs unminified) in the same folder.
https://github.com/dkleehammer/bootstrap-popover-extra-placements
Yes:
test2.removeAll(test1)
Although this will mutate test2
, so create a copy if you need to preserve it.
Also, you probably meant <Integer>
instead of <int>
.
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
Advanced bash scripting guide, 10.2. Parameter Substitution:
to base your program logic on whether the variable $mystr is defined or not, you can do the following:
isdefined=0
${mystr+ export isdefined=1}
now, if isdefined=0 then the variable was undefined, if isdefined=1 the variable was defined
This way of checking variables is better than the above answer because it is more elegant, readable, and if your bash shell was configured to error on the use of undefined variables (set -u)
, the script will terminate prematurely.
Other useful stuff:
to have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:
mystr=${mystr- 7}
to print an error message and exit the function if the variable is undefined:
: ${mystr? not defined}
Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.
you are calling a script file not a command so you have to use -file eg :
powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"
for PS V2
powershell.exe -noexit &'c:\my scripts\test.ps1'
(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )
Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.
This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input:
N = n_neurons * ( n_inputs + 1)
.
Have you looked into querying INFORMATION_SCHEMA.Tables? As in
SELECT ic.Table_Name,
ic.Column_Name,
ic.data_Type,
IFNULL(Character_Maximum_Length,'') AS `Max`,
ic.Numeric_precision as `Precision`,
ic.numeric_scale as Scale,
ic.Character_Maximum_Length as VarCharSize,
ic.is_nullable as Nulls,
ic.ordinal_position as OrdinalPos,
ic.column_default as ColDefault,
ku.ordinal_position as PK,
kcu.constraint_name,
kcu.ordinal_position,
tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
left outer join INFORMATION_SCHEMA.key_column_usage ku
on ku.table_name = ic.table_name
and ku.column_name = ic.column_name
left outer join information_schema.key_column_usage kcu
on kcu.column_name = ic.column_name
and kcu.table_name = ic.table_name
left outer join information_schema.table_constraints tc
on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
In my case it was because the filename was containing spaces. Solved it thanks to this documentation (which is unrelated to the problem):
from urllib.parse import unquote_plus
key_name = unquote_plus(event['Records'][0]['s3']['object']['key'])
You also need to upload urllib as a layer with corresponding version (if your lambda is Python 3.7 you have to package urllib in a python 3.7 environment).
The reason is that AWS transform ' ' into '+' (why...) which is really problematic...
For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.
Find combine result for Datatype and Length and is nullable in form of "NULL" and "Not null" Use below query.
SELECT c.name AS 'Column Name',
t.name + '(' + cast(c.max_length as varchar(50)) + ')' As 'DataType',
case
WHEN c.is_nullable = 0 then 'null' else 'not null'
END AS 'Constraint'
FROM sys.columns c
JOIN sys.types t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = Object_id('TableName')
you will find result as shown below.
Thank you.
The numbers generated by
=NORMINV(RAND(),10,7)
are uniformally distributed. If you want the numbers to be normally distributed, you will have to write a function I guess.
For Linux or OSX, you can use ipfw
.
From Quora (http://www.quora.com/What-is-the-best-tool-to-simulate-a-slow-internet-connection-on-a-Mac)
Essentially using a firewall to throttle all network data:
Define a rule that uses a pipe to reroute all traffic from any source address to any destination address, execute the following command (as root, or using sudo):
$ ipfw add pipe 1 all from any to any
To configure this rule to limit bandwidth to 300Kbit/s and impose 200ms of latency each way:
$ ipfw pipe 1 config bw 300Kbit/s delay 200ms
To remove all rules and recover your original network connection:
$ ipfw flush
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
Some older browsers implemented keydown events in a non-standard way.
KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.
which
and keyCode
are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.
The isKeyPressed
function checks if the pressed key was enter and event.preventDefault()
hinders the form from submitting.
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
JS
function isKeyPressed(event, expectedKey, expectedCode) {
const code = event.which || event.keyCode;
if (expectedKey === event.key || code === expectedCode) {
return true;
}
return false;
}
document.getElementById('myInput').addEventListener('keydown', function(event) {
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
});
HTML
<form>
<input id="myInput">
</form>
The checking of the presence of the member before assigning it is, in my opinion, quite ugly.
Kohana has a useful function to make selecting parameters simple.
You can make your own like so...
function arrayGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
And then do something like...
$page = arrayGet($_GET, 'p', 1);
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout
.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100
and 200
) in a single line.
UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:
var date = new Date(unixTimestamp*1000);
First use git remote update
, to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking
is ahead, behind or has diverged. If it says nothing, the local and
remote are the same. Sample result:On branch DEV
Your branch is behind 'origin/DEV' by 7 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
git show-branch *master
will show you the commits in all of the
branches whose names end in 'master' (eg master and origin/master).If you use -v
with git remote update (git remote -v update
) you can see which branches got updated, so you don't really need any further commands.
Try to use response.json():
fetch('http://example.com/api/node', {
mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
}).then((response) => {
console.log(response.json()); // null
return dispatch({
type: "GET_CALL",
response: response.json()
});
})
.catch(error => { console.log('request failed', error); });
If the above solution didn't work and you got any unhandled promise rejection then try to follow steps :
Clean the Cordova project
cordova clean
cordova platform remove android/ios
cordova plugin remove
First of all you need to extract the path with something like this:
$("a#myLink").attr("href");
Then take a look at this plugin: http://plugins.jquery.com/project/query-object
It will help you handle all kinds of querystring things you want to do.
/Peter F
Comment out the warning lines in the below file:
lib64/python2.7/site-packages/cryptography/__init__.py
As Simon says above, using drawImage shouldn't work. But, using the canvg library and:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.
I think there is little difference between the two events. To understand this, I created a simple example to manipulation:
XAML
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
Title="MainWindow" Height="1000" Width="525"
WindowStartupLocation="CenterScreen"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded">
<Grid Name="RootGrid">
</Grid>
</Window>
Code behind
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded");
}
In this case the message Loaded
appears the first after the message ContentRendered
. This confirms the information in the documentation.
In general, in WPF the Loaded
event fires if the element:
is laid out, rendered, and ready for interaction.
Since in WPF the Window
is the same element, but it should be generally content that is arranged in a root panel (for example: Grid
). Therefore, to monitor the content of the Window
and created an ContentRendered
event. Remarks from MSDN:
If the window has no content, this event is not raised.
That is, if we create a Window
:
<Window x:Class="LoadedAndContentRendered.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow"
ContentRendered="Window_ContentRendered"
Loaded="Window_Loaded" />
It will only works Loaded
event.
With regard to access to the elements in the Window
, they work the same way. Let's create a Label
in the main Grid
of Window
. In both cases we have successfully received access to Width
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}
As for the Styles
and Templates
, at this stage they are successfully applied, and in these events we will be able to access them.
For example, we want to add a Button
:
private void Window_ContentRendered(object sender, EventArgs e)
{
MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "ContentRendered Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Right;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
Button b1 = new Button();
b1.Content = "Loaded Button";
RootGrid.Children.Add(b1);
b1.Height = 25;
b1.Width = 200;
b1.HorizontalAlignment = HorizontalAlignment.Left;
}
In the case of Loaded
event, Button
to add to Grid
immediately at the appearance of the Window
. In the case of ContentRendered
event, Button
to add to Grid
after all its content will appear.
Therefore, if you want to add items or changes before load Window
you must use the Loaded
event. If you want to do the operations associated with the content of Window
such as taking screenshots you will need to use an event ContentRendered
.
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
if you have generic types in your class you should use TypeReference
with convertValue()
.
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
Also you can use that to convert a pojo to java.util.Map
back.
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
Take for instance If I had a table named 'site' with a created_at and an update_at column that were both DATETIME and need the default value of now, I could execute the following sql to achieve this.
ALTER TABLE `site` CHANGE `created_at` `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ALTER TABLE `site` CHANGE `created_at` `created_at` DATETIME NULL DEFAULT NULL; ALTER TABLE `site` CHANGE `updated_at` `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ALTER TABLE `site` CHANGE `updated_at` `updated_at` DATETIME NULL DEFAULT NULL;
The sequence of statements is important because a table can not have two columns of type TIMESTAMP with default values of CUREENT TIMESTAMP
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
or much easier:
max(some_list , key = len)
For Rails 4.x the log level is configured a bit different than in Rails 3.x
Add this to config/environment/test.rb
# Enable stdout logger
config.logger = Logger.new(STDOUT)
# Set log level
config.log_level = :ERROR
The logger level is set on the logger instance from config.log_level
at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70
Environment variable
As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:
# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")
And then running tests from shell:
# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test
# Log level :ERROR
$ rake test
From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
So in your case, when: deployed_revision is not defined
should work
For copy directory use following command
cp -r source Destination
For example
cp -r /home/hasan /opt
For copy file use command without -r
cp /home/file /home/hasan/
I added Anaconda3/Library/Bin
to the environment path and PyCharm no longer complained with the error.
Stated by https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001194720/comments/360000341500
Yes, but not how you would imagine. According to caniuse (a very good resource) there is no support and no polyfill available for adding text-shadow
support to IE9. However, IE has their own proprietary text shadow (detailed here).
Example implementation, taken from their website (works in IE5.5 through IE9):
p.shadow {
filter: progid:DXImageTransform.Microsoft.Shadow(color=#0000FF,direction=45);
}
For cross-browser compatibility and future-proofing of code, remember to also use the CSS3 standard text-shadow
property (detailed here). This is especially important considering that IE10 has officially announced their intent to drop support for legacy dx filters. Going forward, IE10+ will only support the CSS3 standard text-shadow
.
I use this i tested it as key from my EhCacheManager
Memory map ....
Its cleaner i suppose
/**
* Return Hash256 of String value
*
* @param text
* @return
*/
public static String getHash256(String text) {
try {
return org.apache.commons.codec.digest.DigestUtils.sha256Hex(text);
} catch (Exception ex) {
Logger.getLogger(HashUtil.class.getName()).log(Level.SEVERE, null, ex);
return "";
}
}
am using maven but this is the jar commons-codec-1.9.jar
Set seekbar max and min value
seekbar have method that setmax(int position) and setProgress(int position)
thanks
select convert(varchar(10), cast(fmdate as date), 101) from sery
Without cast I was not getting fmdate converted, so fmdate was a string.
I usually do it like this.. Works every time..
var loc = ctrl.PointToScreen(Point.Empty);
I don't think you even need to attach it to the DOM, this seems to work for me:
$("<div>Test message</div>").dialog();
Here's a JS fiddle:
Modern linear algebra libraries include optimized versions of the most common operations. Many of them include dynamic CPU dispatch, which chooses the best implementation for the hardware at program execution time (without compromising on portability).
This is commonly a better alternative to performing manual optimization of your functinos via vector extensions intrinsic functions. The latter will tie your implementation to a particular hardware vendor and model: if you decide to swap to a different vendor (e.g. Power, ARM) or to a newer vector extensions (e.g. AVX512), you will need to re-implement it again to get the most of them.
MKL transposition, for example, includes the BLAS extensions function imatcopy
. You can find it in other implementations such as OpenBLAS as well:
#include <mkl.h>
void transpose( float* a, int n, int m ) {
const char row_major = 'R';
const char transpose = 'T';
const float alpha = 1.0f;
mkl_simatcopy (row_major, transpose, n, m, alpha, a, n, n);
}
For a C++ project, you can make use of the Armadillo C++:
#include <armadillo>
void transpose( arma::mat &matrix ) {
arma::inplace_trans(matrix);
}
Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error. You would also see a log message of the form "client denied by server configuration". The feature is requiring a user identity to access a directory. It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive
Require all denied
This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:
Require all granted
as in
<Directory "your directory here">
Order allow,deny
Allow from all
# New directive needed in Apache 2.4.3:
Require all granted
</Directory>
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
swift solution
yourlabel.text = yourvariable
or self is use for when you are in async {brackets} or in some Extension
DispatchQueue.main.async{
self.yourlabel.text = "typestring"
}
use the syntax .ToList()
to convert object read from db to list to avoid being re-read again.Hope this would work for it. Thanks.
@Vilmantas Baranauskas: Regarding this answer, I would comment if I had the rep points, but I don't. I wanted to note that the Counter class defined there is NOT thread-safe as it is not sufficient to just synchronize inc() without synchronizing value(). Other threads calling value() are not guaranteed to see the the value unless a happens-before relationship has been established with the update.
Edit your conftest.py and add following lines of code:
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), '..')))
And if trying to run the test case through terminal, use following ex:
python -m pytest test_some_step_file_steps.py --html=HTML_step_file_output.html --self-contained-html
i'd recommend using tables for this problem. i'm having a similar issue and as long as the table is just used to display some data and not for the main page layout it is fine.
Aside from @Verhás István answer (which I like), I was expecting a one-liner for the question:
${project.reporting.outputDirectory}
resolves to target/site
in your project.
Simplest way IMO is to include an ID and runat server tag on all your elements.
<div id="MYDIV" runat="server" />
Since it sounds like these are dynamically inserted controls, you might appreciate FindControl().
You can use dictionary :
x = 0
y = 1
z = 3
list=[]
dict = {0: 'c', 1: 'd', 2: 'e', 3: 'f'}
if x in dict:
list.append(dict[x])
else:
pass
if y in dict:
list.append(dict[y])
else:
pass
if z in dict:
list.append(dict[z])
else:
pass
print list
Here is something really neat and simple (atleast I believe so :)) and requires no manipulation of date to be cloned or overloading any of browser's native functions like toJSON (reference: How to JSON stringify a javascript Date and preserve timezone, courtsy Shawson)
Pass a replacer function to JSON.stringify that stringifies stuff to your heart's content!!! This way you don't have to do hour and minute diffs or any other manipulations.
I have put in console.logs to see intermediate results so it is clear what is going on and how recursion is working. That reveals something worthy of notice: value param to replacer is already converted to ISO date format :). Use this[key] to work with original data.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
This answer is not related to the above question, but I faced a similar issue, and maybe this will be useful to someone. I am trying to merge my feature branch to master like below:
$ git merge fix-load
for this got the following error message:
merge: fix-load - not something we can merge
I looked into above all solutions, but not none of the worked.
Finally, I realized the issue cause is a spelling mistake on my branch name (actually, the merge branch name is fix-loads
).
Using awk.
i starts at 0, i++
will increment the value of i, but return the original value that i held before being incremented.
awk '{print i++ "," $0}' file
Python uses "Duck typing", i.e. if a variable kwaks like a duck, it must be a duck. In your case, you probably want it to be iterable, or you want to access the item at a certain index. You should just do this: i.e. use the object in for var:
or var[idx]
inside a try
block, and if you get an exception it wasn't a duck...
Luke's answer didn't work for me. The 'New Window' command was already listed in the customize settings, but not showing up in the .js tabs context menu, despite deleting the registry setting.
So I used:
Tools
Customize...
Keyboard...
Scroll down to select Window.NewWindow
And I pressed and assigned the shortcut keys, Ctrl + Shift + W.
That worked for me.
==== EDIT ====
Well, 'worked' was too strong. My keyboard shortcut does indeed open another tab on the same JavaScript file, but rather unhelpfully it does not render the contents; it is just an empty white window! You may have better luck.
I haven't been able to find much evidence as to why you would want to choose C over C++.
You can hardly call what I'm about to say evidence; it's just my opinion.
People like C because it fits nicely inside the mind of the prgrammer.
There are many complex rules of C++ [when do you need virtual destructors, when can you call virtual methods in a constructor, how does overloading and overriding interact, ...], and to master them all takes a lot of effort. Also, between references, operator overloading and function overloading, understanding a piece of code can require you to understand other code that may or may not be easy to find.
A different question in why organizations would prefer C over C++. I don't know that, I'm just a people ;-)
In the defense of C++, it does bring valuable features to the table; the one I value most is probably parametric('ish) polymorphism, though: operations and types that takes one or more types as arguments.
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
I add those key in InfoPlist.strings
in iOS 8.4, iPad mini 2. It works too. I don't set any key, like NSLocationWhenInUseUsageDescription
, in my Info.plist
.
InfoPlist.strings:
"NSLocationWhenInUseUsageDescription" = "I need GPS information....";
Base on this thread, it said, as in iOS 7
, can be localized in the InfoPlist.strings. In my test, those keys can be configured directly in the file InfoPlist.strings
.
So the first thing you need to do is to add one or both of the > following keys to your Info.plist file:
- NSLocationWhenInUseUsageDescription
- NSLocationAlwaysUsageDescription
Both of these keys take a string which is a description of why you need location services. You can enter a string like “Location is required to find out where you are” which, as in iOS 7, can be localized in the InfoPlist.strings file.
UPDATE:
I think @IOS
's method is better. Add key to Info.plist
with empty value and add localized strings to InfoPlist.strings
.
somevar = tag.getArtist()
Do a git rebase -i FAR_ENOUGH_BACK
and drop the line for the commit you don't want.
This eclipse documentation has details on the markups in .project
file: The project description file
It describes the .project
file as:
When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"
For Scala developers, here it is recursive function to execute a full scan and map the contents of an AmazonS3 bucket using the official AWS SDK for Java
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{S3ObjectSummary, ObjectListing, GetObjectRequest}
import scala.collection.JavaConversions.{collectionAsScalaIterable => asScala}
def map[T](s3: AmazonS3Client, bucket: String, prefix: String)(f: (S3ObjectSummary) => T) = {
def scan(acc:List[T], listing:ObjectListing): List[T] = {
val summaries = asScala[S3ObjectSummary](listing.getObjectSummaries())
val mapped = (for (summary <- summaries) yield f(summary)).toList
if (!listing.isTruncated) mapped.toList
else scan(acc ::: mapped, s3.listNextBatchOfObjects(listing))
}
scan(List(), s3.listObjects(bucket, prefix))
}
To invoke the above curried map()
function, simply pass the already constructed (and properly initialized) AmazonS3Client object (refer to the official AWS SDK for Java API Reference), the bucket name and the prefix name in the first parameter list. Also pass the function f()
you want to apply to map each object summary in the second parameter list.
For example
val keyOwnerTuples = map(s3, bucket, prefix)(s => (s.getKey, s.getOwner))
will return the full list of (key, owner)
tuples in that bucket/prefix
or
map(s3, "bucket", "prefix")(s => println(s))
as you would normally approach by Monads in Functional Programming
You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:
public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
HSSFPalette palette = workbook.getCustomPalette();
HSSFColor hssfColor = null;
try {
hssfColor= palette.findColor(r, g, b);
if (hssfColor == null ){
palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
}
} catch (Exception e) {
logger.error(e);
}
return hssfColor;
}
And later use it for background color:
HSSFColor lightGray = setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);
https://forums.oracle.com/forums/thread.jspa?threadID=447344
The pertinent section reads:
There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.
There is also a button on the toolbar which is a "Fetch All
" button.
FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.
As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows()
procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.
This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
This worked for me to stop silly work breaks from happening within Chrome textareas
word-break: keep-all;
On latest version of NPM you can just do:
npm install gitAuthor/gitRepo#tag
If the repo is a valid NPM package it will be auto-aliased in package.json as:
{
"NPMPackageName": "gitAuthor/gitRepo#tag"
}
If you could add this to @justingordon 's answer there is no need for manual aliasing now !
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
The solutions here didn't work for me as I'm styling react components.
What worked though for the sidebar was
.sidebar{
position: sticky;
top: 0;
}
Hope this helps someone.
Have read the documentation you've linked. That's totally silly! xclip
is just a clipboard. You'll find other ways to copy paste the key... (I'm sure)
If you aren't working from inside a graphical X session you need to pass the $DISPLAY
environment var to the command. Run it like this:
DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub
Of course :0
depends on the display you are using. If you have a typical desktop machine it is likely that it is :0
I guess you want it along the curvature of the earth. Your two points and the center of the earth are on a plane. The center of the earth is the center of a circle on that plane and the two points are (roughly) on the perimeter of that circle. From that you can calculate the distance by finding out what the angle from one point to the other is.
If the points are not the same heights, or if you need to take into account that the earth is not a perfect sphere it gets a little more difficult.
If you just want the list, then you should ask here: http://unix.stackexchange.com
The answer is: cd / && find -name *.js
If you want to implement this, you have to specify the language.
Other suggested approaches:
Using the 'Print and then select save as pdf.' from your HTML file will result in loss of border edges, highlighting of syntax, trimming of plots etc.
Some other libraries have shown to be broken when it comes to using obsolete versions.
Solution: A better, hassle-free option is to use an online converter which will convert the *.html version of your *.ipynb to *.pdf.
Steps:
File > Download as > HTML(.html)
Upload the newly created *.html file here and then select the option HTML to PDF.
Your pdf file is now ready for download.
You now have .ipynb, .html and .pdf files
I think you want to set
tableView.alwaysBounceVertical = NO;
I know this is old, but if you want a similar PHP die()
function, you could do:
function die(reason) {
throw new Error(reason);
}
Usage:
console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");
The example above will only print "Hello".
Based on the existing answer(s) I'd like to add a "shorter" version without the if:
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
lastIndex += findStr.length() - 1;
count++;
}
System.out.println(count); // output: 3
A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.
When dealing with a hash {}
, use both the key and value to the block inside the ||
.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]
const http = require('http');_x000D_
const fs = require('fs');_x000D_
const url = require('url');_x000D_
const path = require('path');_x000D_
_x000D_
_x000D_
let mimeTypes = {_x000D_
'.html': 'text/html',_x000D_
'.css': 'text/css',_x000D_
'.js': 'text/javascript',_x000D_
'.jpg': 'image/jpeg',_x000D_
'.png': 'image/png',_x000D_
'.ico': 'image/x-icon',_x000D_
'.svg': 'image/svg+xml',_x000D_
'.eot': 'appliaction/vnd.ms-fontobject',_x000D_
'.ttf': 'aplication/font-sfnt'_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
http.createServer(function (request, response) {_x000D_
let pathName = url.parse(request.url).path;_x000D_
if(pathName === '/'){_x000D_
pathName = '/index.html';_x000D_
}_x000D_
pathName = pathName.substring(1, pathName.length);_x000D_
let extName = path.extName(pathName);_x000D_
let staticFiles = `${__dirname}/template/${pathName}`;_x000D_
_x000D_
if(extName =='.jpg' || extName == '.png' || extName == '.ico' || extName == '.eot' || extName == '.ttf' || extName == '.svg')_x000D_
{_x000D_
let file = fr.readFileSync(staticFiles);_x000D_
res.writeHead(200, {'Content-Type': mimeTypes[extname]});_x000D_
res.write(file, 'binary');_x000D_
res.end();_x000D_
}else {_x000D_
fs.readFile(staticFiles, 'utf8', function (err, data) {_x000D_
if(!err){_x000D_
res.writeHead(200, {'Content-Type': mimeTypes[extname]});_x000D_
res.end(data);_x000D_
}else {_x000D_
res.writeHead(404, {'Content-Type': 'text/html;charset=utf8'});_x000D_
res.write(`<strong>${staticFiles}</strong>File is not found.`);_x000D_
}_x000D_
res.end();_x000D_
});_x000D_
}_x000D_
}).listen(8081);
_x000D_
If you are trying to use javascript to avoid using SSL, think again. There are many half-way measures, but only SSL provides secure communication. Javascript encryption libraries can help against a certain set of attacks, but not a true man-in-the-middle attack.
The following article explains how to attempt to create secure communication with javascript, and how to get it wrong: Use JavaScript encryption module instead of SSL/HTTPS
Note: If you are looking for SSL for google app engine on a custom domain, take a look at wwwizer.com.
I solved this by putting two CardViews in a RelativeLayout. One with background of the border color and the other one with the image. (or whatever you wish to use)
Note the margin added to top and start for the second CardView. In my case I decided to use a 2dp thick border.
<android.support.v7.widget.CardView
android:id="@+id/user_thumb_rounded_background"
android:layout_width="36dp"
android:layout_height="36dp"
app:cardCornerRadius="18dp"
android:layout_marginEnd="6dp">
<ImageView
android:id="@+id/user_thumb_background"
android:background="@color/colorPrimaryDark"
android:layout_width="36dp"
android:layout_height="36dp" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/user_thumb_rounded"
android:layout_width="32dp"
android:layout_height="32dp"
app:cardCornerRadius="16dp"
android:layout_marginTop="2dp"
android:layout_marginStart="2dp"
android:layout_marginEnd="6dp">
<ImageView
android:id="@+id/user_thumb"
android:src="@drawable/default_profile"
android:layout_width="32dp"
android:layout_height="32dp" />
</android.support.v7.widget.CardView>
basename($_SERVER['REQUEST_URI'])
returns everything after and including the '?',
In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.
$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);
$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
In Python 3, dict.values()
(along with dict.keys()
and dict.items()
) returns a view
, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values()
in a call to list
like so:
v = list(d.values())
{names[i]:v[i] for i in range(len(names))}
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
Check documentation for model.fit here.
By setting verbose 0, 1 or 2 you just say how do you want to 'see' the training progress for each epoch.
verbose=0
will show you nothing (silent)
verbose=1
will show you an animated progress bar like this:
verbose=2
will just mention the number of epoch like this:
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
for what DB is the user? look at this example
mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
so to return to you question the "%" operator means all computers in your network.
like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:
SELECT user,password,host FROM user;
as soon as you got your user set up you should be able to connect like this:
mysql -h localhost -u gmeier -p
hope it helps
The default session timeout is defined into IIS to 20 minutes
Follow the procedures below for each site hosted on the IIS 8.5 web
Open the IIS 8.5 Manager.
Click the site name.
Select "Configuration Editor" under the "Management" section.
From the "Section:" drop-down list at the top of the configuration editor, locate "system.web/sessionState".
Set the "timeout" to "00:20:00 or less”, using the lowest value possible depending upon the application. Acceptable values are 5 minutes for high-value applications, 10 minutes for medium-value applications, and 20 minutes for low-value applications.
In the "Actions" pane, click "Apply".
Sometimes it happens when you duplicate files typically README sort of.
You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -
public static string GetInnerHtmlFromDiv(string url)
{
string HTML;
using (var wc = new WebClient())
{
HTML = wc.DownloadString(url);
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HTML);
HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
if (element != null)
{
return element.InnerHtml.ToString();
}
return null;
}
Another possible cause is to have the wrong order of RequestMapping attributes. As spring doc says:
An @RequestMapping handler method can have a very flexible signatures. The supported method arguments and return values are described in the following section. Most arguments can be used in arbitrary order with the only exception of BindingResult arguments. This is described in the next section.
If you scroll down the doc, you will see that the BindingResult has to be immediatelly after the model attribute, since we can have multiple model objects per request and thus multiple bindings
The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more than one model object and Spring will create a separate BindingResult instance for each of them so the following sample won’t work:
Here are two examples:
Invalid ordering of BindingResult and @ModelAttribute.
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... } Note, that there is a Model parameter in between Pet and BindingResult. To get this working you have to reorder the parameters as follows:
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
You can do this with SQL Server Management Studio.
? Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.
Rank and Dense rank gives the rank in the partitioned dataset.
Rank() : It doesn't give you consecutive integer numbers.
Dense_rank() : It gives you consecutive integer numbers.
In above picture , the rank of 10008 zip is 2 by dense_rank() function and 24 by rank() function as it considers the row_number.
Dictionaries are not Serializable in C# by default, I don't know why, but it seems to have been a design choice.
Right now, I'd recommend using Json.NET to convert it to JSON and from there into a dictionary (and vice versa). Unless you really need the XML, I'd recommend using JSON completely.
if ( defined $x && $x !~ m/\D/ ) {} or $x = 0 if ! $x; if ( $x !~ m/\D/) {}
This is a slight variation on Veekay's answer but let me explain my reasoning for the change.
Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.
Late one but hopefully useful since it adds more details…
There is no way to see queries executed in SSMS by default. There are several options though.
Reading transaction log – this is not an easy thing to do because its in proprietary format. However if you need to see queries that were executed historically (except SELECT) this is the only way.
You can use third party tools for this such as ApexSQL Log and SQL Log Rescue (free but SQL 2000 only). Check out this thread for more details here SQL Server Transaction Log Explorer/Analyzer
SQL Server profiler – best suited if you just want to start auditing and you are not interested in what happened earlier. Make sure you use filters to select only transactions you need. Otherwise you’ll end up with ton of data very quickly.
SQL Server trace - best suited if you want to capture all or most commands and keep them in trace file that can be parsed later.
Triggers – best suited if you want to capture DML (except select) and store these somewhere in the database
MYSQL PROCEDURE steps:
DELIMITER //
create PROCEDURE, you can refer syntax
NOTE: Don't forget to end statement with ' ; '
create procedure ProG() begin SELECT * FROM hs_hr_employee_leave_quota; end;//
delimiter ;
call ProG();
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
I did it like this:
Model.findOne({
where: {
condtions
}
}).then( j => {
return j.update({
field you want to update
}).then( r => {
return res.status(200).json({msg: 'succesfully updated'});
}).catch(e => {
return res.status(400).json({msg: 'error ' +e});
})
}).catch( e => {
return res.status(400).json({msg: 'error ' +e});
});
Use utcOffset function.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
console.log(localDate.format()); //2015-01-30T20:00:00+10:00
JTable.AUTO_RESIZE_LAST_COLUMN
is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!
So in your case this would be the correct way:
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
Just finish it up.
string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";
DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(
sqlCommand, new SqlConnection(connectionString)))
{
cmd.Connection.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
ds.Tables.Add(table);
}
return ds;
}
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.
See: Visual Studio Community 2017 component directory
But this kind of item is not available on all project types. Just try for yourself:
In a Console App (.NET Framework) is available;
In a Console App (.NET Core) is not available.
I couldn't find more info on future availability also for .NET Core projects.
The solution is to simply reinstall ggplot2
. Maybe there is an incompatibility between the R version you are using, and your installed version of ggplot2
. Alternatively, something might have gone wrong while installing ggplot2
earlier, causing the issue you see.
If you have Apache2.4 check 000-default.conf
- remove DocumentRoot
and add
Redirect permanent / https://[your-domain]/
As the accepted answer suggests you can add "using" to all views by adding to section of config file.
But for a single view you could just use
@using SomeNamespace.Extensions
The entry point for Java programs is the method:
public static void main(String[] args) {
//Code
}
If you do not have this, your program will not run.
Also, you may want to try Data::Dumper. Example:
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
in head
reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html
browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests
select case
when exists (select 1
from sales
where sales_type = 'Accessories')
then 'Y'
else 'N'
end as rec_exists
from dual;
I found results like the following ugly:
1 years, 2 months, 0 days, 0 hours, 53 minutes and 1 seconds
Because of that I realized a function that respects plurals, removes empty values and optionally it is possible to shorten the output:
function since($timestamp, $level=6) {
global $lang;
$date = new DateTime();
$date->setTimestamp($timestamp);
$date = $date->diff(new DateTime());
// build array
$since = array_combine(array('year', 'month', 'day', 'hour', 'minute', 'second'), explode(',', $date->format('%y,%m,%d,%h,%i,%s')));
// remove empty date values
$since = array_filter($since);
// output only the first x date values
$since = array_slice($since, 0, $level);
// build string
$last_key = key(array_slice($since, -1, 1, true));
$string = '';
foreach ($since as $key => $val) {
// separator
if ($string) {
$string .= $key != $last_key ? ', ' : ' ' . $lang['and'] . ' ';
}
// set plural
$key .= $val > 1 ? 's' : '';
// add date value
$string .= $val . ' ' . $lang[ $key ];
}
return $string;
}
Looks much better:
1 year, 2 months, 53 minutes and 1 second
Optionally use $level = 2
to shorten it as follows:
1 year and 2 months
Remove the $lang
part if you need it only in English or edit this translation to fit your needs:
$lang = array(
'second' => 'Sekunde',
'seconds' => 'Sekunden',
'minute' => 'Minute',
'minutes' => 'Minuten',
'hour' => 'Stunde',
'hours' => 'Stunden',
'day' => 'Tag',
'days' => 'Tage',
'month' => 'Monat',
'months' => 'Monate',
'year' => 'Jahr',
'years' => 'Jahre',
'and' => 'und',
);
I’d really suggest that people who encounter this problem go and find a third party database comparison tool.
Reason – these tools save a lot of time and make the process less error prone.
I’ve used comparison tools from ApexSQL (Diff and Data Diff) but you can’t go wrong with other tools marc_s and Marina Nastenko already pointed out.
If you’re absolutely sure that you are only going to compare tables once then SQL is fine but if you’re going to need this from time to time you’ll be better off with some 3rd party tool.
If you don’t have budget to buy it then just use it in trial mode to get the job done.
I hope new readers will find this useful even though it’s a late answer…
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
According to the documentation for 3.4, It is preferred to use attributes with attr()
method.
$('<div></div>').attr(
{
id: 'some dynanmic|static id',
"class": 'some dynanmic|static class'
}
).click(function() {
$( "span", this ).addClass( "bar" ); // example from the docs
});
Could you not 'stringify' your object...then use sessionStorage.setItem()
to store that string representation of your object...then when you need it sessionStorage.getItem()
and then use $.parseJSON()
to get it back out?
Working example http://jsfiddle.net/pKXMa/
Type info variables
to list "All global and static variable names".
Type info locals
to list "Local variables of current stack frame" (names and values), including static variables in that function.
Type info args
to list "Arguments of the current stack frame" (names and values).
Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.
Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin
.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
You're running the code before the DOM is loaded.
Try this:
Live example:
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
The default port 1433 is used when there is only one SQL Server named instance running on the computer.
When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.
You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch
.
In the service:
factory('aService', function() {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
//example of when you may want to notify observers
this.foo = someNgResource.query().$then(function(){
notifyObservers();
});
});
And in the controller:
function FooCtrl($scope, aService){
var updateFoo = function(){
$scope.foo = aService.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
We can check by Four ways
The first way is
BOOL flagWayOne = TRUE;
NSLog(@"The flagWayOne result is - %@",flagWayOne ? @"TRUE":@"FALSE");
The second way is
BOOL flagWayTwo = YES;
NSLog(@"The flagWayTwo result is - %@",flagWayTwo ? @"YES":@"NO");
The third way is
BOOL flagWayThree = 1;
NSLog(@"The flagWayThree result is - %d",flagWayThree ? 1:0);
The fourth way is
BOOL flagWayFour = FALSE; // You can set YES or NO here.Because TRUE = YES,FALSE = NO and also 1 is equal to YES,TRUE and 0 is equal to FALSE,NO whatever you want set here.
NSLog(@"The flagWayFour result is - %s",flagWayFour ? YES:NO);
While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date
object instead of a datetime.datetime
. So for those searching and finding this thread:
datetime.date
has no .strptime
method; use the one on datetime.datetime
instead and then call .date()
on it to receive the datetime.date
object.
Like so:
>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)
./version.sh
or version.bat
If there are no version.bat or version.sh then use a tool to unzipping JAR files (\tomcat\server\lib\catalina.jar) and look in the file org\apache\catalina\util\lib\ServerInfo.properties. the version defined under "server.info=".
Catching an exception while using a Python 'with' statement
The with statement has been available without the __future__
import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:
from __future__ import with_statement
Here's the closest thing to correct that you have. You're almost there, but with
doesn't have an except
clause:
with open("a.txt") as f: print(f.readlines()) except: # <- with doesn't have an except clause. print('oops')
A context manager's __exit__
method, if it returns False
will reraise the error when it finishes. If it returns True
, it will suppress it. The open
builtin's __exit__
doesn't return True
, so you just need to nest it in a try, except block:
try:
with open("a.txt") as f:
print(f.readlines())
except Exception as error:
print('oops')
And standard boilerplate: don't use a bare except:
which catches BaseException
and every other possible exception and warning. Be at least as specific as Exception
, and for this error, perhaps catch IOError
. Only catch errors you're prepared to handle.
So in this case, you'd do:
>>> try:
... with open("a.txt") as f:
... print(f.readlines())
... except IOError as error:
... print('oops')
...
oops
You might want to look at the RouteLink()
method.That one lets you specify everything (except the link text and route name) via a dictionary.
git add myfile.h
git commit -m "your commit message"
git push -u origin master
if you don't remember all the files you need to update, use
git status
In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.
it may be another mysqld instance running and stoped it with:
sudo service mysql stop
Worked for me.
Add this to your python script.
import os
os.system("exec /path/to/another/script")
This executes that command as if it were typed into the shell.
delimiter //
CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
declare str VARCHAR(255) default '';
declare x INT default 0;
SET x = 1;
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
select str;
END//
Which prints:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
delimiter //
CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 5;
SET str = '';
REPEAT
SET str = CONCAT(str,x,',');
SET x = x - 1;
UNTIL x <= 0
END REPEAT;
SELECT str;
END//
Which prints:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
delimiter //
CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = -5;
SET str = '';
loop_label: LOOP
IF x > 0 THEN
LEAVE loop_label;
END IF;
SET str = CONCAT(str,x,',');
SET x = x + 1;
ITERATE loop_label;
END LOOP;
SELECT str;
END//
Which prints:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx
If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.
Why not just call list()
on the Queryset
?
answers_list = list(answers)
This will also evaluate the QuerySet
/run the query. You can then remove/add from that list.
I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.
IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.
check out the documentation and the demo.
try json_decode like so
<?php
$var = '["SupplierInvoiceReconciliation"]';
$var = json_decode($var, TRUE);
print_r($var);
?>
When XML first came out, we were told it would solve all our problems: XML will be user-friendly, infinitely extensible, avoid strong-typing, and not require any programming skills. I learnt about DTD's and wrote my own XML parser. 15+ years later, I see that most XML is not user-friendly, and not very extensible (depending on its usage). As soon as some clever clogs hooked up XML to a database I knew that data types were all but inevitable. And, you should see the XSLT (transformation file) I had to work on the other day. If that isn't programming, I don't know what is! Nowadays it's not unusual to see all kinds of problems relating to XML data or interfaces gone bad. I love XML but, it has strayed far from its original altruistic starting point.
The short answer? DTD's have been deprecated in favor of XSD's because an XSD lets you define an XML structure with more precision.
I was able to get this to work...
SELECT CAST('<![CDATA[' + LargeTextColumn + ']]>' AS XML) FROM TableName;
With your own Code and a Slight Change withou jQuery,
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
console.log(httpGet(url,key));
}
function httpGet(url,key){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send(null);
return xmlHttp.responseText;
}
Thank You
You can use a query to get the same:
SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;
Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"
To avoid above we can use the IsNull
keyword to get the same.
SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;
If anyone containing null value the ' ' (space) will add with next value.
The local names for a function are decided when the function is defined:
>>> x = 1
>>> def inc():
... x += 5
...
>>> inc.__code__.co_varnames
('x',)
In this case, x
exists in the local namespace. Execution of x += 5
requires a pre-existing value for x
(for integers, it's like x = x + 5
), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError
is named as such.
Compare the other version, where x
is not a local variable, so it can be resolved at the global scope instead:
>>> def incg():
... print(x)
...
>>> incg.__code__.co_varnames
()
Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
Any of these will work from the shell command line. bc
is probably your most straight forward solution though.
Using bc:
$ echo "$d1 - $d2" | bc
Using awk
:
$ echo $d1 $d2 | awk '{print $1 - $2}'
Using perl
:
$ perl -E "say $d1 - $d2"
Using Python
:
$ python -c "print $d1 - $d2"
all return
4
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
The following code must be put at the end of your HTML file so that once the content has loaded, the script will be executed and the window will print.
<script type="text/javascript">
<!--
window.print();
//-->
</script>
Use my extensions :
Number.prototype.isEven=function(){
return this % 2===0;
};
Number.prototype.isOdd=function(){
return !this.isEven();
}
then
var a=5;
a.isEven();
==False
a.isOdd();
==True
if you are not sure if it is a Number , test it by the following branching :
if(a.isOdd){
a.isOdd();
}
UPDATE :
if you would not use variable :
(5).isOdd()
It turns out that Procedural paradigm is better than OOP paradigm . By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .
Actually I think using plain slices is the best solution in this case:
for i in range(0, len(data), 100):
chunk = data[i:i + 100]
...
If you want to avoid copying the slices, you could use itertools.islice()
, but it doesn't seem to be necessary here.
The itertools()
documentation also contains the famous "grouper" pattern:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.
Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.
I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below
ORIGINALLY
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
MADE A NEW FUNCTION upload
and called passed onSubmit
and event as arguments
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}
I have found this to be the easiest way by far.
Use this method:
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
And use it like this:
String json = getJSON(url);
JSONObject obj;
try {
obj = new JSONObject(json);
JSONArray results_arr = obj.getJSONArray("results");
final int n = results_arr.length();
for (int i = 0; i < n; ++i) {
// get the place id of each object in JSON (Google Search API)
String place_id = results_arr.getJSONObject(i).getString("place_id");
}
}
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
In bootstrap tooltip just use data-html="true"
I'd recommend the Range object's AutoFill method for this:
rngSource.AutoFill Destination:=rngDest
Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.
It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.
Here's an example:
'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"
'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")
Hope this helps.
E-satis's response is the correct way to determine the file extension.
Alternatively, instead of relying on a files extension, you could use the fileinfo to determine the files MIME type.
Here's a simplified example of processing an image uploaded by a user:
// Code assumes necessary extensions are installed and a successful file upload has already occurred
// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');
// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {
case 'image/jpg':
$im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case 'image/png':
$im = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
case 'image/gif':
$im = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
}
You have a misplaced closing brace before the return
statement.
Edit your conf/log4j.properties
file and change the following line:
log4j.rootCategory=INFO, console
to
log4j.rootCategory=ERROR, console
Another approach would be to :
Start spark-shell and type in the following:
import org.apache.log4j.Logger
import org.apache.log4j.Level
Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)
You won't see any logs after that.
Other options for Level include: all
, debug
, error
, fatal
, info
, off
, trace
, trace_int
, warn
key = cv2.waitKey(1)
This is from the openCV package. It detects a keypress without waiting.
Everything in MySQL seems to be done closer to the metal than in MSSQL, And the documentation treats it that way. Especially for optimization, you'll need to understand how indexes, system configuration, and the optimizer interact under various circumstances.
The "optimizer" is more a parser. In MSSQL your query plan is often a surprise (usually good, sometimes not). In MySQL, it pretty much does what you asked it to do, the way you expected it to. Which means you yourself need to have a deep understanding of the various ways it might be done.
Not built around a good TRANSACTION model (default MyISAM engine).
File-system setup is your problem.
All the database configuration is your problem - especially various cache sizes.
Sometimes it seems best to think of it as an ad-hoc, glorified isam. Codd and Date don't carry much weight here. They would say it with no embarrassment.
.arrow {_x000D_
display : inline-block;_x000D_
font-size: 10px; /* adjust size */_x000D_
line-height: 1em; /* adjust vertical positioning */_x000D_
border: 3px solid #000000;_x000D_
border-left: transparent;_x000D_
border-bottom: transparent;_x000D_
width: 1em; /* use font-size to change overall size */_x000D_
height: 1em; /* use font-size to change overall size */_x000D_
}_x000D_
_x000D_
.arrow:before {_x000D_
content: "\00a0"; /* needed to hook line-height to "something" */_x000D_
}_x000D_
_x000D_
.arrow.left {_x000D_
margin-left: 0.5em;_x000D_
-webkit-transform: rotate(225deg);_x000D_
-moz-transform: rotate(225deg);_x000D_
-o-transform: rotate(225deg);_x000D_
-ms-transform: rotate(225deg);_x000D_
transform: rotate(225deg);_x000D_
}_x000D_
_x000D_
.arrow.right {_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-moz-transform: rotate(45deg);_x000D_
-o-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
.arrow.top {_x000D_
line-height: 0.5em; /* use this to adjust vertical positioning */_x000D_
margin-left: 0.5em;_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(-45deg);_x000D_
-moz-transform: rotate(-45deg);_x000D_
-o-transform: rotate(-45deg);_x000D_
-ms-transform: rotate(-45deg);_x000D_
transform: rotate(-45deg);_x000D_
}_x000D_
_x000D_
.arrow.bottom {_x000D_
line-height: 2em;_x000D_
/* use this to adjust vertical positioning */_x000D_
margin-left: 0.5em;_x000D_
margin-right: 0.5em;_x000D_
-webkit-transform: rotate(135deg);_x000D_
-moz-transform: rotate(135deg);_x000D_
-o-transform: rotate(135deg);_x000D_
-ms-transform: rotate(135deg);_x000D_
transform: rotate(135deg);_x000D_
}
_x000D_
<div>_x000D_
here are some arrows_x000D_
<div class='arrow left'></div> space_x000D_
<div class='arrow right'></div> space_x000D_
<div class='arrow top'></div> space_x000D_
<div class='arrow bottom'></div> space with proper spacing?_x000D_
</div>
_x000D_
Similar to Roko C, but a little more control over size and placement.
Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".
An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.
For example, here is a completely imaginary case with a pseudo language:
You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:
book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // I over simplify ...
while (row = data.next())
{
book = new Book();
book.setAuthor(row.get('author');
book_list.add(book);
}
With an ORM library, it would look like this:
book_list = BookTable.query(author="Linus");
The mechanical part is taken care of automatically via the ORM library.
Using ORM saves a lot of time because:
Using an ORM library is more flexible because:
But ORM can be a pain:
for
loop.Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:
If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:
Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.
background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}