Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
<?PHP
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio == 'male') {
$male_status = 'checked';
}else if ($selected_radio == 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
<FORM name ="form1" method ="post" action ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'
<?PHP print $male_status; ?>
>Male
<Input type = 'Radio' Name ='gender' value= 'female'
<?PHP print $female_status; ?>
>Female
<P>
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>
Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.
In Access, there are two types:
2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.
3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.
Minor quibble with the answers:
There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:
?Me!MyCheckBox.Value
?Me!MyCheckBox
The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:
If Me!MyCheckBox Then
...write one of these options:
If (Me!MyCheckBox) Then ' forces evaluation of the control
If Me!MyCheckBox = True Then
If (Me!MyCheckBox = True) Then
If (Me!MyCheckBox = Not False) Then
Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.
Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.
I wanted to replicate Unix/Linux's cp -r
as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e
Copies directories and subdirectories, including empty ones.
/k
Copies attributes. Normal Xcopy will reset read-only attributes.
/h
Copies hidden and system files also.
/i
If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat
) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q
Quiet. Do not display file names while copying.
/b
Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o
Copies directory and file ACLs. (requires UAC admin)
Media that is designed for textual data is of course eventually binary as well, but textual media often use certain binary values for control characters. Also, textual media may reject certain binary values as non-text.
Base64 encoding encodes binary data as values that can only be interpreted as text in textual media, and is free of any special characters and/or control characters, so that the data will be preserved across textual media as well.
For example:
sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data {
public static void main(String[] args) {
Map<String, String> data = new HashMap<String, String>();
data.put("John", "Taxi Driver");
data.put("Mark", "Professional Killer");
}
}
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data {
private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data {
private static final Map<String, String> DATA = new HashMap<>();
static {
DATA.put("John", "Taxi Driver");
}
}
Sometimes web browsers seems to be more forgiving if you use the Unicode string ­
rather than the ­
entity.
Couldn't resist to add another method, using childElementCount
. It returns the number of child element nodes from a given parent, so you can loop over it.
for(var i=0, len = parent.childElementCount ; i < len; ++i){
... do something with parent.children[i]
}
Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<webResources>
<resources>
<directory>WebContent</directory>
<includes>
<include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
</includes>
<excludes>
<exclude>*.java</exclude>
</excludes>
</resources>
</webResources>
<webXml>WebContent/WEB-INF/web.xml</webXml>
</configuration>
</plugin>
pthread_self()
function will give the thread id of current thread.
pthread_t pthread_self(void);
The pthread_self()
function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np()
to return an integral identifier for the thread.
NOTE:
pthread_id_np_t tid;
tid = pthread_getthreadid_np();
is significantly faster than these calls, but provides the same behavior.
pthread_id_np_t tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
I have experienced the GUIDs not being unique during multi-threaded/multi-process unit-testing (too?). I guess that has to do with, all other tings being equal, the identical seeding (or lack of seeding) of pseudo random generators. I was using it for generating unique file names. I found the OS is much better at doing that :)
You ask if GUIDs are 100% unique. That depends on the number of GUIDs it must be unique among. As the number of GUIDs approach infinity, the probability for duplicate GUIDs approach 100%.
Thanks Jason Rogers's answer first.
In Android && cpp should be this:
const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
Can fix this errors:
1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'
3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'
4.add "env->DeleteLocalRef(nativeString);" at end.
I also had problems because my program interpreter was /lib/ld-linux.so.2 however it was on an embedded device, so I solved the problem by asking gcc to use ls-uClibc instead as follows:
-Wl,--dynamic-linker=/lib/ld-uClibc.so.0
There is already an ISO standard for this; no need to invent your own scheme:
http://en.wikipedia.org/wiki/ISO_5218
Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.
Given Enum1 value = ...
, then if you mean by name:
Enum2 value2 = (Enum2) Enum.Parse(typeof(Enum2), value.ToString());
If you mean by numeric value, you can usually just cast:
Enum2 value2 = (Enum2)value;
(with the cast, you might want to use Enum.IsDefined
to check for valid values, though)
How about this?
def replace_all(dict, str):
for key in dict:
str = str.replace(key, dict[key])
return str
then
print(replace_all({"&":"\&", "#":"\#"}, "&#"))
output
\&\#
similar to answer
Use backticks.
$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`
Then fetch the output of the producer script as an argument on the consumer script.
The standard error (SE) is just the standard deviation of the sampling distribution. The variance of the sampling distribution is the variance of the data divided by N and the SE is the square root of that. Going from that understanding one can see that it is more efficient to use variance in the SE calculation. The sd
function in R already does one square root (code for sd
is in R and revealed by just typing "sd"). Therefore, the following is most efficient.
se <- function(x) sqrt(var(x)/length(x))
in order to make the function only a bit more complex and handle all of the options that you could pass to var
, you could make this modification.
se <- function(x, ...) sqrt(var(x, ...)/length(x))
Using this syntax one can take advantage of things like how var
deals with missing values. Anything that can be passed to var
as a named argument can be used in this se
call.
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
Refer below code for formatting date
long strDate1 = 1346524199000;
Date date=new Date(strDate1);
try {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
date = df2.format(format.parse("yourdate");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)action
(will render as click
on command links/buttons)The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
Simple solution for downloading a file from the server:
protected void btnDownload_Click(object sender, EventArgs e)
{
string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "image/jpeg";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(Server.MapPath("~/File/001.jpg"));
response.Flush();
response.End();
}
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
You can use this to get border on one side
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
EDITED
As many including me wanted to have a one side border with transparent background, I have implemented a BorderDrawable
which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a BorderFrameLayout
in which your layout can be wrapped.
See my github for the complete source.
I found this for you: Jump between braces in Visual Studio:
Put your cursor before or after the brace (your choice) and then press CTRL + ]. It works with parentheses ( ), brackets [ ] and braces { }. From now on you don’t need to play Where’s Waldo? to find that brace.
On MacOS, use CMD + SHIFT + \
Eclipse is recommending that you declare the type of the HashMap because that enforces some type safety. Of course, it sounds like you're trying to avoid type safety from your second part.
If you want to do the latter, try declaring map as HashMap<String,Object>
.
If you using the updated or 2018 Version for Android Studio...
compile 'com.android.support:recyclerview-v7:+'
will give you an error with following message "Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. It will be removed at the end of 2018."
Try using this
implementation 'com.android.support:recyclerview-v7:+'
One possible reason is because you are declaring a virtual function without defining it.
When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).
An example of defining the virtual function is:
virtual void fn() { /* insert code here */ }
In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.
The line
virtual void fn();
declares fn()
without defining it and will cause the error message you asked about.
It's very similar to the code:
extern int i;
int *pi = &i;
which states that the integer i
is declared in another compilation unit which must be resolved at link time (otherwise pi
can't be set to it's address).
As you are trying to add a string of CSS to <head>
with JavaScript?
injecting a string of CSS into a page it is easier to do this with the <link>
element than the <style>
element.
The following adds p { color: green; }
rule to the page.
<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />
You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF
attribute. Much simpler than all the quirks of <style>
elements or directly accessing stylesheets.
var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));
This will work in IE 5.5 upwards
The solution you have marked will work but this solution requires fewer dom operations and only a single element.
Did you already check your proxys here?
git config --global --list
or
git config --local --list
A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
};
List.indexOf()
will give you what you want, provided you know precisely what you're after, and provided that the equals()
method for Party
is well-defined.
Party searchCandidate = new Party("FirstParty");
int index = cave.parties.indexOf(searchCandidate);
This is where it gets interesting - subclasses shouldn't be examining the private properties of their parents, so we'll define equals()
in the superclass.
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CaveElement)) {
return false;
}
CaveElement that = (CaveElement) o;
if (index != that.index) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
return true;
}
It's also wise to override hashCode
if you override equals
- the general contract for hashCode
mandates that, if x.equals(y)
, then x.hashCode() == y.hashCode().
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + index;
return result;
}
Based on Guy Daher's answer.
I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.
I would do nil check if statement:
class CustomView: UIView
{
override func draw(_ rect: CGRect)
{
super.draw(rect)
if let context = UIGraphicsGetCurrentContext()
{
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
I personally use Style It for inline-style in React or keep my style separately in a CSS or SASS file...
But if you are really interested doing it inline, look at the library, I share some of the usages below:
In the component:
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro {
font-size: 40px;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
);
}
}
export default Intro;
Output:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 40px;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
Also you can use JavaScript variables with hover in your CSS as below :
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
const fontSize = 13;
return Style.it(`
.intro {
font-size: ${ fontSize }px; // ES2015 & ES6 Template Literal string interpolation
}
.package {
color: blue;
}
.package:hover {
color: aqua;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
And the result as below:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 13px;
}
._scoped-1 .package {
color: blue;
}
._scoped-1 .package:hover {
color: aqua;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
One can also get "Skipping JaCoCo execution due to missing execution data file" error due to missing tests in project. For example when you fire up new project and have no *Test.java files at all.
Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.
if location == a2:
img = Image.open("picture.jpg")
Img.show
Make sure the name of the image is in parantheses this should work
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
The following will work independent of your database privileges:
select * from all_triggers
where table_name = 'YOUR_TABLE'
The following alternate options may or may not work depending on your assigned database privileges:
select * from DBA_TRIGGERS
or
select * from USER_TRIGGERS
I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!
<?xml version="1.0" encoding="UTF-8"?>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jst.java" version="6.0"/>
<installed facet="jst.utility" version="1.0"/>
There are many ways, for example:
Method one:
public string test()
{
string ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
return ErrMsg
}
Method two:
public void test(ref string ErrMsg )
{
ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
}
If you are behind a proxy server this issue could happen i had the same issue and was solved by: Preferences -> General -> Proxy Settings -> No Proxy.
"Maybe the tomcat ready-message was sent to the proxy - and never reached the IDE."
found @: https://netbeans.org/bugzilla/show_bug.cgi?id=231220
Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.
You need to detect the OS your program is running on, then:
For Linux -
import subprocess
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)
For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html
More resources:
Print PDF document with python's win32print module?
How do I print to the OS's default printer in Python 3 (cross platform)?
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
EDIT: Some clarification.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
This is parsed as an "array of references" - which isn't legal.
Instances of the String
constructor have a .search()
method which accepts a RegExp and returns the index of the first match.
To start the search from a particular position (faking the second parameter of .indexOf()
) you can slice
off the first i
characters:
str.slice(i).search(/re/)
But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i
) to the returned index if it wasn't -1
. This will give you the index in the original string:
function regexIndexOf(text, re, i) {
var indexInSuffix = text.slice(i).search(re);
return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}
For Angular:
getUserPicture(userId) {
FB.api('/' + userId, {fields: 'picture.width(800).height(800)'}, function(response) {
console.log('getUserPicture',response);
});
}
If you don't want to use jquery, use this:
<script>
// without jquery
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
// run your open popup function after 5 sec = 5000
PopUp();
}, 5000)
});
</script>
OR With jquery
<script>
$(document).ready(function(){
setTimeout(function(){
// open popup after 5 seconds
PopUp();
},5000);
});
</script>
Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.
$original = (
[0] => Array
(
[title] => Speed
[width] => 14
)
[1] => Array
(
[title] => Date
[width] => 18
)
[2] => Array
(
[title] => Pineapple
[width] => 30
)
)
Adding an item in same format to this array will add all new array indexes as items instead of just item.
$new = array(
'title' => 'Time',
'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new; // replaced with actual item
Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.
You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.
The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])
So, I'm used to use
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.
modifying the first answer you are able to switch between n functions :
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="Generator" content="EditPlus.com®">_x000D_
<!-- <script src="../js/jquery.js"></script> -->_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>_x000D_
<title>my stupid example</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<nav>_x000D_
<div>b<sub>1</sub></div>_x000D_
<div>b<sub>2</sub></div>_x000D_
<div>b<sub>3</sub></div>_x000D_
<!-- .......... -->_x000D_
<div>b<sub>n</sub></div>_x000D_
</nav>_x000D_
<script type="text/javascript">_x000D_
<!--_x000D_
$(document).ready(function() {_x000D_
(function($) {_x000D_
$.fn.clickToggle = function() {_x000D_
var ta=arguments;_x000D_
this.data('toggleclicked', 0);_x000D_
this.click(function() {_x000D_
id= $(this).index();console.log( id );_x000D_
var data = $(this).data();_x000D_
var tc = data.toggleclicked;_x000D_
$.proxy(ta[id], this)();_x000D_
data.toggleclicked = id_x000D_
});_x000D_
return this;_x000D_
};_x000D_
}(jQuery));_x000D_
_x000D_
_x000D_
$('nav div').clickToggle(_x000D_
function() {alert('First handler');}, _x000D_
function() {alert('Second handler');},_x000D_
function() {alert('Third handler');}_x000D_
//...........how manny parameters you want....._x000D_
,function() {alert('the `n handler');}_x000D_
);_x000D_
_x000D_
});_x000D_
//-->_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
select ISNULL(CONVERT(VARCHAR(23), WorkingDate,121),'') from uv_Employee
If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data
and you have some function find_definition()
which gets the definition, you can do something like the following:
for word in data:
data[word] = find_definition(word)
You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )
subsequent_amount = invest(initial_amount,top_company(5,year,year+1))
Update
Since extract_numeric
is deprecated, we can use parse_number
from readr
package.
library(readr)
parse_number(years)
Here is another option with extract_numeric
library(tidyr)
extract_numeric(years)
#[1] 20 1
A fairly simple option would be to create a javascript function called on the form's "onsubmit" event to enable the radiobutton back so that it's value is posted with the rest of the form.
It does not seem to be an omission on HTML specs, but a design choice (a logical one, IMHO), a radiobutton can't be readonly as a button can't be, if you don't want to use it, then disable it.
Why do you want to generate all the sql by hand? Have you looked at an ORM like Hibernate Depending on your project it will probably do at least 95% of what you need, do it in a cleaner way then raw SQL, and if you need to get the last bit of performance you can create the SQL queries that need to be hand tuned.
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);
//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
NSLog("File not exist");
} else {
NSLog("File exist");
}
//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
cell.photoImageView.image = image;//Display image
}
GROUP BY
lets you use aggregate functions, like AVG
, MAX
, MIN
, SUM
, and COUNT
.
On the other hand DISTINCT
just removes duplicates.
For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:
SELECT department, SUM(amount) FROM purchases GROUP BY department
This will give you one row per department, containing the department name and the sum of all of the amount
values in all rows for that department.
If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.
Since these previous answers above, there is now a release of an Eclipse Plugin to assist with development using AngularJS:
https://marketplace.eclipse.org/content/angularjs-eclipse https://github.com/angelozerr/angularjs-eclipse/wiki/Installation---Update-Site (take a look around the other Wiki pages for information on features)
The release at the time of the answer is 0.1.0.
Please also checkout JSDT (http://www.eclipse.org/webtools/jsdt/) and also Eclipse VJET (http://eclipse.org/vjet/). The VJET project appears to be an attempt to provide better feature sets to the editor without being encumbered by the JSDT project (open source politics at play I guess).
Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. :)
https://github.com/paulopmx/Flexigrid - Flexgrid
http://datatables.net/index - Data tables.
https://github.com/tonytomov/jqGrid
If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.
To create apk in android studio,go to build menu->build bundles/apk->build apk
it will make the apk file of your project.After this the apk will be available in your
project directory->app->build->outputs->apk->debug->app-debug.apk
On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR
make variable, so you can often do:
make install DESTDIR=/tmp/myinst/
sudo cp -va /tmp/myinst/ /
The advantage of this approach is that make install
don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
From a performance point of view, (and on the assumption that you read more than you write)
I think the best way would be to pre calculate and store a stripped version of the column, This way you do the transform less.
You can then put an index on the new column and get the database to do the work for you.
You can find examples for writing OAuth clients here:
In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails
. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:
@EnableOAuth2Client
@Configuration
class MyConfig{
@Value("${oauth.resource:http://localhost:8082}")
private String baseUrl;
@Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
private String authorizeUrl;
@Value("${oauth.token:http://localhost:8082/oauth/token}")
private String tokenUrl;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource;
resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("restapp");
resource.setClientSecret("restapp");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("**USERNAME**");
resource.setPassword("**PASSWORD**");
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
Do not forget about @EnableOAuth2Client
on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger
with debug
enabled set.
Good luck
I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .
you should use only english version of phpmyadmin if you are using all languages you should enable all languages mbstring in php.in file.....just search for mbstring in php.in
The following works:
@NonCPS
def printParams() {
env.getEnvironment().each { name, value -> println "Name: $name -> Value $value" }
}
printParams()
Note that it will most probably fail on first execution and require you approve various groovy methods to run in jenkins sandbox. This is done in "manage jenkins/in-process script approval"
The list I got included:
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
=>Create a new table directly with the following query:
CREATE TABLE table_name (Column_1 TEXT,Column_2 TEXT);
=>Now insert the data into table_name from existing_table with the following query:
INSERT INTO table_name (Column_1,Column_2) FROM existing_table;
=>Now drop the existing_table by following query:
DROP TABLE existing_table;
I think I ran into the similar problem. If you started a local git repository but have not set up a remote git project and want to push your local project to to git project.
1) create a remote git project and note the URL of project
2) open/edit your local git project
3) in the VS terminal type: git push --set-upstream [URL of project]
to leave the file in the repo but ignore future changes to it:
git update-index --assume-unchanged <file>
and to undo this:
git update-index --no-assume-unchanged <file>
to find out which files have been set this way:
git ls-files -v|grep '^h'
credit for the original answer to http://blog.pagebakers.nl/2009/01/29/git-ignoring-changes-in-tracked-files/
What fixed it for me was right clicking on project > Maven > Update Project
Bubble sort with sort direction -
using System;
public class Program
{
public static void Main(string[] args)
{
var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
BubbleSort(input);
Array.ForEach(input, Console.WriteLine);
Console.ReadKey();
}
public enum Direction
{
Ascending = 0,
Descending
}
public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
{
bool swapped;
var length = input.Length;
do
{
swapped = false;
for (var index = 0; index < length - 1; index++)
{
var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
if (needSwap)
{
var temp = input[index];
input[index] = input[index + 1];
input[index + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
$(document).on("keydown","form", function(event)
{
node = event.target.nodeName.toLowerCase();
type = $(event.target).prop('type').toLowerCase();
if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
{
event.preventDefault();
return false;
}
});
It works perfectly!
public boolean dispatchTouchEvent(MotionEvent ev){
boolean consume =false;
if(onInterceptTouchEvent(ev){
consume = onTouchEvent(ev);
}else{
consume = child.dispatchTouchEvent(ev);
}
}
i found this js fiddle. this works like this
function unescapeHTML(html) {
var escapeEl = document.createElement('textarea');
escapeEl.innerHTML = html;
return escapeEl.textContent;
}
<textarea className="form-control redactor"
rows="5" cols="9"
defaultValue={unescapeHTML(this.props.destination.description)}
name='description'></textarea>
jsfiddle link
Take a look at this... http://getbootstrap.com/
For big websites I use Bootstrap and sometimes (for simple websites) I create all the style with some @mediaqueries. It's very simple, just think all the code in percentage.
.container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
}
Inside the container, your structure must have widths in percentage like this...
.col-1 {
width: 40%;
float: left;
}
.col-2 {
width: 60%;
float: left;
}
@media screen and (max-width: 320px) {
.col-1, .col-2 { width: 100%; }
}
In some simple interfaces, if you start to develop the project in this way, you will have great chances to have a fully responsive site using break points only to adjust the flow of objects.
Files.move(source, target, REPLACE_EXISTING);
You can use the Files
object
Read more about Files
For starters,
mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.
Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.
From line 215, update:
if (isset($_POST)) {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$C_Email = $_POST['C_Email'];
$Password = $_POST['password'];
$C_Password = $_POST['c_password'];
$SecQ = $_POST['SecQ'];
$SecA = $_POST['SecA'];
}
POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.
You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:
if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}
Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm
Target framework
.Net framework 4.0 Client Profile
then change it to .Net Framework 4.0
It works now
var topViewController: UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while let presentedViewController = topViewController.presentedViewController {
topViewController = presentedViewController
}
return topViewController
}
Customizing the Calendar and Date while Marshaling
Step 1 : Prepare jaxb binding xml for custom properties, In this case i prepared for date and calendar
<jaxb:bindings version="2.1" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jaxb:globalBindings generateElementProperty="false">
<jaxb:serializable uid="1" />
<jaxb:javaType name="java.util.Date" xmlType="xs:date"
parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDate"
printMethod="com.stech.jaxb.util.CalendarTypeConverter.printDate" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="com.stech.jaxb.util.CalendarTypeConverter.printCalendar" />
Setp 2 : Add custom jaxb binding file to Apache or any related plugins at xsd option like mentioned below
<xsdOption>
<xsd>${project.basedir}/src/main/resources/tutorial/xsd/yourxsdfile.xsd</xsd>
<packagename>com.tutorial.xml.packagename</packagename>
<bindingFile>${project.basedir}/src/main/resources/xsd/jaxbbindings.xml</bindingFile>
</xsdOption>
Setp 3 : write the code for CalendarConverter class
package com.stech.jaxb.util;
import java.text.SimpleDateFormat;
/**
* To convert the calendar to JaxB customer format.
*
*/
public final class CalendarTypeConverter {
/**
* Calendar to custom format print to XML.
*
* @param val
* @return
*/
public static String printCalendar(java.util.Calendar val) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
return simpleDateFormat.format(val.getTime());
}
/**
* Date to custom format print to XML.
*
* @param val
* @return
*/
public static String printDate(java.util.Date val) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(val);
}
}
Setp 4 : Output
<xmlHeader>
<creationTime>2014-09-25T07:23:05</creationTime> Calendar class formatted
<fileDate>2014-09-25</fileDate> - Date class formatted
</xmlHeader>
War -
distribute Java-based web applications. A WAR has the same file structure as a JAR file, which is a single compressed file that contains multiple files bundled inside it.
Jar -
The .jar files contain libraries, resources and accessories files like property files.
WAR files are used to combine JSPs, servlets, Java class files, XML files, javascript libraries, JAR libraries, static web pages, and any other resources needed to run the application.
I use Kate (KDE Advanced Text Editor) for most of my development, including Django. It has both a Python and Django Templates syntax higlighting. I switch to Quanta+ when a significant part of the project involves HTML.
Since it uses Kate's KPart, it's just as good for editing the Python parts, and for the HTML templates i have the whole Quanta+ tools, while still highligting Django-specific tags.
Update 2013: Unfortunately, Quanta+ has been dead for years now, and there's no hope that it will ever be resurrected. Also, there's no other usable HTML editor out there, so it's Kate all the time now.
Goto Start -> Programs -> Microsoft SQL ServerYYYY -> Configuration Tools -> SQL Server YYYY Configuration Manager or run "SQLServerManager12.msc".
Make sure that TCP/IP is enabled under Client Protocols.
Then go into "SQL Server Network Configuration" and double click TCP/IP. Click the "IP Addresses" tab and scroll to the bottom. Under "IP All" remove TCP Dynamic Ports if it is present and set TCP Port to 1433. Click OK and then go back to "SQL Server Services" and restart SQL Server instance. Now you can connect via localhost, at least I could.
Note that this error can of course occur when connecting from other applications as well. Example for a normal C# web application Web.config
connection string:
<connectionStrings>
<add name="DefaultConnection" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
Use the below code. I am using same code for my spring integration test where I am using log back for logging. Use method assertJobIsScheduled to assert the text printed in the log.
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
private Logger rootLogger;
final Appender mockAppender = mock(Appender.class);
@Before
public void setUp() throws Exception {
initMocks(this);
when(mockAppender.getName()).thenReturn("MOCK");
rootLogger = (Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.addAppender(mockAppender);
}
private void assertJobIsScheduled(final String matcherText) {
verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
@Override
public boolean matches(final Object argument) {
return ((LoggingEvent)argument).getFormattedMessage().contains(matcherText);
}
}));
}
Using display:inline-block
#element1 {display:inline-block;margin-right:10px;}
#element2 {display:inline-block;}
Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
return list;
}
The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
return list;
}
In my case i had no problem at all, just forgot to start the mysql service...
sudo service mysqld start
Add this in your css file:
.custom_class
{
background-image: url(../img/beach.jpg);
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
and then, in your .html (or .php) file call this class like that:
<div class="custom_class">
...
</div>
If you are using jQuery, use css to add CSS
$("#voltaic_holder").css({'position': 'absolute',
'top': '-75px'});
To remove CSS attributes
$("#voltaic_holder").css({'position': '',
'top': ''});
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)
<?php
function qry($q){
global $qry;
try {
$host = "?";
$dbname = "?";
$username = "?";
$password = "?";
$dbcon = new PDO("mysql:host=$host;
dbname=$dbname","$username","$password");
}
catch (Exception $e) {
echo "ERROR ".$e->getMEssage();
}
$qry = $dbcon->query($q);
$qry->setFetchMode(PDO:: FETCH_OBJ);
return $qry;
}
echo "<table>";
/*Get Colums Names in table row */
$columns = array();
$qry1= qry("SHOW COLUMNS FROM Your_table_name");
while (@$column = $qry1->fetch()->Field) {
echo "<td>".$column."</td>";
$columns[] = $column;
}
echo "<tr>";
/* Fetch all data into a html table * /
$qry2 = qry("SELECT * FROM Your_table_name");
while ( $details = $qry2->fetch()) {
echo "<tr>";
foreach ($columns as $c_name) {
echo "<td>".$details->$c_name."</td>";
}
}
echo "</table>";
?>
I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.
To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.
public MainWindow()
{
try
{
InitializeComponent();
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.
Added the reference and problem solved.
This is very good: http://simononsoftware.com/virtualenv-tutorial-part-2/
And this is a slightly more practical one: https://web.archive.org/web/20160404222648/https://iamzed.com/2009/05/07/a-primer-on-virtualenv/
Checkout BigDecimal
and BigInteger
.
Use dataType casting. For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;
Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
Another workaround is to get a free domain from no-ip.org and point it to your local ip address.
Then, instead of using http://localhost/yourwebservice
you can try http://yourdomain.no-ip.org/yourwebservice
I had a problem where IntelliJ was unable to compile classes, claiming that dependencies between projects were missing. Reimporting the project as suggested in the answers of this question didn't solve the problem. The solution for me, was:
WARNING: on some projects, you might have to increment max memory for maven import (maven settings on maven tab / Importing / VM options for importer).
Depending on your usage context, you may use C# 7's pattern-matching feature:
int? v1 = 100;
if (v1 is int v2)
{
Console.WriteLine($"I'm not nullable anymore: {v2}");
}
Since some people are downvoting without leaving an explanation, I'd like to add some details to explain the rationale for including this as a viable solution.
C# 7's pattern matching now allows us check the type of a value and cast it implicitly. In the above snippet, the if-condition will only pass when the value stored in v1
is type-compatible to the type for v2
, which in this case is int
. It follows that when the value for v1
is null
, the if-condition will fail since null cannot be assigned to an int
. More properly, null
is not an int
.
I'd like to highlight that the that this solution may not always be the optimal choice. As I suggest, I believe this will depend on the developer's exact usage context. If you already have an int?
and want to conditionally operate on its value if-and-only-if the assigned value is not null (this is the only time it is safe to convert a nullable int to a regular int without losing information), then pattern matching is perhaps one of the most concise ways to do this.
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
Using CSS2.1 only, Work with all browsers (IE8+), without specifying any height or width.
That means that if your header suddenly grows longer, or your left navigation needs to enlarge, you don't have to fix anything in your CSS.
Totally responsive, simple & clear and very easy to manage.
<div class="Container">
<div class="Header">
</div>
<div class="HeightTaker">
<div class="Wrapper">
<div class="LeftNavigation">
</div>
<div class="Content">
</div>
</div>
</div>
</div>
Explanation:
The container div
takes 100% height of the body, and he's divided into 2 sections.
The header section will span to its needed height, and the HeightTaker
will take the rest.
How is it achieved? by floating an empty element along side the container with 100% height (using :before
), and giving the HeightTaker
an empty element at the end with the clear rule (using :after
). that element cant be in the same line with the floated element, so he's pushed till the end. which is exactly the 100% of the document.
With that we make the HeightTaker
span the rest of the container height, without stating any specific height/ margin.
inside that HeightTaker
we build a normal floated layout (to achieve the column like display) with a minor change.. we have a Wrapper
element, that is needed for the 100%
height to work.
Here's the Demo with Bootstrap classes. (I just added one div to your layout)
Bash program to wait for sftp to ask for a password then send it along:
#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "
You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.
The following is OK in HTML4, but not in XHTML. Check your editor.
<input type=button value="Submit" />
An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new
), whereas a class variable is a member of the class itself.
Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.
What’s the difference between a class variable and an instance variable?
This test class illustrates the difference:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}
Check out my answer in this similar question:
python: urllib2 how to send cookie with urlopen request
import urllib2
import urllib
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()
EDIT:
I see I've gotten a few downvotes for my answer, but no explaining comments. I'm guessing it's because I'm referring to the urllib
libraries instead of requests
. I do that because the OP asks for help with requests
or for someone to suggest another approach.
hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}
it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX
<?php
error_reporting(0);
# Coded by L0c4lh34rtz - IndoXploit
# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #
$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")
if(isset($argv[1])) {
foreach($list as $wordlist) {
print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
}
} else {
print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>
I have also come across this need for my database project. I decided to share my findings here.
1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)
2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)
3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (https://www.w3schools.com/sql/sql_default.asp)
4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:
GO
PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';
GO
ALTER TABLE [dbo].[PROD_WHSE_ACTUAL]
ADD [DATE] DATE DEFAULT getdate() NOT NULL;
-
Here are the steps I took to update my database using Visual Studio for development.
1) Add default value (Visual Studio SSDT: DB Project: table designer)
2) Use the Schema Comparison tool to generate the change script.
code already provided above
I was having issues building frameworks from the command line. My framework depends on other frameworks that were missing support for ARM-based simulators. I ended up excluding support for ARM-based simulators until I upgrade my dependencies.
I needed the EXCLUDED_ARCHS=arm64
flag when building the framework for simulators from CLI.
xcodebuild archive -project [project] -scheme [scheme] -destination "generic/platform=iOS Simulator" -archivePath "archives/[scheme]-iOS-Simulator" SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES EXCLUDED_ARCHS=arm64
Here is a full example of an axios.post request with custom headers
var postData = {_x000D_
email: "[email protected]",_x000D_
password: "password"_x000D_
};_x000D_
_x000D_
let axiosConfig = {_x000D_
headers: {_x000D_
'Content-Type': 'application/json;charset=UTF-8',_x000D_
"Access-Control-Allow-Origin": "*",_x000D_
}_x000D_
};_x000D_
_x000D_
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)_x000D_
.then((res) => {_x000D_
console.log("RESPONSE RECEIVED: ", res);_x000D_
})_x000D_
.catch((err) => {_x000D_
console.log("AXIOS ERROR: ", err);_x000D_
})
_x000D_
There are three unique situations:
Margin="a,b,c,d"
.Margin="a,b"
.Margin="a"
.If there are 4 numbers, then its left
, top
, right
, bottom
(a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":
<object Margin="left,top,right,bottom"/>
Example: if we use Margin="10,20,30,40"
it generates:
If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":
<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".
Example: if we use Margin="10,30"
, the left & right margin are both 10, and the top & bottom are both 30.
If there is 1 number, then the number is repeated (its essentially a border thickness).
<object Margin="a"/> // Equivalent to Margin="a,a,a,a".
Example: if we use Margin="20"
it generates:
Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.
The rule:
All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).
For Windows users : psql -U postgres
You should see then the command-line interface to PostgreSQL: postgres=#
Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:
/**
* <PRE>
* insert code as you would anywhere else
* </PRE>
*/
is the simplest way to do this.
An Example from a javadoc I got from a java.awt.Event method:
/**
* <PRE>
* int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
* int offmask = CTRL_DOWN_MASK;
* if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
* ...
* }
* </PRE>
*/
This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.
I can't answer all questions, but I will do my best.
As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.
Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.
WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).
In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.
Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.
About the protocol, as Wikipedia shows, it looks like this:
Client sends:
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
Server replies:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.
As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support
Upgrade: websocket
Connection: Upgrade
will reply with an error or with a page content.
Two options - the first, as you said in your own answer, is setting the environment variable ANSIBLE_HOST_KEY_CHECKING
to False.
The second way to set it is to put it in an ansible.cfg file, and that's a really useful option because you can either set that globally (at system or user level, in /etc/ansible/ansible.cfg
or ~/.ansible.cfg
), or in an config file in the same directory as the playbook you are running.
To do that, make an ansible.cfg
file in one of those locations, and include this:
[defaults]
host_key_checking = False
You can also set a lot of other handy defaults there, like whether or not to gather facts at the start of a play, whether to merge hashes declared in multiple places or replace one with another, and so on. There's a whole big list of options here in the Ansible docs.
Edit: a note on security.
SSH host key validation is a meaningful security layer for persistent hosts - if you are connecting to the same machine many times, it's valuable to accept the host key locally.
For longer-lived EC2 instances, it would make sense to accept the host key with a task run only once on initial creation of the instance:
- name: Write the new ec2 instance host key to known hosts
connection: local
shell: "ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts"
There's no security value for checking host keys on instances that you stand up dynamically and remove right after playbook execution, but there is security value in checking host keys for persistent machines. So you should manage host key checking differently per logical environment.
~/.ansible.cfg
)./ansible.cfg
alongside the playbook for unit tests against vagrant VMs, automation for short-lived ec2 instances)You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
Try below code. Worked in my case. Hope this helps!
select id,total_Hour,
(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)) as weekday_Listing_Hrs,
(coalesce(weekend_1,0)+coalesce(weekend_2,0)+coalesce(weekend_3,0)) as weekend_Listing_Hrs
from
select *,
listing_duration_Hour-(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)+coalesce(weekend_1,0)+coalesce(weekend_2,0)) as weekend_3
from
(
select * ,
case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (0,1,2,3,4)
then timestampdiff(hour,Start_Date,End_Date)
when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (0,1,2,3,4)
then 24-timestampdiff(hour,date(Start_Date),Start_Date)
end as weekday_1,
case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (0,1,2,3,4)
then timestampdiff(hour,date(End_Date),End_Date)
end as weekday_2,
case when date(Start_Date) != date(End_Date) then
(5*(DATEDIFF(date(End_Date),adddate(date(Start_Date),+1)) DIV 7) +
MID('0123455501234445012333450122234501101234000123450',7 * WEEKDAY(adddate(date(Start_Date),+1))
+ WEEKDAY(date(End_Date)) + 1, 1))* 24 end as weekday_3,
case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (5,6)
then timestampdiff(hour,Start_Date,End_Date)
when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (5,6)
then 24-timestampdiff(hour,date(Start_Date),Start_Date)
end as weekend_1,
case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (5,6)
then timestampdiff(hour,date(End_Date),End_Date)
end as weekend_2
from
TABLE_1
)
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
System.IO.Path.GetTempPath()
is just a wrapper for a native call to GetTempPath(..)
in Kernel32.
Have a look at http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx
Copied from that page:
The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:
- The path specified by the TMP environment variable.
- The path specified by the TEMP environment variable.
- The path specified by the USERPROFILE environment variable.
- The Windows directory.
It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows.
So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.
You may need to do a combination of the above to resolve this problem. I normally get this error when I do
mvn clean install
and see a compile error preventing the my tests from fully compiling.
Assuming the issues resolved by the above have been dealt with, try clicking Project, Clean, and clean the project which contains the test you want to run. Also make sure Build Automatically is checked.
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
I am using python3 and found out that you need to encode your string before you can pass it into stdin:
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
Not currently. It will be available in CSS 3, but it will take some time until it's implemented in most browsers.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gifImageView = (GifImageView) findViewById(R.id.GifImageView);
gifImageView.setGifImageResource(R.drawable.success1);
new Thread(new Runnable() {
@Override
public void run() {
try {
//dummy delay for 2 second
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
gifImageView.setGifImageResource(R.drawable.success);
}
});
}
}).start();
}
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ','
|| r.serial# || ''' immediate';
END LOOP;
END;
This should work - I just changed your script to add the immediate
keyword. As the previous answers pointed out, the kill session
only marks the sessions for killing; it does not do so immediately but later when convenient.
From your question, it seemed you are expecting to see the result immediately. So immediate
keyword is used to force this.
Setting
onPressed: null // disables click
and
onPressed: () => yourFunction() // enables click
This question may help: How to pass variable by reference in javascript? Read data from ActiveX function which returns more than one value
To summarise, Javascript primitive types are always passed by value, whereas the values inside objects are passed by reference (thanks to commenters for pointing out my oversight). So to get round this, you have to put your integer inside an object:
var myobj = {x:0};_x000D_
_x000D_
function a(obj)_x000D_
{_x000D_
obj.x++;_x000D_
}_x000D_
_x000D_
a(myobj);_x000D_
alert(myobj.x); // returns 1_x000D_
_x000D_
_x000D_
$("#your-table-id").empty();
That's as fast as you get.
[]
is to select columns.When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.
So, in the question above: df[2]
searches for a column name matching the integer value 2
. This column does not exist and a KeyError
is raised.
Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.
df[2:3]
This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.
df[6:20:3]
You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.
I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc
.
You please change the port 80 to port 7080 or something difference. Dont use 8080. It might be busy in most case.
Updated Listen 80 to Listen:7080 and ServerName localhost to ServerName localhost:7080.
It will work fine.
If you open your second link in a browser you'll see the source code:
#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov
[...]
# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4
for year in {2002..2003}
do
for tile in {1159..1160}
do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
# An example using curl instead of wget
#do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
done
done
So it's a bash script. Got Linux?
In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.
var builder = new ConfigurationBuilder()
.AddJsonFile("appSettings.json")
.AddEnvironmentVariables(prefix: "ABC_")
var config = builder.Build();
According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_")
line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.
After losing hours trying to find my error, the problem is your formula:
sigma = sum(y*(x-mean)**2)/n
This previous formula is wrong, the correct formula is the square root of this!;
sqrt(sum(y*(x-mean)**2)/n)
Hope this helps
I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.
## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011
# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipelineByPropertyName = $true)]
[Alias('From')] # This is the name of the parameter e.g. -From [email protected]
[String]$EmailFrom, # This is the value [Don't forget the comma at the end!]
[Parameter(Mandatory = $true,
Position = 1,
ValueFromPipelineByPropertyName = $true)]
[Alias('To')]
[String[]]$Arry_EmailTo,
[Parameter(Mandatory = $true,
Position = 2,
ValueFromPipelineByPropertyName = $true)]
[Alias('Subj')]
[String]$EmailSubj,
[Parameter(Mandatory = $true,
Position = 3,
ValueFromPipelineByPropertyName = $true)]
[Alias('Body')]
[String]$EmailBody,
[Parameter(Mandatory = $false,
Position = 4,
ValueFromPipelineByPropertyName = $true)]
[Alias('Attachment')]
[String[]]$Arry_EmailAttachments
)
# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");
# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
$emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
$emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)
Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.
I'm using
$("input:radio[name='html_radio']").is(":checked")
And will return FALSE if all the items in the radiogroup are unchecked and TRUE if an item is checked.
save()
can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO
:
buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
A function to truncate an arbitrary number of decimals:
public decimal Truncate(decimal number, int digits)
{
decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
int temp = (int)(stepper * number);
return (decimal)temp / stepper;
}
Guess @user3010492 tested it but I used this with fixed cell A5 --> $A$5 and fixed element of G7 --> $G7
=INDIRECT("'"&$A$5&"'!$G7")
Also works nested nicely in other formula if you enclose it in brackets.
You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.
If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the
System.DirectoryServices.AccountManagement namespace.
It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.
Brent
According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : http://www.oracle.com/technetwork/java/javafx/overview/roadmap-1446331.html ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait
You can use gettimeofday()
together with the timedifference_msec()
function below to calculate the number of milliseconds elapsed between two samples:
#include <sys/time.h>
#include <stdio.h>
float timedifference_msec(struct timeval t0, struct timeval t1)
{
return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}
int main(void)
{
struct timeval t0;
struct timeval t1;
float elapsed;
gettimeofday(&t0, 0);
/* ... YOUR CODE HERE ... */
gettimeofday(&t1, 0);
elapsed = timedifference_msec(t0, t1);
printf("Code executed in %f milliseconds.\n", elapsed);
return 0;
}
Note that, when using gettimeofday()
, you need to take seconds into account even if you only care about microsecond differences because tv_usec
will wrap back to zero every second and you have no way of knowing beforehand at which point within a second each sample is obtained.
For anyone reading the example in "A Swift Tour" chapter of "The Swift Programming Language" and looking for a way to simplify the simpleDescription() method, converting the enum itself to String by doing String(self)
will do it:
enum Rank: Int
{
case Ace = 1 //required otherwise Ace will be 0
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace, .Jack, .Queen, .King:
return String(self).lowercaseString
default:
return String(self.rawValue)
}
}
}
you can use this too
.parent:hover * {
/* ... */
}
_x000D_
I got the same issue when I ran mongod command after installing it on Windows10. I stopped the mongodb service and started it again. Working like a charm
Command to stop mongodb service (in windows): net stop mongodb
Command to start mongodb server: mongod --dbpath PATH_TO_DATA_FOLDER
http://www.mathworks.com/help/techdoc/ref/rand.html
n = 13 + (rand(1) * 7);
I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
This is another valid way to make a copy of a vector, just use its constructor:
std::vector<int> newvector(oldvector);
This is even simpler than using std::copy
to walk the entire vector from start to finish to std::back_insert
them into the new vector.
That being said, your .swap()
one is not a copy, instead it swaps the two vectors. You would modify the original to not contain anything anymore! Which is not a copy.
Based on watching the Maven console in Eclipse (Kepler), sources will be automatically downloaded for a Maven dependency if you attempt to open a class from said Maven dependency in the editor for which you do not have the sources downloaded already. This is handy when you don't want to grab source for all of your dependencies, but you don't know which ones you want ahead of time (and you're using Eclipse).
I ended up using @GabrielRamierez's approach, but will employ @PascalThivent's approach going forward.
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
Given annotation worked for me. Can have a try
For Example :-
public class Parent{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cct_id")
private Integer cct_id;
@OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<Child> childs;
}
public class Child{
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="cct_id")
private Parent parent;
}
I wrote a quick and easy python script to include in my bash script.
For example, your ini file is called food.ini
and in the file you can have some sections and some lines:
[FRUIT]
Oranges = 14
Apples = 6
Copy this small 6 line Python script and save it as configparser.py
#!/usr/bin/python
import configparser
import sys
config = configparser.ConfigParser()
config.read(sys.argv[1])
print config.get(sys.argv[2],sys.argv[3])
Now, in your bash script you could do this for example.
OrangeQty=$(python configparser.py food.ini FRUIT Oranges)
or
ApplesQty=$(python configparser.py food.ini FRUIT Apples)
echo $ApplesQty
This presupposes:
Hope it helps :¬)
Reset all selection fields to the default option, where the attribute selected is defined.
$("#reset").on("click", function () {
// Reset all selections fields to default option.
$('select').each( function() {
$(this).val( $(this).find("option[selected]").val() );
});
});
They work at different levels.
The simplest way to view the difference, from a beginner perspective is that jQuery is essentially an abstract of JavaScript, so the way we design a page for JavaScript is pretty much how we will do it for jQuery. Start with the DOM then build a behavior layer on top of that. Not so with Angular.Js. The process really begins from the ground up, so the end result is the desired view.
With jQuery you do dom-manipulations, with Angular.Js you create whole web-applications.
jQuery was built to abstract away the various browser idiosyncracies, and work with the DOM without having to add IE6 checks and so on. Over time, it developed a nice, robust API which allowed us to do a lot of things, but at its core, it is meant for dealing with the DOM, finding elements, changing UI, and so on. Think of it as working directly with nuts and bolts.
Angular.Js was built as a layer on top of jQuery, to add MVC concepts to front end engineering. Instead of giving you APIs to work with DOM, Angular.Js gives you data-binding, templating, custom components (similar to jQuery UI, but declarative instead of triggering through JS) and a whole lot more. Think of it as working at a higher level, with components that you can hook together, instead of directly at the nuts and bolts level.
Additionally, Angular.Js gives you structures and concepts that apply to various projects, like Controllers, Services, and Directives. jQuery itself can be used in multiple (gazillion) ways to do the same thing. Thankfully, that is way less with Angular.Js, which makes it easier to get into and out of projects. It offers a sane way for multiple people to contribute to the same project, without having to relearn a system from scratch.
A short comparison can be this-
And much more
Think this helps.
More can be found-
Database Clustering is actually a mode of synchronous replication between two or possibly more nodes with an added functionality of fault tolerance added to your system, and that too in a shared nothing architecture. By shared nothing it means that the individual nodes actually don't share any physical resources like disk or memory.
As far as keeping the data synchronized is concerned, there is a management server to which all the data nodes are connected along with the SQL node to achieve this(talking specifically about MySQL).
Now about the differences: load balancing is just one result that could be achieved through clustering, the others include high availability, scalability and fault tolerance.
public static void main(String s[])
{
int firstArray[] = {2, 14, 6, 82, 22};
int secondArray[] = {3, 16, 12, 14, 48, 96};
int number = getCommonMinimumNumber(firstArray, secondArray);
System.out.println("The number is " + number);
}
public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
{
Integer result =0;
if ( firstSeries.length !=0 && secondSeries.length !=0 )
{
series(firstSeries);
series(secondSeries);
one : for (int i = 0 ; i < firstSeries.length; i++)
{
for (int j = 0; j < secondSeries.length; j++)
if ( firstSeries[i] ==secondSeries[j])
{
result =firstSeries[i];
break one;
}
else
result = -999;
}
}
else if ( firstSeries == Null || secondSeries == null)
result =-999;
else
result = -999;
return result;
}
public static int[] series(int number[])
{
int temp;
boolean fixed = false;
while(fixed == false)
{
fixed = true;
for ( int i =0 ; i < number.length-1; i++)
{
if ( number[i] > number[i+1])
{
temp = number[i+1];
number[i+1] = number[i];
number[i] = temp;
fixed = false;
}
}
}
/*for ( int i =0 ;i< number.length;i++)
System.out.print(number[i]+",");*/
return number;
}
Each deployed webapp has a context.xml
file that lives in
$CATALINA_BASE/conf/[enginename]/[hostname]
(conf/Catalina/localhost by default)
and has the same name as the webapp (manager.xml
in this case). If no file is present, default values are used.
So, you need to create a file conf/Catalina/localhost/manager.xml
and specify the rule you want to allow remote access. For example, the following content of manager.xml
will allow access from all machines:
<Context privileged="true" antiResourceLocking="false"
docBase="${catalina.home}/webapps/manager">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>
Note that the allow attribute of the Valve
element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).
Other Valve
classes cater for other rules (e.g. RemoteHostValve
for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.
Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml
you should have access to the Manager.
I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this
needing to be enclosed as $(this)
I wanted a more enhanced version so I ended up with a module which allows: UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately. Supports pyinstaller.
prototype:
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
winadmin.py
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7
import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3
# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"
wrconn = None
#fake logger for message sending
class fakelogger:
def __init__(self, xlogger=None):
self.lg = xlogger
def write(self, a):
global wrconn
if wrconn is not None:
wrconn.send(LOGTAG+a)
elif self.lg is not None:
self.lg.write(a)
else:
print(LOGTAG+a)
class Writer():
wzconn=None
counter = 0
def __init__(self, tport=6000,authkey=b'secret password'):
global wrconn
if wrconn is None:
address = ('localhost', tport)
try:
wrconn = Client(address, authkey=authkey)
except:
wrconn = None
wzconn = wrconn
self.wrconn = wrconn
self.__class__.counter+=1
def __del__(self):
self.__class__.counter-=1
if self.__class__.counter == 0 and wrconn is not None:
import time
time.sleep(0.1) # slows deletion but is enough to print stderr
wrconn.send('close')
wrconn.close()
def sendx(cls, mesg):
cls.wzconn.send(msg)
def sendw(self, mesg):
self.wrconn.send(msg)
#fake file to be passed as stdout and stderr
class connFile():
def __init__(self, thekind="out", tport=6000):
self.cnt = 0
self.old=""
self.vg=Writer(tport)
if thekind == "out":
self.kind=sys.__stdout__
else:
self.kind=sys.__stderr__
def write(self, *args, **kwargs):
global wrconn
global dbz
from io import StringIO # # Python2 use: from cStringIO import StringIO
mystdout = StringIO()
self.cnt+=1
__builtin__.print(*args, **kwargs, file=mystdout, end = '')
#handles "\n" wherever it is, however usually is or string or \n
if "\n" not in mystdout.getvalue():
if mystdout.getvalue() != "\n":
#__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
self.old += mystdout.getvalue()
else:
#__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
if wrconn is not None:
wrconn.send(dbz[1]+self.old)
else:
__builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
self.kind.flush()
self.old=""
else:
vv = mystdout.getvalue().split("\n")
#__builtin__.print("V:",vv, file=self.kind, end='')
for el in vv[:-1]:
if wrconn is not None:
wrconn.send(dbz[0]+self.old+el)
self.old = ""
else:
__builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
self.kind.flush()
self.old=""
self.old=vv[-1]
def open(self):
pass
def close(self):
pass
def flush(self):
pass
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print ("Admin check failed, assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
print("Unsupported operating system for this module: %s" % (os.name,))
exit()
#raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
def runAsAdmin(cmdLine=None, wait=True, hidden=False):
if os.name != 'nt':
raise (RuntimeError, "This function is only implemented on Windows.")
import win32api, win32con, win32process
from win32com.shell.shell import ShellExecuteEx
python_exe = sys.executable
arb=""
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif not isinstance(cmdLine, (tuple, list)):
if isinstance(cmdLine, (str)):
arb=cmdLine
cmdLine = [python_exe] + sys.argv
print("original user", arb)
else:
raise( ValueError, "cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
if len(arb) > 0:
params += " "+arb
cmdDir = ''
if hidden:
showCmd = win32con.SW_HIDE
else:
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=64,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = procInfo['hProcess']
return rc
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
global dbz
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
import getpass
uname = getpass.getuser()
if (tport> 0):
address = ('localhost', tport) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
rc = runAsAdmin(uname, wait=False, hidden=True)
if (tport> 0):
hr = win32event.WaitForSingleObject(rc, 40)
conn = listener.accept()
print ('connection accepted from', listener.last_accepted)
sys.stdout.flush()
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
else:
if msg.startswith(dbz[0]+LOGTAG):
if xlogger != None:
xlogger.write(msg[len(LOGTAG):])
else:
print("Missing a logger")
else:
print(msg)
sys.stdout.flush()
listener.close()
else: #no port connection, its silent
WaitForSingleObject(rc, INFINITE);
return False
else:
#redirect prints stdout on master, errors in error.txt
print("HIADM")
sys.stdout.flush()
if (tport > 0) and (redir):
vox= connFile(tport=tport)
sys.stdout=vox
if not errFile:
sys.stderr=vox
else:
vfrs=open("errFile.txt","w")
sys.stderr=vfrs
#print("HI ADMIN")
return True
def test():
rc = 0
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
sys.stdout.flush()
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print ("You are an admin!", os.getpid(), "params: ", sys.argv)
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.
If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.
A simple example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());
Quote:
These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.
This would actually work as following:
.element {
font-min-size: 10px;
font-max-size: 18px;
font-size: 5vw; // viewport-relative units are responsive.
}
This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.
Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).
It turns out that, yes, the problem is not simple, but the solution is.
First I had to create a shell script to wrap the "source" command. That said I used the "." instead, because I've read that it's better to use it than source for Bash scripts.
#!/bin/bash
. /path/to/env/bin/activate
Then from my Python script I can simply do this:
import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')
The whole trick lies within the --rcfile
argument.
When the Python interpreter exits it leaves the current shell in the activated environment.
Win!
BehaviourSubject will return the initial value or the current value on Subscription
var bSubject= new Rx.BehaviorSubject(0); // 0 is the initial value
bSubject.subscribe({
next: (v) => console.log('observerA: ' + v) // output initial value, then new values on `next` triggers
});
bSubject.next(1); // output new value 1 for 'observer A'
bSubject.next(2); // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription
bSubject.subscribe({
next: (v) => console.log('observerB: ' + v) // output current value 2, then new values on `next` triggers
});
bSubject.next(3);
With output:
observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3
Subject does not return the current value on Subscription. It triggers only on .next(value)
call and return/output the value
var subject = new Rx.Subject();
subject.next(1); //Subjects will not output this value
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
subject.next(2);
subject.next(3);
With the following output on the console:
observerA: 2
observerB: 2
observerA: 3
observerB: 3
There are 2 views of annotations
user view, most of the time, annotations work like a shortcut, save you some key strokes, or make your program more readable
vendor view, the processor's view of annotation is more of light weighted 'interface', your program DOES confront to SOMETHING but without explicitly "implements" the particular interface(here aka the annotation)
e.g. in jpa you define something like
@Entity class Foo {...}
instead of
class Foo implements Entity {...}
both speak the same thing "Foo is an Entity class"
Below Steps worked for me:
1). right click on source task.
2). click on "Show Advanced editor". advanced edit option for source task in ssis
3). Go to "Input and Output Properties" tab.
4). select the output column for which you are getting the error.
5). Its data type will be "String[DT_STR]".
6). Change that data type to "Unicode String[DT_WSTR]". Changing the data type to unicode string
7). save and close. Hope this helps!
From the sed
man page:
Normally, sed cyclically copies a line of input, not including its terminating newline character, into a pattern space, (unless there is something left after a "D" function), applies all of the commands with addresses that select that pattern space, copies the pattern space to the standard output, appending a newline, and deletes the pattern space.
It's operating on the line without the newline present, so the pattern you have there can't ever match. You need to do something else - like match against $
(end-of-line) or ^
(start-of-line).
Here's an example of something that worked for me:
$ cat > states
California
Massachusetts
Arizona
$ sed -e 's/$/\
> /' states
California
Massachusetts
Arizona
I typed a literal newline character after the \
in the sed
line.
You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.
public interface MyInterface {
public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}
I'll add a bit to this old thread.
Usually you would use
$ echo "$FOO"
However, I've had problems even with this syntax. Consider the following script.
#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"
The *
needs to be passed verbatim to curl
, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*
. You also can't quote $curl_opts
because it will be recognized as a single (invalid) option to curl
.
curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
Therefore I would recommend the use of the bash
variable $GLOBIGNORE
to prevent filename expansion altogether if applied to the global pattern, or use the set -f
built-in flag.
#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1" ## no filename expansion
Applying to your original example:
me$ FOO="BAR * BAR"
me$ echo $FOO
BAR file1 file2 file3 file4 BAR
me$ set -f
me$ echo $FOO
BAR * BAR
me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
Running the below command solved the problem for me.
git config --global credential.helper wincred
Please refer the below github documentation:
https://help.github.com/articles/caching-your-github-password-in-git/
Use this:
String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12
hope help you.
The code marked @Before
is executed before each test, while @BeforeClass
runs once before the entire test fixture. If your test class has ten tests, @Before
code will be executed ten times, but @BeforeClass
will be executed only once.
In general, you use @BeforeClass
when multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClass
into @Before
, but your test run may take longer. Note that the code marked @BeforeClass
is run as static initializer, therefore it will run before the class instance of your test fixture is created.
In JUnit 5, the tags @BeforeEach
and @BeforeAll
are the equivalents of @Before
and @BeforeClass
in JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.
>>> mask = df['ids'].str.contains('ball')
>>> mask
0 True
1 True
2 False
3 True
Name: ids, dtype: bool
>>> df[mask]
ids vals
0 aball 1
1 bball 2
3 fball 4
I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.
There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.
The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.
body {
position:absolute;
width:1000px;
left: 50%;
margin-left:-500px;
}
Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.
Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.
But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.
The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:
// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;
jQuery(document).ready(function () {
$(document).mousemove(function (e) {
var bodyOffsets = document.body.getBoundingClientRect();
tempX = e.pageX - bodyOffsets.left;
tempY = e.pageY;
});
})
Phew. That took me a while to fix ! I hope this is useful to other developers !
The following technique worked for me:
1) Right click on the project Solution -> Click on Clean solution
2) Right click on the project Solution -> Click on Rebuild solution
Be aware of the use of backquotes too. I had in a script the following statement
ALTER TABLE service ADD FOREIGN KEY (create_by) REFERENCES `system_user(id)`;
but the backquotes at the end were false. It should have been:
ALTER TABLE service ADD FOREIGN KEY (create_by) REFERENCES `system_user`(`id`);
MySQL give unfortunalty no details on this error...
To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):
Parser.new.methods - Object.new.methods
There's actually seven variants of this:
char description unicode html html entity utf-8 · Middle Dot U+00B7 · · C2 B7 · Greek Ano Teleia U+0387 · CE 87 • Bullet U+2022 • • E2 80 A2 ‧ Hyphenation Point U+2027 ₁ E2 80 A7 ∙ Bullet Operator U+2219 ∙ E2 88 99 ● Black Circle U+25CF ● E2 97 8F ⬤ Black Large Circle U+2B24 ⬤ E2 AC A4
Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.
Here's an alternative answer in case the ones listed above don't work for you. You can use the following solution(s) as well, which was found here:
ip addr
OR
ip addr show
OR
ip link
All three of these will show your MAC address(es) next to link/ether
. I stumbled on this because I had just done a fresh install of Debian 9.5 from a USB stick without internet access, so I could only do a very minimal install, and received
-bash: ifconfig: command not found
when I tried some of the above solutions. I figured somebody else may come across this problem as well. Hope it helps.
URLs should be case insensitive unless there is a good reason why they are should not be.
This is not mandatory (it is not any part of an RFC) but it makes the communication and storage of URLs far more reliable.
If I have two pages on a website:
http://stackoverflow.com/ABOUT.html
and
http://stackoverflow.com/about.html
How should they differ? Maybe one is written 'shouting style' (caps) - but from an IA point of view, the distinction should never be made by a change in the case of the URL.
Moreover, it is easy to implement this in Apache - just use CheckSpelling On
from mod_Speling.
Here's yet another example:
VARTEST="value of VARTEST"
#export VARTEST="value of VARTEST"
sudo env | grep -i vartest
sudo echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}"
sudo bash -c 'echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}"'
Only by using export VARTEST the value of VARTEST is available in sudo bash -c '...'!
For further examples see:
bash-hackers.org/wiki/doku.php/scripting/processtree