Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
This is how I did it and it works:
dictlist = [dict() for x in range(n)]
It gives you a list of n empty dictionaries.
let size = text.size(withAttributes:[.font: UIFont.systemFont(ofSize:18.0)])
To bootstrap 3.0.0:
.popover{ right:0!important; }
And modify too
.popover { max-width:WWWpx!important; }
where WWW is your correct max-width to show your popover content.
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
#include <iterator>
#include <numeric>
using namespace std;
typedef long double ld;
typedef unsigned int uint;
typedef std::vector<ld>::iterator vec_iter_ld;
/**
* Overriding the ostream operator for pretty printing vectors.
*/
template<typename T>
std::ostream &operator<<(std::ostream &os, std::vector<T> vec) {
os << "[";
if (vec.size() != 0) {
std::copy(vec.begin(), vec.end() - 1, std::ostream_iterator<T>(os, " "));
os << vec.back();
}
os << "]";
return os;
}
/**
* This class calculates mean and standard deviation of a subvector.
* This is basically stats computation of a subvector of a window size qual to "lag".
*/
class VectorStats {
public:
/**
* Constructor for VectorStats class.
*
* @param start - This is the iterator position of the start of the window,
* @param end - This is the iterator position of the end of the window,
*/
VectorStats(vec_iter_ld start, vec_iter_ld end) {
this->start = start;
this->end = end;
this->compute();
}
/**
* This method calculates the mean and standard deviation using STL function.
* This is the Two-Pass implementation of the Mean & Variance calculation.
*/
void compute() {
ld sum = std::accumulate(start, end, 0.0);
uint slice_size = std::distance(start, end);
ld mean = sum / slice_size;
std::vector<ld> diff(slice_size);
std::transform(start, end, diff.begin(), [mean](ld x) { return x - mean; });
ld sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
ld std_dev = std::sqrt(sq_sum / slice_size);
this->m1 = mean;
this->m2 = std_dev;
}
ld mean() {
return m1;
}
ld standard_deviation() {
return m2;
}
private:
vec_iter_ld start;
vec_iter_ld end;
ld m1;
ld m2;
};
/**
* This is the implementation of the Smoothed Z-Score Algorithm.
* This is direction translation of https://stackoverflow.com/a/22640362/1461896.
*
* @param input - input signal
* @param lag - the lag of the moving window
* @param threshold - the z-score at which the algorithm signals
* @param influence - the influence (between 0 and 1) of new signals on the mean and standard deviation
* @return a hashmap containing the filtered signal and corresponding mean and standard deviation.
*/
unordered_map<string, vector<ld>> z_score_thresholding(vector<ld> input, int lag, ld threshold, ld influence) {
unordered_map<string, vector<ld>> output;
uint n = (uint) input.size();
vector<ld> signals(input.size());
vector<ld> filtered_input(input.begin(), input.end());
vector<ld> filtered_mean(input.size());
vector<ld> filtered_stddev(input.size());
VectorStats lag_subvector_stats(input.begin(), input.begin() + lag);
filtered_mean[lag - 1] = lag_subvector_stats.mean();
filtered_stddev[lag - 1] = lag_subvector_stats.standard_deviation();
for (int i = lag; i < n; i++) {
if (abs(input[i] - filtered_mean[i - 1]) > threshold * filtered_stddev[i - 1]) {
signals[i] = (input[i] > filtered_mean[i - 1]) ? 1.0 : -1.0;
filtered_input[i] = influence * input[i] + (1 - influence) * filtered_input[i - 1];
} else {
signals[i] = 0.0;
filtered_input[i] = input[i];
}
VectorStats lag_subvector_stats(filtered_input.begin() + (i - lag), filtered_input.begin() + i);
filtered_mean[i] = lag_subvector_stats.mean();
filtered_stddev[i] = lag_subvector_stats.standard_deviation();
}
output["signals"] = signals;
output["filtered_mean"] = filtered_mean;
output["filtered_stddev"] = filtered_stddev;
return output;
};
int main() {
vector<ld> input = {1.0, 1.0, 1.1, 1.0, 0.9, 1.0, 1.0, 1.1, 1.0, 0.9, 1.0, 1.1, 1.0, 1.0, 0.9, 1.0, 1.0, 1.1, 1.0,
1.0, 1.0, 1.0, 1.1, 0.9, 1.0, 1.1, 1.0, 1.0, 0.9, 1.0, 1.1, 1.0, 1.0, 1.1, 1.0, 0.8, 0.9, 1.0,
1.2, 0.9, 1.0, 1.0, 1.1, 1.2, 1.0, 1.5, 1.0, 3.0, 2.0, 5.0, 3.0, 2.0, 1.0, 1.0, 1.0, 0.9, 1.0,
1.0, 3.0, 2.6, 4.0, 3.0, 3.2, 2.0, 1.0, 1.0, 0.8, 4.0, 4.0, 2.0, 2.5, 1.0, 1.0, 1.0};
int lag = 30;
ld threshold = 5.0;
ld influence = 0.0;
unordered_map<string, vector<ld>> output = z_score_thresholding(input, lag, threshold, influence);
cout << output["signals"] << endl;
}
I don't believe there's a convenient way to retrieve an arbitrary value from a generator. The generator will provide a next() method to traverse itself, but the full sequence is not produced immediately to save memory. That's the functional difference between a generator and a list.
select concat('''','abc','''')
This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.
To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.
NB git am
applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr
, as per this answer.
$('div[id ^= "player_"]');
This worked for me..select all Div starts with "players_" keyword and display it.
Interesting that these answers utilize printf
like it is a given.
printf
converts the integer to a Hexadecimal string value.
//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base = number base for conversion; decimal=10,hex=16
// char sign = signed or unsigned output
// char *outbuf = buffer to hold the output number
//*************************************************************
void prntnum(unsigned long n, int base, char sign, char *outbuf)
{
int i = 12;
int j = 0;
do{
outbuf[i] = "0123456789ABCDEF"[num % base];
i--;
n = num/base;
}while( num > 0);
if(sign != ' '){
outbuf[0] = sign;
++j;
}
while( ++i < 13){
outbuf[j++] = outbuf[i];
}
outbuf[j] = 0;
}
To extract Google Drive zip from a Google colab notebook for example:
import zipfile
from google.colab import drive
drive.mount('/content/drive/')
zip_ref = zipfile.ZipFile("/content/drive/My Drive/ML/DataSet.zip", 'r')
zip_ref.extractall("/tmp")
zip_ref.close()
This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
Here is a simple example of scrapy
with an AJAX request. Let see the site rubin-kazan.ru.
All messages are loaded with an AJAX request. My goal is to fetch these messages with all their attributes (author, date, ...):
When I analyze the source code of the page I can't see all these messages because the web page uses AJAX technology. But I can with Firebug from Mozilla Firefox (or an equivalent tool in other browsers) to analyze the HTTP request that generate the messages on the web page:
It doesn't reload the whole page but only the parts of the page that contain messages. For this purpose I click an arbitrary number of page on the bottom:
And I observe the HTTP request that is responsible for message body:
After finish, I analyze the headers of the request (I must quote that this URL I'll extract from source page from var section, see the code below):
And the form data content of the request (the HTTP method is "Post"):
And the content of response, which is a JSON file:
Which presents all the information I'm looking for.
From now, I must implement all this knowledge in scrapy. Let's define the spider for this purpose:
class spider(BaseSpider):
name = 'RubiGuesst'
start_urls = ['http://www.rubin-kazan.ru/guestbook.html']
def parse(self, response):
url_list_gb_messages = re.search(r'url_list_gb_messages="(.*)"', response.body).group(1)
yield FormRequest('http://www.rubin-kazan.ru' + url_list_gb_messages, callback=self.RubiGuessItem,
formdata={'page': str(page + 1), 'uid': ''})
def RubiGuessItem(self, response):
json_file = response.body
In parse
function I have the response for first request.
In RubiGuessItem
I have the JSON file with all information.
You can't.
In order to "use" the struct, i.e. to be able to declare objects of that type and to access its internals you need the full definition of the struct. So, it you want to do any of that (and you do, judging by your error messages), you have to place the full definition of the struct type into the header file.
Another clever way from that ancient thread:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
c=0
words = ['challa','reddy','challa']
for idx, word in enumerate(words):
if idx==0:
firstword=word
print(firstword)
elif idx == len(words)-1:
lastword=word
print(lastword)
if firstword==lastword:
c=c+1
print(c)
Here is my answer when you want to animate it and start fading it out after couple of seconds. I used opacity because first of all i didn't want to fade it out completely, second, it does not go back and force after many scrolls.
$(window).scroll(function () {
var elem = $('div');
setTimeout(function() {
elem.css({"opacity":"0.2","transition":"2s"});
},4000);
elem.css({"opacity":"1","transition":"1s"});
});
In Angular we can add an option as placeholder that can be hidden in option dropdown. We can even add a custom dropdown icon as background that replaces browser dropdown icon.
The trick is to enable placeholder css only when value is not selected
/**My Component Template*/
<div class="dropdown">
<select [ngClass]="{'placeholder': !myForm.value.myField}"
class="form-control" formControlName="myField">
<option value="" hidden >Select a Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
/**My Component.TS */
constructor(fb: FormBuilder) {
this.myForm = this.fb.build({
myField: ''
});
}
/**global.scss*/
.dropdown {
width: 100%;
height: 30px;
overflow: hidden;
background: no-repeat white;
background-image:url('angle-arrow-down.svg');
background-position: center right;
select {
background: transparent;
padding: 3px;
font-size: 1.2em;
height: 30px;
width: 100%;
overflow: hidden;
/*For moz*/
-moz-appearance: none;
/* IE10 */
&::-ms-expand {
display: none;
}
/*For chrome*/
-webkit-appearance:none;
&.placeholder {
opacity: 0.7;
color: theme-color('mutedColor');
}
option {
color: black;
}
}
}
You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
keyWindow = window;
break;
}
}
}
If the image isn't that big, and if there's a good chance you'll be re-using the image often, and if you don't have too many of them, and if the images are not secret (meaning it's no big deal if one user could potentially see another person's image)...
Lots of "if"s here, so there's a good chance this is a bad idea:
You can store the image bytes in Cache
for a short time, and make an image tag pointed toward an action method, which in turn reads from the cache and spits out your image. This will allow the browser to cache the image appropriately.
// In your original controller action
HttpContext.Cache.Add("image-" + model.Id, model.ImageBytes, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1),
CacheItemPriority.Normal, null);
// In your view:
<img src="@Url.Action("GetImage", "MyControllerName", new{fooId = Model.Id})">
// In your controller:
[OutputCache(VaryByParam = "fooId", Duration = 60)]
public ActionResult GetImage(int fooId) {
// Make sure you check for null as appropriate, re-pull from DB, etc.
return File((byte[])HttpContext.Cache["image-" + fooId], "image/gif");
}
This has the added benefit (or is it a crutch?) of working in older browsers, where the inline images don't work in IE7 (or IE8 if larger than 32kB).
Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.
Example: Suppose we had this class:
class ScopeMonitor
{
static string urlFragment = "foo/bar";
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
}
When you access fullUr
, it will be "http://www.example.com/foo/bar".
Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
static string urlFragment = "foo/bar";
}
Your fullUrl
value is now just "http://www.example.com/" since urlFragment
hadn't been initialized at the time fullUrl
was being set. Not good. So, you add a static constructor to take care of the initialization:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl;
static string urlFragment = "foo/bar";
static ScopeMonitor()
{
fullUrl= firstPart + urlFragment;
}
}
Now, no matter what order you have the fields, the initialization will always be correct.
This can be done in multple ways.
As suggested above, before return
store all elements in the array
Loop inside return
Method 1
let container =[];
let arr = [1,2,3] //can be anything array, object
arr.forEach((val,index)=>{
container.push(<div key={index}>
val
</div>)
/**
* 1. All loop generated elements require a key
* 2. only one parent element can be placed in Array
* e.g. container.push(<div key={index}>
val
</div>
<div>
this will throw error
</div>
)
**/
});
return (
<div>
<div>any things goes here</div>
<div>{container}</div>
</div>
)
Method 2
return(
<div>
<div>any things goes here</div>
<div>
{(()=>{
let container =[];
let arr = [1,2,3] //can be anything array, object
arr.forEach((val,index)=>{
container.push(<div key={index}>
val
</div>)
});
return container;
})()}
</div>
</div>
)
FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.
Using VsVim the code snippets seem to work a little funny. The shortcut I was looking for when I ended up here is much simpler: after a member name type {g;s;
I have delimiter auto-closing turned on, so the closing brace appears on {, and typing a semicolon triggers an autocomplete for get and set.
It works on VS2013 and VS2015, and VS2012 just lacks the automatic brace matching.
I made a small tkinter application which is sets the label after button clicked
#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory
class Application:
def __init__(self, master):
frame = Frame(master,width=200,height=200)
frame.pack()
self.log_file_btn = Button(frame, text="Select Log File", command=self.selectLogFile,width=25).grid(row=0)
self.image_folder_btn = Button(frame, text="Select Image Folder", command=self.selectImageFile,width=25).grid(row=1)
self.quite_button = Button(frame, text="QUIT", fg="red", command=frame.quit,width=25).grid(row=5)
self.logFilePath =StringVar()
self.imageFilePath = StringVar()
self.labelFolder = Label(frame,textvariable=self.logFilePath).grid(row=0,column=1)
self.labelImageFile = Label(frame,textvariable = self.imageFilePath).grid(row = 1,column=1)
def selectLogFile(self):
filename = askopenfilename()
self.logFilePath.set(filename)
def selectImageFile(self):
imageFolder = askdirectory()
self.imageFilePath.set(imageFolder)
root = Tk()
root.title("Geo Tagging")
root.geometry("600x100")
app = Application(root)
root.mainloop()
The most common reasons for me are so that:
CREATE PROCEDURE UpdateTables
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @RowCount1 INTEGER
DECLARE @RowCount2 INTEGER
DECLARE @RowCount3 INTEGER
DECLARE @RowCount4 INTEGER
UPDATE Table1 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount1 = @@ROWCOUNT
UPDATE Table2 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount2 = @@ROWCOUNT
UPDATE Table3 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount3 = @@ROWCOUNT
UPDATE Table4 Set Column = 0 WHERE Column IS NULL
SELECT @RowCount4 = @@ROWCOUNT
SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
here's another alternative using vector::assign
:
theVector.assign(theSet.begin(), theSet.end());
Download full/Non customized package from there site and replace your fonts file with non customized packages fonts. Its will fixed.
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
Difference Between Abstraction and Encapsulation.
Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.
For example if you delete a record using ORM, and your DELETE CASCADE
will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.
EDITED after @ErdemKAYA comment.
To erase a variable, use the magic command:
%reset_selective <regular_expression>
The variables that are erased from the namespace are the one matching the given <regular_expression>
.
Therefore
%reset_selective -f a
will erase all the variables containing an a
.
Instead, to erase only a
and not aa
:
In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a # raise NameError
In: aa # returns 2
see as well %reset_selective?
for more examples and https://regexone.com/ for a regex tutorial.
To erase all the variables in the namespace see:
%reset?
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
The accepted answer has the drawback that it doesn't take into consideration that a database can be locked by a connection that is executing a query that involves tables in a database other than the one connected to.
This can be the case if the server instance has more than one database and the query directly or indirectly (for example through synonyms) use tables in more than one database etc.
I therefore find that it sometimes is better to use syslockinfo to find the connections to kill.
My suggestion would therefore be to use the below variation of the accepted answer from AlexK:
USE [master];
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), req_spid) + ';'
FROM master.dbo.syslockinfo
WHERE rsc_type = 2
AND rsc_dbid = db_id('MyDB')
EXEC(@kill);
I got this problem while using Bootstrap and I had multiple columns in each rows.
I was trying to give page-break-inside: avoid;
or break-inside: avoid;
to the col-md-6
div elements. That was not working.
I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;
.
Instead, I had to give page-break-inside: avoid;
or break-inside: avoid;
to the <div class="row">
element. And I had multiple rows in my print page.
That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.
In another example case, if you want 4 columns in each row, then use col-md-3
.
You could match the port numbers from wireshark up to port numbers from, say, netstat which will tell you the PID of a process listening on that port.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:
E.g.,
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.
Actually we were wrong.
Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
class RegularEmployee {
private BigDecimal salary = BigDecimal.ONE;
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".02");
}
public BigDecimal calculateBonus() {
return salary.multiply(this.getBonusMultiplier());
}
public BigDecimal calculateOverridenBonus() {
try {
// System.out.println(this.getClass().getDeclaredMethod(
// "getBonusMultiplier").toString());
try {
return salary.multiply((BigDecimal) this.getClass()
.getDeclaredMethod("getBonusMultiplier").invoke(this));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
// ... presumably lots of other code ...
}
final class SpecialEmployee extends RegularEmployee {
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".03");
}
}
public class StaticTestCoolMain {
static public void main(String[] args) {
RegularEmployee Alan = new RegularEmployee();
System.out.println(Alan.calculateBonus());
System.out.println(Alan.calculateOverridenBonus());
SpecialEmployee Bob = new SpecialEmployee();
System.out.println(Bob.calculateBonus());
System.out.println(Bob.calculateOverridenBonus());
}
}
Resulting output:
0.02
0.02
0.02
0.03
what we were trying to achieve :)
Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case
RegularEmployee Carl = new SpecialEmployee();
System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
just look at output console:
0.02
0.03
;)
$("selectorbyclassorbyIDorbyName").click(function () {
$("selectorbyclassorbyIDorbyName").attr("disabled", true).delay(2000).attr("disabled", false);
});
select the button and by its id or text or class ... it just disables after 1st click and enables after 20 Milli sec
Works very well for post backs n place it in Master page, applies to all buttons without calling implicitly like onclientClick
I encapsulate the jQuery Ajax to a method:
var http_util = function (type, url, params, success_handler, error_handler, base_url) {
if(base_url) {
url = base_url + url;
}
var success = arguments[3]?arguments[3]:function(){};
var error = arguments[4]?arguments[4]:function(){};
$.ajax({
type: type,
url: url,
dataType: 'json',
data: params,
success: function (data, textStatus, xhr) {
if(textStatus === 'success'){
success(xhr.code, data); // there returns the status code
}
},
error: function (xhr, error_text, statusText) {
error(xhr.code, xhr); // there returns the status code
}
})
}
Usage:
http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
console(status_code, data)
}, function(status_code, err){
console(status_code, err)
})
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
Using window.location.href
it's not possible to send a POST request.
What you have to do is to set up a form
tag with data fields in it, set the action
attribute of the form to the URL and the method
attribute to POST, then call the submit
method on the form
tag.
I prefer this syntax as it allows to set configuration parameters for the shell:
---
- name: an example
shell:
cmd: |
docker build -t current_dir .
echo "Hello World"
date
chdir: /home/vagrant/
The new tests you wrote (directly or indirectly) use classes that log using Log4j.
Log4J needs to be configured for this logging to work properly.
Put a log4j.properties (or log4j.xml) file in the root of your test classpath.
It should have some basic configuration such as
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
An appender outputs to the console by default, but you can also explicitly set the target like this:
log4j.appender.A1.Target=System.out
This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,
Log4J Logging will then be properly configured and this warning will disappear.
In simple words, dereferencing means accessing the value from a certain memory location against which that pointer is pointing.
Use valueAsNumber
instead of .val()
.
input . valueAsNumber [ = value ]
Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.
I know, I know, but...
public static bool TryGetQueryString<T>(string key, out T queryString)
run this code
npm i -g react-native-cli
close your cmd and open it again
I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:
.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }
Fiddle: http://jsfiddle.net/5WsEt/
In my situation, the controller method was not made as async and the method called inside the controller method was async.
So I guess its important to use async/await all the way to top level to avoid issues like these.
By far the easiest way is to log in GitHub account:
yourUsername/yourRepository
for example mbaric/zpropertyz
.gitHubUsername/nameOfTheRepository
and click on the button below which says: I understand the consequences, delete the repositoryimport java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
I needed an elegant solution for the busybox (router), all xargs or array solutions were useless to me - no such command available there. find and mtime is not the proper answer as we are talking about 10 items and not necessarily 10 days. Espo's answer was the shortest and cleanest and likely the most unversal one.
Error with spaces and when no files are to be deleted are both simply solved the standard way:
rm "$(ls -td *.tar | awk 'NR>7')" 2>&-
Bit more educational version: We can do it all if we use awk differently. Normally, I use this method to pass (return) variables from the awk to the sh. As we read all the time that can not be done, I beg to differ: here is the method.
Example for .tar files with no problem regarding the spaces in the filename. To test, replace "rm" with the "ls".
eval $(ls -td *.tar | awk 'NR>7 { print "rm \"" $0 "\""}')
Explanation:
ls -td *.tar
lists all .tar files sorted by the time. To apply to all the files in the current folder, remove the "d *.tar" part
awk 'NR>7...
skips the first 7 lines
print "rm \"" $0 "\""
constructs a line: rm "file name"
eval
executes it
Since we are using rm
, I would not use the above command in a script! Wiser usage is:
(cd /FolderToDeleteWithin && eval $(ls -td *.tar | awk 'NR>7 { print "rm \"" $0 "\""}'))
In the case of using ls -t
command will not do any harm on such silly examples as: touch 'foo " bar'
and touch 'hello * world'
. Not that we ever create files with such names in real life!
Sidenote. If we wanted to pass a variable to the sh this way, we would simply modify the print (simple form, no spaces tolerated):
print "VarName="$1
to set the variable VarName
to the value of $1
. Multiple variables can be created in one go. This VarName
becomes a normal sh variable and can be normally used in a script or shell afterwards. So, to create variables with awk and give them back to the shell:
eval $(ls -td *.tar | awk 'NR>7 { print "VarName=\""$1"\"" }'); echo "$VarName"
str = str.replace(/abc/g, '');
Or try the replaceAll function from here:
What are useful JavaScript methods that extends built-in objects?
str = str.replaceAll('abc', ''); OR
var search = 'abc';
str = str.replaceAll(search, '');
EDIT: Clarification about replaceAll availability
The 'replaceAll' method is added to String's prototype. This means it will be available for all string objects/literals.
E.g.
var output = "test this".replaceAll('this', 'that'); //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
Just append :after
to your #alertlist li:hover
selector the same way you do with your #alertlist li.selected
selector:
#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
queryForList returns a List of LinkedHashMap objects.
You need to cast it first like this:
List list = jdbcTemplate.queryForList(...); for (Object o : list) { Map m = (Map) o; ... }
You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.
To do so you first need to install Plotly by running:
pip install plotly
You might also want to upgrade the library by running:
pip install plotly --upgrade
After that in you Jupyter Notebook you may write something like:
# Import dependencies
import plotly
import plotly.graph_objs as go
# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()
# Configure the trace.
trace = go.Scatter3d(
x=[1, 2, 3], # <-- Put your data instead
y=[4, 5, 6], # <-- Put your data instead
z=[7, 8, 9], # <-- Put your data instead
mode='markers',
marker={
'size': 10,
'opacity': 0.8,
}
)
# Configure the layout.
layout = go.Layout(
margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)
data = [trace]
plot_figure = go.Figure(data=data, layout=layout)
# Render the plot.
plotly.offline.iplot(plot_figure)
As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.
Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.
Most of my points are related to Invariant's answer, so I would suggest to go through it first.
UPDATE
JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.
Old answer with JavaFXPorts
Some bad news first:
Now, some good news:
If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.
Most of the documentation on how to get started can be found here and some of the samples can be found here.
Since Server.MapPath()
does not exist within a Web Api (Soap or REST), you'll need to denote the local- relative to the web server's context- home directory. The easiest way to do so is with:
string AppContext.BaseDirectory { get;}
You can then use this to concatenate a path string to map the relative path to any file.
NOTE: string paths are \
and not /
like they are in mvc.
Ex:
System.IO.File.Exists($"{**AppContext.BaseDirectory**}\\\\Content\\\\pics\\\\{filename}");
returns true- positing that this is a sound path in your example
This is a perfect use-case for DISTINCT ON
- a Postgres specific extension of the standard DISTINCT
:
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY category, date DESC;
Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST
:
DISTINCT ON
is simple and fast. Detailed explanation in this related answer:
For big tables with many rows per category
consider an alternative approach:
A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.
It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.
Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.
They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.
Never mind, figured it out:
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
Which I found by:
show all
And looking for some option that seemed relevant.
For what it's worth, here is how using GitHub on a Windows machine. Let's say you have a cloned repo in residing in C:\dir1
. The directory structure looks like this: C:\dir1\dir2\dir3
. The dir3
directory is the one I want to be a new separate repo.
Github:
MyTeam/mynewrepo
Bash Prompt:
$ cd c:/Dir1
$ git filter-branch --prune-empty --subdirectory-filter dir2/dir3 HEAD
Returned: Ref 'refs/heads/master' was rewritten
(fyi: dir2/dir3 is case sensitive.)
$ git remote add some_name [email protected]:MyTeam/mynewrepo.git
git remote add origin etc
. did not work, returned "remote origin already exists
"
$ git push --progress some_name master
Partial Class _Default
Inherits System.Web.UI.Page
Dim str As String
Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed
str += "PAGE DISPOSED" & "<br />"
End Sub
Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
str += "PAGE ERROR " & "<br />"
End Sub
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
str += "PAGE INIT " & "<br />"
End Sub
Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
str += "INIT Complte " & "<br />"
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
str += "PAGE LOAD " & "<br />"
End Sub
Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
str += "PAGE LOAD Complete " & "<br />"
End Sub
Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
str = ""
str += "PAGE PRE INIT" & "<br />"
End Sub
Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
str += "PAGE PRE LOAD " & "<br />"
End Sub
Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
str += "PAGE PRE RENDER " & "<br />"
End Sub
Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
str += "PAGE PRE RENDER COMPLETE " & "<br />"
End Sub
Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
str += "PAGE SAVE STATE COMPLTE " & "<br />"
lbl.Text = str
End Sub
Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
'Response.Write("PAGE UN LOAD\n")
End Sub
End Class
There is a small bug in the above code (by the way Dave it was very helpful your post thank you)
In the part where we save the credentials it also needs the following code in order to work properly.
[self.keychainItem setObject:@"myCredentials" forKey:(__bridge id)(kSecAttrService)];
most probably is because the second time we try to (re-)sign in with the same credentials it finds them already assigned in the keychain items and the app crashes. with the above code it works like a charm.
Try use this:
<html>
<body>
<input type="text" style="direction: rtl;" value="1">
<input type="text" style="direction: rtl;" value="10">
<input type="text" style="direction: rtl;" value="100">
</body>
</html>
my jQuery powered solution is below :)
Text Element:
<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />
Javascript behind:
<script type="text/javascript" language="javascript">
function fnCheckValue() {
var myVal = $("#txtTextBox").val();
if (myVal == "") {
alert("Blank message");
return false;
}
else {
return true;
}
}
function EnterEvent(e) {
if (e.keyCode == 13) {
if (fnCheckValue()) {
$("#btnSubmitButton").trigger("click");
} else {
return false;
}
}
}
$("#btnSubmitButton").click(function () {
return fnCheckValue();
});
</script>
My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.
You can use my library for accessing files from multiple apps.
You can install it from nuget: Install-Package Xabe.FileLock
If you want more information about it check https://github.com/tomaszzmuda/Xabe.FileLock
ILock fileLock = new FileLock(file);
if(fileLock.Acquire(TimeSpan.FromSeconds(15), true))
{
using(fileLock)
{
// file operations here
}
}
fileLock.Acquire method will return true only if can lock file exclusive for this object. But app which uploading file must do it in file lock too. If object is inaccessible metod returns false.
You're trying to use a dict
as a key to another dict
or in a set
. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:
>>> key = frozenset(dict_key.items())
Now you may use key
as a key in a dict
or set
:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Of course you need to repeat the exercise whenever you want to look up something using a dict:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
If the dict
you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d
It works for me. In oracle:
SELECT SUM(DECODE(COUNT(*),1,1,1))
FROM DocumentOutputItems GROUP BY DocumentId, DocumentSessionId;
In jpql:
SELECT SUM(CASE WHEN COUNT(i)=1 THEN 1 ELSE 1 END)
FROM DocumentOutputItems i GROUP BY i.DocumentId, i.DocumentSessionId;
In swift
yourLabel.intrinsicContentSize().width
Use the following code if you want to select an option with a specific value:
$('select>option[value="' + value + '"]').prop('selected', true);
/* The customcheck */_x000D_
.customcheck {_x000D_
display: block;_x000D_
position: relative;_x000D_
padding-left: 35px;_x000D_
margin-bottom: 12px;_x000D_
cursor: pointer;_x000D_
font-size: 22px;_x000D_
-webkit-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #eee;_x000D_
border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
background-color: #02cf32;_x000D_
border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
left: 9px;_x000D_
top: 5px;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid white;_x000D_
border-width: 0 3px 3px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>Custom Checkboxes</h1></br>_x000D_
_x000D_
<label class="customcheck">One_x000D_
<input type="checkbox" checked="checked">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Two_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Three_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
<label class="customcheck">Four_x000D_
<input type="checkbox">_x000D_
<span class="checkmark"></span>_x000D_
</label>_x000D_
</div>
_x000D_
You only have to provide
-Dmaven.test.skip
You no longer need to append =true
.
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
Have a look at PHP's available XML extensions.
The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.
Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.
RETURN day(dateadd(month, 12 * @year + @month - 22800, -1))
select day(dateadd(month, 12 * year(date) + month(date) - 22800, -1))
data.matrix(SFI)
From ?data.matrix
:
Description:
Return the matrix obtained by converting all the variables in a
data frame to numeric mode and then binding them together as the
columns of a matrix. Factors and ordered factors are replaced by
their internal codes.
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:
conda install python=3.6
then:
pip install tensorflow
it worked for me in Ubuntu.
All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:
sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"
It's possible to define almost all mysql_*
functions using mysqli or PDO. Just include them on top of your old PHP application, and it will work on PHP7. My solution here.
<?php
define('MYSQL_LINK', 'dbl');
$GLOBALS[MYSQL_LINK] = null;
function mysql_link($link=null) {
return ($link === null) ? $GLOBALS[MYSQL_LINK] : $link;
}
function mysql_connect($host, $user, $pass) {
$GLOBALS[MYSQL_LINK] = mysqli_connect($host, $user, $pass);
return $GLOBALS[MYSQL_LINK];
}
function mysql_pconnect($host, $user, $pass) {
return mysql_connect($host, $user, $pass);
}
function mysql_select_db($db, $link=null) {
$link = mysql_link($link);
return mysqli_select_db($link, $db);
}
function mysql_close($link=null) {
$link = mysql_link($link);
return mysqli_close($link);
}
function mysql_error($link=null) {
$link = mysql_link($link);
return mysqli_error($link);
}
function mysql_errno($link=null) {
$link = mysql_link($link);
return mysqli_errno($link);
}
function mysql_ping($link=null) {
$link = mysql_link($link);
return mysqli_ping($link);
}
function mysql_stat($link=null) {
$link = mysql_link($link);
return mysqli_stat($link);
}
function mysql_affected_rows($link=null) {
$link = mysql_link($link);
return mysqli_affected_rows($link);
}
function mysql_client_encoding($link=null) {
$link = mysql_link($link);
return mysqli_character_set_name($link);
}
function mysql_thread_id($link=null) {
$link = mysql_link($link);
return mysqli_thread_id($link);
}
function mysql_escape_string($string) {
return mysql_real_escape_string($string);
}
function mysql_real_escape_string($string, $link=null) {
$link = mysql_link($link);
return mysqli_real_escape_string($link, $string);
}
function mysql_query($sql, $link=null) {
$link = mysql_link($link);
return mysqli_query($link, $sql);
}
function mysql_unbuffered_query($sql, $link=null) {
$link = mysql_link($link);
return mysqli_query($link, $sql, MYSQLI_USE_RESULT);
}
function mysql_set_charset($charset, $link=null){
$link = mysql_link($link);
return mysqli_set_charset($link, $charset);
}
function mysql_get_host_info($link=null) {
$link = mysql_link($link);
return mysqli_get_host_info($link);
}
function mysql_get_proto_info($link=null) {
$link = mysql_link($link);
return mysqli_get_proto_info($link);
}
function mysql_get_server_info($link=null) {
$link = mysql_link($link);
return mysqli_get_server_info($link);
}
function mysql_info($link=null) {
$link = mysql_link($link);
return mysqli_info($link);
}
function mysql_get_client_info() {
$link = mysql_link();
return mysqli_get_client_info($link);
}
function mysql_create_db($db, $link=null) {
$link = mysql_link($link);
$db = str_replace('`', '', mysqli_real_escape_string($link, $db));
return mysqli_query($link, "CREATE DATABASE `$db`");
}
function mysql_drop_db($db, $link=null) {
$link = mysql_link($link);
$db = str_replace('`', '', mysqli_real_escape_string($link, $db));
return mysqli_query($link, "DROP DATABASE `$db`");
}
function mysql_list_dbs($link=null) {
$link = mysql_link($link);
return mysqli_query($link, "SHOW DATABASES");
}
function mysql_list_fields($db, $table, $link=null) {
$link = mysql_link($link);
$db = str_replace('`', '', mysqli_real_escape_string($link, $db));
$table = str_replace('`', '', mysqli_real_escape_string($link, $table));
return mysqli_query($link, "SHOW COLUMNS FROM `$db`.`$table`");
}
function mysql_list_tables($db, $link=null) {
$link = mysql_link($link);
$db = str_replace('`', '', mysqli_real_escape_string($link, $db));
return mysqli_query($link, "SHOW TABLES FROM `$db`");
}
function mysql_db_query($db, $sql, $link=null) {
$link = mysql_link($link);
mysqli_select_db($link, $db);
return mysqli_query($link, $sql);
}
function mysql_fetch_row($qlink) {
return mysqli_fetch_row($qlink);
}
function mysql_fetch_assoc($qlink) {
return mysqli_fetch_assoc($qlink);
}
function mysql_fetch_array($qlink, $result=MYSQLI_BOTH) {
return mysqli_fetch_array($qlink, $result);
}
function mysql_fetch_lengths($qlink) {
return mysqli_fetch_lengths($qlink);
}
function mysql_insert_id($qlink) {
return mysqli_insert_id($qlink);
}
function mysql_num_rows($qlink) {
return mysqli_num_rows($qlink);
}
function mysql_num_fields($qlink) {
return mysqli_num_fields($qlink);
}
function mysql_data_seek($qlink, $row) {
return mysqli_data_seek($qlink, $row);
}
function mysql_field_seek($qlink, $offset) {
return mysqli_field_seek($qlink, $offset);
}
function mysql_fetch_object($qlink, $class="stdClass", array $params=null) {
return ($params === null)
? mysqli_fetch_object($qlink, $class)
: mysqli_fetch_object($qlink, $class, $params);
}
function mysql_db_name($qlink, $row, $field='Database') {
mysqli_data_seek($qlink, $row);
$db = mysqli_fetch_assoc($qlink);
return $db[$field];
}
function mysql_fetch_field($qlink, $offset=null) {
if ($offset !== null)
mysqli_field_seek($qlink, $offset);
return mysqli_fetch_field($qlink);
}
function mysql_result($qlink, $offset, $field=0) {
if ($offset !== null)
mysqli_field_seek($qlink, $offset);
$row = mysqli_fetch_array($qlink);
return (!is_array($row) || !isset($row[$field]))
? false
: $row[$field];
}
function mysql_field_len($qlink, $offset) {
$field = mysqli_fetch_field_direct($qlink, $offset);
return is_object($field) ? $field->length : false;
}
function mysql_field_name($qlink, $offset) {
$field = mysqli_fetch_field_direct($qlink, $offset);
if (!is_object($field))
return false;
return empty($field->orgname) ? $field->name : $field->orgname;
}
function mysql_field_table($qlink, $offset) {
$field = mysqli_fetch_field_direct($qlink, $offset);
if (!is_object($field))
return false;
return empty($field->orgtable) ? $field->table : $field->orgtable;
}
function mysql_field_type($qlink, $offset) {
$field = mysqli_fetch_field_direct($qlink, $offset);
return is_object($field) ? $field->type : false;
}
function mysql_free_result($qlink) {
try {
mysqli_free_result($qlink);
} catch (Exception $e) {
return false;
}
return true;
}
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
There's no goto
instruction in the Python programming language. You'll have to write your code in a structured way... But really, why do you want to use a goto
? that's been considered harmful for decades, and any program you can think of can be written without using goto
.
Of course, there are some cases where an unconditional jump might be useful, but it's never mandatory, there will always exist a semantically equivalent, structured solution that doesn't need goto
.
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
If you are using Laravel Framework then you can simply use this:
$allKeyList = Redis::KEYS("*");
print_r($allKeyList);
In Core PHP:
$redis = new Redis();
$redis->connect('hostname', 6379);
$allKeyList = $redis->keys('*');
print_r($allKeyList);
Use sysdate-1 to subtract one day from system date.
select sysdate, sysdate -1 from dual;
Output:
SYSDATE SYSDATE-1
-------- ---------
22-10-13 21-10-13
I prefer to do this via a script nowadays
REM install the needed Windows IIS features for WCF
dism /Online /Enable-Feature /FeatureName:WAS-WindowsActivationService
dism /Online /Enable-Feature /FeatureName:WAS-ProcessModel
dism /Online /Enable-Feature /FeatureName:WAS-NetFxEnvironment
dism /Online /Enable-Feature /FeatureName:WAS-ConfigurationAPI
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45
REM Feature Install Complete
pause
I hit the same error. I suspect you're using node 12 and gulp 3. That combination does not work: https://github.com/gulpjs/gulp/issues/2324
A previous workaround from Jan. does not work either: https://github.com/gulpjs/gulp/issues/2246
Solution: Either upgrade to gulp 4 or downgrade to an earlier node.
You should think JS for behaviour, and CSS for visual candy as much as possible. By changing your HTML a bit :
<td class="post">
<a class="p-edit-btn" href="#" onclick="showStuff(this.parentNode);return false;">Edit</a>
<span id="answer1" class="post-answer">
<textarea rows="10" cols="115"></textarea>
</span>
<span class="post-text" id="text1">Lorem ipsum ... </span>
</td>
You'll be able to switch from one view to the other simply using CSS rules :
td.post-editing > a.post-edit-btn,
td.post-editing > span.post-text,
td.post > span.post-answer
{
display : none;
}
And JS code that switch between the two classes
<script type="text/javascript">
function showStuff(aPostTd) {
aPostTd.className="post-editing";
}
</script>
You can also use for 1080 hd values:
240p: &vq=small , 360p: &vq=medium , 480p: &vq=large , 720p: &vq=hd720 , &vq=hd1080
Try using WGET
:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
You can do it by MXBeans
public class Check {
public static void main(String[] args) {
MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
MemoryUsage heapMemoryUsage = memBean.getHeapMemoryUsage();
System.out.println(heapMemoryUsage.getMax()); // max memory allowed for jvm -Xmx flag (-1 if isn't specified)
System.out.println(heapMemoryUsage.getCommitted()); // given memory to JVM by OS ( may fail to reach getMax, if there isn't more memory)
System.out.println(heapMemoryUsage.getUsed()); // used now by your heap
System.out.println(heapMemoryUsage.getInit()); // -Xms flag
// |------------------ max ------------------------| allowed to be occupied by you from OS (less than xmX due to empty survival space)
// |------------------ committed -------| | now taken from OS
// |------------------ used --| | used by your heap
}
}
But remember it is equivalent to Runtime.getRuntime()
(took depicted schema from here)
memoryMxBean.getHeapMemoryUsage().getUsed() <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax() <=> runtime.maxMemory()
from javaDoc
init - represents the initial amount of memory (in bytes) that the Java virtual machine requests from the operating system for memory management during startup. The Java virtual machine may request additional memory from the operating system and may also release memory to the system over time. The value of init may be undefined.
used - represents the amount of memory currently used (in bytes).
committed - represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine. The amount of committed memory may change over time (increase or decrease). The Java virtual machine may release memory to the system and committed could be less than init. committed will always be greater than or equal to used.
max - represents the maximum amount of memory (in bytes) that can be used for memory management. Its value may be undefined. The maximum amount of memory may change over time if defined. The amount of used and committed memory will always be less than or equal to max if max is defined. A memory allocation may fail if it attempts to increase the used memory such that used > committed even if used <= max would still be true (for example, when the system is low on virtual memory).
+----------------------------------------------+
+//////////////// | +
+//////////////// | +
+----------------------------------------------+
|--------|
init
|---------------|
used
|---------------------------|
committed
|----------------------------------------------|
max
As additional note, maxMemory is less than -Xmx because there is necessity at least in one empty survival space, which can't be used for heap allocation.
also it is worth to to take a look at here and especially here
Here is a simple implementation that handles an unequal number of classes in the predicted and actual labels (see examples 3 and 4). I hope this helps!
For folks just learning this, here's a quick review. The labels for the columns indicate the predicted class, and the labels for the rows indicate the correct class. In example 1, we have [3 1] on the top row. Again, rows indicate truth, so this means that the correct label is "0" and there are 4 examples with ground truth label of "0". Columns indicate predictions, so we have 3/4 of the samples correctly labeled as "0", but 1/4 was incorrectly labeled as a "1".
def confusion_matrix(actual, predicted):
classes = np.unique(np.concatenate((actual,predicted)))
confusion_mtx = np.empty((len(classes),len(classes)),dtype=np.int)
for i,a in enumerate(classes):
for j,p in enumerate(classes):
confusion_mtx[i,j] = np.where((actual==a)*(predicted==p))[0].shape[0]
return confusion_mtx
Example 1:
actual = np.array([1,1,1,1,0,0,0,0])
predicted = np.array([1,1,1,1,0,0,0,1])
confusion_matrix(actual,predicted)
0 1
0 3 1
1 0 4
Example 2:
actual = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","a"])
confusion_matrix(actual,predicted)
0 1
0 4 0
1 1 3
Example 3:
actual = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","z"]) # <-- notice the 3rd class, "z"
confusion_matrix(actual,predicted)
0 1 2
0 4 0 0
1 0 3 1
2 0 0 0
Example 4:
actual = np.array(["a","a","a","x","x","b","b","b"]) # <-- notice the 4th class, "x"
predicted = np.array(["a","a","a","a","b","b","b","z"])
confusion_matrix(actual,predicted)
0 1 2 3
0 3 0 0 0
1 0 2 0 1
2 1 1 0 0
3 0 0 0 0
In using toolbar you should extends AppCompatActivity and
import android.support.v7.widget.Toolbar
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
Ok, so this was a bit harder than I though:
def print_matrix(list_of_list):
number_width = len(str(max([max(i) for i in list_of_list])))
cols = max(map(len, list_of_list))
output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
for row in list_of_list:
for column in row:
output += '|' + ' {:^{width}d} '.format(column, width = number_width)
output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
return output
This should work for variable number of rows, columns and number of digits (for numbers)
data = [[1,2,30],
[4,23125,6],
[7,8,999],
]
print print_matrix(data)
>>>>+-------+-------+-------+
| 1 | 2 | 30 |
+-------+-------+-------+
| 4 | 23125 | 6 |
+-------+-------+-------+
| 7 | 8 | 999 |
+-------+-------+-------+
Try h.264 in an mp4 container. I've had much success with it on my Droid X. I've been using zencoder.com for format conversions.
Removing the Tomcat Server and adding new tomcat configuration in Eclipse resolved issue for me.
If you have a Decimal or similar numeric type, you can use:
Math.Round(myNumber, 2)
EDIT: So, in your case, it would be:
Public Class Form1
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
End Sub
End Class
cpuguru, if your applet has been compiled with javac 1.3 (or less), your best option is to use Jad.
Unfortunately, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.
If your applet has been compiled with a more recent compiler, you could try JD-GUI : this decompiler is under development, nevertheless, it generates correct Java sources, most of time, for classes compiled with the JDKs 1.4, 1.5 or 1.6.
DarenW, thank you for your post. JD-GUI is not the best decompiler yet ... but I'm working on :)
This query should work very well on MySQL:
SELECT concat(left(curdate(),7),'-01')
There are two ways to get the ip address :
let ip = req.ip
let ip = req.connection.remoteAddress;
But there is a problem with above approaches.
If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1
.
So, the best solution to get the ip address of user is :-
let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height
in the Navbar section.
Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.
public static string ToFormattedCurrencyString(
this decimal currencyAmount,
string isoCurrencyCode,
CultureInfo userCulture)
{
var userCurrencyCode = new RegionInfo(userCulture.Name).ISOCurrencySymbol;
if (userCurrencyCode == isoCurrencyCode)
{
return currencyAmount.ToString("C", userCulture);
}
return string.Format(
"{0} {1}",
isoCurrencyCode,
currencyAmount.ToString("N2", userCulture));
}
case 1: case 2: case 3: case 4: case 5:
System.out.println("testing case 1 to 5");
break;
case 6: case 7: case 8: case 9: case 10:
System.out.println("testing case 6 to 10");
break;
default:
System.out.println("default");
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
In the contracting world I'm often using machines that are using older images. After trying everything above I decided to update my VS 2013 to the most recent version (Update 4). After 90 minutes and a restart the references are working just fine now! Hope this helps!
Try this code for Kotlin
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
var DEVICE_WIDTH = size.x
var DEVICE_HEIGHT = size.y
N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):
N[i]/2
will be a float64
but range()
expects an integer. Just cast the call to
for j in range(int(N[i]/2)):
I had a same problem with AWS and Serverless. I tried with eu-central-1
region and it didn't work so I had to change it to us-east-2
for the example.
Try simple & lightweight PathJS lib.
Simple example:
Path.map("#/page").to(function(){
alert('page!');
});
The /i switch might be what your after.
From xcopy /?
/I If destination does not exist and copying more than one file, assumes that destination must be a directory.
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
Checkout the -maxdepth
flag of find
find . -maxdepth 1 -type d -exec ls -ld "{}" \;
Here I used 1 as max level depth, -type d
means find only directories, which then ls -ld
lists contents of, in long format.
In a nutshell:
Mono = Compiler for C#
Mono Develop = Compiler+IDE
.Net Core = ASP Compiler
Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.
There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.
There are a number of approaches that vary wildly: React inline-style lib comparison chart
What we refer to as "style" actually includes quite a few concepts:
React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.
Instead of building components to render with conditional state-classes, consider adding state-styles directly:
// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />
// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />
Note that we're using a class to style appearance but no longer using any .is-
prefixed class for state and behavior.
We can use Object.assign
(ES6) or _.extend
(underscore/lodash) to add support for multiple states:
// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>
Now that we're using Object.assign
it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />
. Implemented like this:
<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>
Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.
That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.
// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />
// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>
For layout support, I often try to design components to be 100%
width
and height
.
This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.
One thing is certain, you'll need the assistance of a library. Browser-states (:hover
, :focus
), and media-queries are painful in raw React.
I like Radium because the syntax for those hard parts is designed to model that of SASS.
Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:
var styles = {
root: {
display: "block"
},
item: {
color: "black"
complete: {
textDecoration: "line-through"
},
due: {
color: "red"
}
},
}
Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:
React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},
render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});
I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.
I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic
Python (at least the most common implementation of it) follows a pattern of compiling the original source to byte codes, then interpreting the byte codes on a virtual machine. This means (again, the most common implementation) is neither a pure interpreter nor a pure compiler.
The other side of this is, however, that the compilation process is mostly hidden -- the .pyc files are basically treated like a cache; they speed things up, but you normally don't have to be aware of them at all. It automatically invalidates and re-loads them (re-compiles the source code) when necessary based on file time/date stamps.
About the only time I've seen a problem with this was when a compiled bytecode file somehow got a timestamp well into the future, which meant it always looked newer than the source file. Since it looked newer, the source file was never recompiled, so no matter what changes you made, they were ignored...
I have recently encountered this problem. Here are the steps to resolve
<servers>_x000D_
<server>_x000D_
<id>serverId</id>_x000D_
<username>username</username>_x000D_
<password>password</password>_x000D_
</server>_x000D_
</servers>
_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id> _x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>
_x000D_
<profiles>_x000D_
<profile>_x000D_
<repositories>_x000D_
<repository>_x000D_
<id>serverId</id>_x000D_
<name>aliyun</name>_x000D_
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
</repository>_x000D_
</repositories>_x000D_
</profile>_x000D_
</profiles>
_x000D_
Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.
Instead of:
input:not(disabled)not:[type="submit"]:focus {}
Use:
input:not([disabled]):not([type="submit"]):focus {}
disabled
is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not()
selector.
Demo: http://jsfiddle.net/HSKPx/
One thing to note: I may be wrong, but I don't think disabled
inputs can normally receive focus, so that part may be redundant.
Alternatively, use :enabled
input:enabled:not([type="submit"]):focus { /* styles here */ }
Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.
Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
@params = new string[]{
"IPutAGuidHere",
"[email protected]",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.
I'd say #3 is pretty wacky and probably less efficient, so forget that.
Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:
undef @Array;
when done.
2 steps to check if a cronjob is working :
Manually run php command :
/usr/bin/php /mydomain.in/cromail.php
And check if any error is displayed
html, body{width: 99%; height: 99%; overflow: hidden}
img.fit{width: 100%; height: 100%;}
Or maybe check this out: http://css-tricks.com/how-to-resizeable-background-image/
In case you need to find documents which contain NULL elements inside an array of sub-documents, I've found this query which works pretty well:
db.collection.find({"keyWithArray":{$elemMatch:{"$in":[null], "$exists":true}}})
This query is taken from this post: MongoDb query array with null values
It was a great find and it works much better than my own initial and wrong version (which turned out to work fine only for arrays with one element):
.find({
'MyArrayOfSubDocuments': { $not: { $size: 0 } },
'MyArrayOfSubDocuments._id': { $exists: false }
})
When using a wildcard, it had to be present on both sides of the refspec, so +refs/heads/*:refs/heads/master
will not work. But you can use +HEAD:refs/heads/master
:
git config remote.heroku.push +HEAD:refs/heads/master
Also, you can do this directly with git push:
git push heroku +HEAD:master
git push -f heroku HEAD:master
take a look at Trim()
which returns a new string with whitespace removed from the beginning and end of the string it is called on.
I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.
ENABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
More generally, to support any IList<T>
, you need to check the interfaces:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~>
-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.
Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.
Alternate word:
~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED
Default value:
~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED
Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.
[Source] From what I've found, it looks like by default, it's only possible to do production and development configs (no staging or other environments) – is that right?
Right now, I've been using a environment.js file that can be used to detect expo release channels and change the variables returned based on that, but for building, I need to update the non- DEV variable returned to be either staging or prod:
import { Constants } from 'expo';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'http://localhost:4000/' : 'http://10.0.2.2:4000/';
const ENV = {
dev: {
apiUrl: localhost,
},
staging: {
apiUrl: 'https://your-staging-api-url-here.com/'
},
prod: {
apiUrl: 'https://your-prod-api-url-here.com/'
},
}
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__) {
return ENV.dev;
} else {
// When publishing to production, change this to `ENV.prod` before running an `expo build`
return ENV.staging;
}
}
export default getEnvVars;
Alternatives
does anyone have experience using react-native-dotenv for projects built with expo? I'd love to hear your thoughts
Make the class public.
class NewClass
{
}
is the same as:
internal class NewClass
{
}
so the class has to be public
Had the same issue with target version 19
on both project.properties
and AndroidManifest.xml
with Ant.
Fixed it by:
Android SDK Build-Tools 19.0.1
Android SDK Build-Tools 19.0.2
I think @Al-Kathiri-Khalid is spot on. The issue is only due to missing support for the API level in Build Tools.
We can also use ReentrantLock to achieve the synchronization for static variables.
public class Test {
private static int count = 0;
private static final ReentrantLock reentrantLock = new ReentrantLock();
public void foo() {
reentrantLock.lock();
count = count + 1;
reentrantLock.unlock();
}
}
First check the version of JDK you are using, it should higher than 1.8.
If it is then proceed to do below steps.
Change Language level of Project and modules in Intellij.
Project
1.File->Project Structure->Project->Project language level Change it to 8 for lamba expressions to work
2.File->Project Structure->Module->Project language level Change it to 8 for lamba expressions to work
This is a simple way to do it!
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script>
function notificationme(){
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"preventDuplicates": true,
"onclick": null,
"showDuration": "100",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "show",
"hideMethod": "hide"
};
toastr.info('MY MESSAGE!');
}
</script>
In my case i had to execute a command to drop all connections including my active administrator connection
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
which terminated all connections and show me a fatal ''error'' message :
FATAL: terminating connection due to administrator command SQL state: 57P01
After that it was possible to drop the database
Yes, you can 'refresh' a Google Map like this:
google.maps.event.trigger(map, 'resize');
This basically sends a signal to your map to redraw it.
Hope that helps!
you can also create your own interface as well.
export interface UserEvent {
target: HTMLInputElement;
}
...
onUpdatingServerName(event: UserEvent) {
.....
}
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):
[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {
...without also also placing a [RoutePrefix] at the top of the Controller:
[RoutePrefix("api/values")]
public class ValuesController : ApiController
I was getting errors stating that no Route was found matching the submitted URI. Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
Blending mode used to apply the background tint.
Tint to apply to the background. Must be a color value, in the form of
#rgb
,#argb
,#rrggbb
, or#aarrggbb
.This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
Currently a git replace might do the trick.
In detail: Create a temporary work branch
git checkout -b temp
Reset to the commit to replace
git reset --hard <sha1>
Amend the commit with the right message
git commit --amend -m "<right message>"
Replace the old commit with the new one
git replace <old commit sha1> <new commit sha1>
go back to the branch where you were
git checkout <branch>
remove temp branch
git branch -D temp
push
guess
done.
This is the answer for the question.Reason for the cause is my LDAP string was wrong.
try
{
string adServer = ConfigurationManager.AppSettings["Server"];
string adDomain = ConfigurationManager.AppSettings["Domain"];
string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
string password = ConfigurationManager.AppSettings["Password"];
string[] dc = adDomain.Split('.');
string dcAdDomain = string.Empty;
foreach (string item in dc)
{
if (dc[dc.Length - 1].Equals(item))
dcAdDomain = dcAdDomain + "DC=" + item;
else
dcAdDomain = dcAdDomain + "DC=" + item + ",";
}
DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);
DirectorySearcher ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";
if (ds.FindOne() != null)
return true;
}
catch (Exception ex)
{
ExLog(ex);
}
return false;
Center x = x + 1/2 of width
Center y = y + 1/2 of height
If you know the width and height already then you only need one set of coordinates.
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
I'm with Stroustrup on this one :-) Since NULL is not part of the language, I prefer to use 0.
Set/change your product name, I had this issue until I created a product name as same as project name.
The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.
What about?
input[type="text"] {
max-width:none;
}
Checking that some css file is causing problems. By default bootstrap displays over the entire width. For instance in MVC directory Content is site.css and there is a definition constraining width.
input,select,textarea {
max-width: 280px;}
The VARCHAR(MAX)
type is a replacement for TEXT
. The basic difference is that a TEXT
type will always store the data in a blob whereas the VARCHAR(MAX)
type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.
Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX)
gives you is that it is also can be used with =
and GROUP BY
as any other VARCHAR
column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.
In regard to if you should use LIKE
to search, or if you should use Full Text Indexing and CONTAINS
. This question is the same regardless of VARCHAR(MAX)
or TEXT
.
If you are searching large amounts of text and performance is key then you should use a Full Text Index.
LIKE
is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.
A few options:
filter(lambda x: len(x) > 0, list1) # Doesn't work with number types
filter(None, list1) # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)
sample session:
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>
Looks like there is more to be done for Rails 4.
Inside you Gemfile add.
gem 'bootstrap-sass', '~> 3.2.0.2'
Next you need to run
$bundle install
This is the part no one has mentioned
Open you config/application.rb file
add this right before the second to last end
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
as seen here about a 20% down the page.
Next create a custom.css.scss file in this directory
app/assets/stylesheets
as seen here a little further down from the above task
Inside that file include
@import "bootstrap";
Now stop your server and restart and everything should work fine.
I tried to run bootstrap without using a gem but it didn't work for me.
Hope that helps someone out!
First Method
- (void)didMoveToParentViewController:(UIViewController *)parent
{
if (![parent isEqual:self.parentViewController]) {
NSLog(@"Back pressed");
}
}
Second Method
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
After trying all the solutions and none giving acceptable results (maybe because I was working on a device with default very large fonts), the following worked for me (COMPLEX_UNIT_DIP = Device Independent Pixels):
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
in your xml
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/CustomProgressBar"
android:layout_margin="5dip" />
And in res/values/styles.xml
:
<resources>
<style name="CustomProgressBar" parent="android:Widget.ProgressBar.Horizontal">
<item name="android:indeterminateOnly">false</item>
<item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
<item name="android:minHeight">10dip</item>
<item name="android:maxHeight">20dip</item>
</style>
<style name="AppTheme" parent="android:Theme.Light" />
</resources>
And custom_progress_bar_horizontal
is a xml stored in drawable folder which defines your custom progress bar. For more detail see this blog.
I hope this will help you.
How your URLs look have nothing to do with REST. Anything goes. It actually is an "implementation detail". So just like how you name your variables. All they have to be is unique and durable.
Don't waste too much time on this, just make a choice and stick to it/be consistent. For example if you go with hierarchies then you do it for all your resources. If you go with query parameters...etc just like naming conventions in your code.
Why so ? As far as I know a "RESTful" API is to be browsable (you know..."Hypermedia as the Engine of Application State"), therefore an API client does not care about what your URLs are like as long as they're valid (there's no SEO, no human that needs to read those "friendly urls", except may be for debugging...)
How nice/understandable a URL is in a REST API is only interesting to you as the API developer, not the API client, as would the name of a variable in your code be.
The most important thing is that your API client know how to interpret your media type. For example it knows that :
Below is an example HTTP exchange (bodies are in yaml since it's easier to write):
Request
GET / HTTP/1.1
Host: api.acme.io
Accept: text/yaml, text/acme-mediatype+yaml
Response: a list of links to main resource (companies, people, whatever...)
HTTP/1.1 200 OK
Date: Tue, 05 Apr 2016 15:04:00 GMT
Last-Modified: Tue, 05 Apr 2016 00:00:00 GMT
Content-Type: text/acme-mediatype+yaml
# body: this is your API's entrypoint (like a homepage)
links:
# could be some random path https://api.acme.local/modskmklmkdsml
# the only thing the API client cares about is the key (or rel) "companies"
companies: https://api.acme.local/companies
people: https://api.acme.local/people
Request: link to companies (using previous response's body.links.companies)
GET /companies HTTP/1.1
Host: api.acme.local
Accept: text/yaml, text/acme-mediatype+yaml
Response: a partial list of companies (under items), the resource contains related links, like link to get the next couple of companies (body.links.next) an other (templated) link to search (body.links.search)
HTTP/1.1 200 OK
Date: Tue, 05 Apr 2016 15:06:00 GMT
Last-Modified: Tue, 05 Apr 2016 00:00:00 GMT
Content-Type: text/acme-mediatype+yaml
# body: representation of a list of companies
links:
# link to the next page
next: https://api.acme.local/companies?page=2
# templated link for search
search: https://api.acme.local/companies?query={query}
# you could provide available actions related to this resource
actions:
add:
href: https://api.acme.local/companies
method: POST
items:
- name: company1
links:
self: https://api.acme.local/companies/8er13eo
# and here is the link to departments
# again the client only cares about the key department
department: https://api.acme.local/companies/8er13eo/departments
- name: company2
links:
self: https://api.acme.local/companies/9r13d4l
# or could be in some other location !
department: https://api2.acme.local/departments?company=8er13eo
So as you see if you go the links/relations way how you structure the path part of your URLs does't have any value to your API client. And if your are communicating the structure of your URLs to your client as documentation, then your are not doing REST (or at least not Level 3 as per "Richardson's maturity model")
If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.
to do this you can write: gVim --remote-tab-silent file
You could always make an alias to this command so that you don't have to type so many words.
For example I use linux and bash and in my ~/.bashrc
file I have:
alias g='gvim --remote-tab-silent'
so instead of doing $ mate file
I do: $ g file
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new);
system( cmd);
Add some error checks...
Otherwise, open both and loop on read/write, but probably not what you want.
...
UPDATE to address valid security concerns:
Rather than using "system()", do a fork/wait, and call execv() or execl() in the child.
execl( "/bin/cp", "-p", old, new);
You need to add following jar file in your classpath: slf4j-simple-1.6.2.jar
. If you don't have it, please download it. Please refer to http://www.slf4j.org/codes.html#multiple_bindings
Hello+World
is how a browser will encode form data (application/x-www-form-urlencoded
) for a GET
request and this is the generally accepted form for the query part of a URI.
http://host/path/?message=Hello+World
If you sent this request to a Java servlet, the servlet would correctly decode the parameter value. Usually the only time there are issues here is if the encoding doesn't match.
Strictly speaking, there is no requirement in the HTTP or URI specs that the query part to be encoded using application/x-www-form-urlencoded
key-value pairs; the query part just needs to be in the form the web server accepts. In practice, this is unlikely to be an issue.
It would generally be incorrect to use this encoding for other parts of the URI (the path for example). In that case, you should use the encoding scheme as described in RFC 3986.
http://host/Hello%20World
More here.
strtotime
? Lists? Regular expressions?
What's wrong with PHP's native DateTime object?
Unknown92 answer helped me (on windows). Note that all versions must fit.
I've downloaded cx_Oracle here, for me the file cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe worked with:
I've fixed this…by simply opening a new tab.
Why it wasn't working I'm not entirely sure, but it could have something to do with how Chrome deals with multiple downloads on a page, perhaps it thought they were spam and just ignored them.
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
As Ryan says, the tsc compiler has a switch --declaration
which generates a .d.ts
file from a .ts
file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.
You sure can.
protected void GetColumNames_DataReader()
{
System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=localhost;database=northwind;trusted_connection=true");
System.Data.SqlClient.SqlCommand SqlCmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Products", SqlCon);
SqlCon.Open();
System.Data.SqlClient.SqlDataReader SqlReader = SqlCmd.ExecuteReader();
System.Int32 _columncount = SqlReader.FieldCount;
System.Web.HttpContext.Current.Response.Write("SqlDataReader Columns");
System.Web.HttpContext.Current.Response.Write(" ");
for ( System.Int32 iCol = 0; iCol < _columncount; iCol ++ )
{
System.Web.HttpContext.Current.Response.Write("Column " + iCol.ToString() + ": ");
System.Web.HttpContext.Current.Response.Write(SqlReader.GetName( iCol ).ToString());
System.Web.HttpContext.Current.Response.Write(" ");
}
}
This is originally from: http://www.dotnetjunkies.ddj.com/Article/B82A22D1-8437-4C7A-B6AA-C6C9BE9DB8A6.dcik
Not sure if this is a new service but now (2016) the easiest way in php is to use geoplugin's php web service: http://www.geoplugin.net/php.gp:
Basic usage:
// GET IP ADDRESS
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = false;
}
// CALL THE WEBSERVICE
$ip_info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
They also provide a ready built class: http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache
C also does a good job at not making anything ambiguous.
Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.
Depending on the usecase it makes a difference whether you use javascript (element.value = x
) or jQuery $(element).val(x);
When x
is undefined
jQuery results in an empty String whereas javascript results in "undefined"
as a String.
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A {
private int i;
public A(int i) {
this.i = i; // this.i can be used to disambiguate the i being referred to
}
}
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method()
clarifies that the call is made by this object.
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
...
<body>
<div id="content">
<b>This is the main container.</b>
</div>
</body>
</html>
You can then center the #content
div using:
#content {
width: 400px;
margin: 0 auto;
background-color: #66ffff;
}
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.
From Python Docs:
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Original:
As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
As olt already pointed out, Image.paste
doesn't work properly, when source and destination both contain alpha.
Consider the following scenario:
Two test images, both contain alpha:
layer1 = Image.open("layer1.png")
layer2 = Image.open("layer2.png")
Compositing image using Image.paste
like so:
final1 = Image.new("RGBA", layer1.size)
final1.paste(layer1, (0,0), layer1)
final1.paste(layer2, (0,0), layer2)
produces the following image (the alpha part of the overlayed red pixels is completely taken from the 2nd layer. The pixels are not blended correctly):
Compositing image using Image.alpha_composite
like so:
final2 = Image.new("RGBA", layer1.size)
final2 = Image.alpha_composite(final2, layer1)
final2 = Image.alpha_composite(final2, layer2)
produces the following (correct) image:
It is working now. This is what I did. You probably won't need all these steps to make it work but just to be sure try them all:
Check the account parameters of your scheduled task and make sure they are set to run whether or not someone is logged into the machine
check run with most privileges/rights
Make sure you go to the full path first: cd C:\inetpub\wwwroot\infoweb\factuur\cron
Don't use double quotes in your batch files (don't know why but seems to help)
Be super admin, enter 'Net user administrator /active:yes' in command prompt, log out and log in as the super admin, so UAC is off
I updated to use ContextCompat.getColor(context, R.color.your_color);
but sometimes (On some devices/Android versions. I'm not sure) that causes a NullPointerExcepiton.
So to make it work on all devices/versions, I fall back on the old way of doing it, in the case of a null pointer.
try {
textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
}
catch(NullPointerException e) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
}
else {
textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
}
}
PostgreSQL drivers jars are included in Central Repository of Maven:
For PostgreSQL up to 9.1, use:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
or for 9.2+
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
(Thanks to @Caspar for the correction)
You can also use a spline. Feed in the values you have and interpolate points between your known points. Linking this with a least-squares fit, moving average or kalman filter (as mentioned in other answers) gives you the ability to calculate the points inbetween your "known" points.
Being able to interpolate the values between your knowns gives you a nice smooth transition and a /reasonable/ approximation of what data would be present if you had a higher-fidelity. http://en.wikipedia.org/wiki/Spline_interpolation
Different splines have different characteristics. The one's I've seen most commonly used are Akima and Cubic splines.
Another algorithm to consider is the Ramer-Douglas-Peucker line simplification algorithm, it is quite commonly used in the simplification of GPS data. (http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)
Let's assume you have: function.apply(thisArg, argArray )
The apply method invokes a function, passing in the object that will be bound to this and an optional array of arguments.
The slice() method selects a part of an array, and returns the new array.
So when you call Array.prototype.slice.apply(arguments, [0])
the array slice method is invoked (bind) on arguments.
This is the easiest solution for this problem -
{% autoescape on %}
{{ body }}
{% endautoescape %}
From this page.
you could get a htmldocument by:
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url);
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string s = reader.ReadToEnd();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(s);
so you have getbiyid and getbyname ... but any further you'd better of with
HTML Agility Pack as suggested . f.e
you can do: doc.DocumentNode.SelectNodes(xpathselector)
or regex to parse the doc ..
btw: why not regex ? . its soo cool if you can use it right... but xpath is also very mighty ... so "choose your poison"
cu
In jQuery, the fn
property is just an alias to the prototype
property.
The jQuery
identifier (or $
) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.
A simple constructor function:
function Test() {
this.a = 'a';
}
Test.prototype.b = 'b';
var test = new Test();
test.a; // "a", own property
test.b; // "b", inherited property
A simple structure that resembles the architecture of jQuery:
(function() {
var foo = function(arg) { // core constructor
// ensure to use the `new` operator
if (!(this instanceof foo))
return new foo(arg);
// store an argument for this example
this.myArg = arg;
//..
};
// create `fn` alias to `prototype` property
foo.fn = foo.prototype = {
init: function () {/*...*/}
//...
};
// expose the library
window.foo = foo;
})();
// Extension:
foo.fn.myPlugin = function () {
alert(this.myArg);
return this; // return `this` for chainability
};
foo("bar").myPlugin(); // alerts "bar"
I don't know but this is the format have used...
<h1>
<span id="site-logo" title="xxx" href="#" target="_self">
<img src="http://www.xxx.com/images/xxx.png" alt="xxx" width="xxx" height="xxx" />
<a style="display:none">
<strong>xxx</strong>
</a>
</span>
</h1>
Simple and it has not done my site any harm as far as I can see. You could css it but I don't see it loading any faster.
I found that the following is useful if you need the return value:
result = %x[ls]
puts result
I specifically wanted to list the pids of all the Java processes on my machine, and used this:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.
Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.
In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.
This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.
OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory
Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx
Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const
type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.
I usually use pyexiv2 to set exif information in JPG files, but when I import the library in a script QGIS script crash.
I found a solution using the library exif:
https://pypi.org/project/exif/
It's so easy to use, and with Qgis I don,'t have any problem.
In this code I insert GPS coordinates to a snapshot of screen:
from exif import Image
with open(file_name, 'rb') as image_file:
my_image = Image(image_file)
my_image.make = "Python"
my_image.gps_latitude_ref=exif_lat_ref
my_image.gps_latitude=exif_lat
my_image.gps_longitude_ref= exif_lon_ref
my_image.gps_longitude= exif_lon
with open(file_name, 'wb') as new_image_file:
new_image_file.write(my_image.get_file())