Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:
engine = create_engine(
"postgresql+psycopg2://scott:tiger@host/dbname",
use_batch_mode=True)
http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109
Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..
first install apt-get install python-setuptools
then try easy_install psycopg2
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
This is one of the very good and step by step process to set up PostgreSQL
in ubuntu server. I have tried it with Ubuntu 16.04
and its working.
On alpine, the library containing pg_config
is postgresql-dev
. To install, run:
apk add postgresql-dev
I just had this error too but it was masking another more relevant error message where the code was trying to store a 125 characters string in a 100 characters column:
DatabaseError: value too long for type character varying(100)
I had to debug through the code for the above message to show up, otherwise it displays
DatabaseError: current transaction is aborted
I was having this problem, the main reason was with 2 equal versions installed. One by postgres.app and one by HomeBrew.
If you choose to keep only the APP:
brew unlink postgresql
pip3 install psycopg2
Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.
Solution using Decorators that survives minification/uglification
We use code generation to decorate our Entity classes with metadata like so:
@name('Customer')
export class Customer {
public custId: string;
public name: string;
}
Then consume with the following helper:
export const nameKey = Symbol('name');
/**
* To perserve class name though mangling.
* @example
* @name('Customer')
* class Customer {}
* @param className
*/
export function name(className: string): ClassDecorator {
return (Reflect as any).metadata(nameKey, className);
}
/**
* @example
* const type = Customer;
* getName(type); // 'Customer'
* @param type
*/
export function getName(type: Function): string {
return (Reflect as any).getMetadata(nameKey, type);
}
/**
* @example
* const instance = new Customer();
* getInstanceName(instance); // 'Customer'
* @param instance
*/
export function getInstanceName(instance: Object): string {
return (Reflect as any).getMetadata(nameKey, instance.constructor);
}
Extra info:
reflect-metadata
reflect-metadata
is pollyfill written by members ot TypeScript for the proposed ES7 Reflection APIMaking a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
android:hint="Enter your question" or something like this must work. I am using Relative layout with EditText as If you want to use password,say android:inputType="textPassword" for hiding characters and "textVisiblePassword" for showing what you enter as password.
I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.
if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
echo "none exist actually exist!"
fi
I concur with Franci, all Sysinternals utilities are worth taking a look (Autoruns is a must too), and Process Monitor, which replaces the good old Filemon and Regmon is precious.
Beside the usage you want, it is very useful to see why a process fails (like trying to access a file or a registry key that doesn't exist), etc.
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
If you are using unix, you need to write a shellscript to run you java batch first.
After that, in unix, you run this command "crontab -e
" to edit crontab script.
In order to configure crontab, please refer to this article http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
Save your crontab setting. Then wait for the time to come, program will run automatically.
A working code:
private void changeScreenOrientation() {
int orientation = yourActivityName.this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
showMediaDescription();
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
hideMediaDescription();
}
if (Settings.System.getInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}, 4000);
}
}
call this method in your button click
Python docs has an answer that covers +/-, and exponent notation
scanf() Token Regular Expression
%e, %E, %f, %g [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?
%i [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)
This regular expression does not support international formats where a comma is used as the separator character between the whole and fractional part (3,14159).
In that case, replace all \.
with [.,]
in the above float regex.
Regular Expression
International float [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
The XMLHttpRequest.timeout
property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0
, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests
requests, used in a document environment or it will throw an InvalidAccessError
exception. You may not use a timeout for synchronous requests with an owning window.
IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.
More info can be found here.
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
The 'string' extension type solves several issues with object-dtype NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear than string.
More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.
Please put this code in head section
<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
and use font-family: 'Lato', sans-serif;
in your css. For example:
h1 {
font-family: 'Lato', sans-serif;
font-weight: 400;
}
Or you can use manually also
Generate .ttf
font from fontSquiral
and can try this option
@font-face {
font-family: "Lato";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Called like this
body {
font-family: 'Lato', sans-serif;
}
suppose supply_master is a table, and
SQL>desc supply_master;
SQL>Name
SUPPLIER_NO
SUPPLIER_NAME
ADDRESS1
ADDRESS2
CITY
STATE
PINCODE
SQL>alter table Supply_master rename column ADDRESS1 TO ADDR;
Table altered
SQL> desc Supply_master;
Name
-----------------------
SUPPLIER_NO
SUPPLIER_NAME
ADDR ///////////this has been renamed........//////////////
ADDRESS2
CITY
STATE
PINCODE
Had a similar problem on Centos 7. When I tried to apply the solution prescribed by Sorin, I started moving in cycles. First I had a permission {write} denied. Then when I solved that I had a permission { connectto } denied. Then back again to permission {write } denied.
Following @Sid answer above of checking the flags using getsebool -a | grep httpd
and toggling them I found that in addition to the httpd_can_network_connect being off. http_anon_write was also off resulting in permission denied write and permission denied {connectto}
type=AVC msg=audit(1501830505.174:799183): avc:
denied { write } for pid=12144 comm="nginx" name="myroject.sock"
dev="dm-2" ino=134718735 scontext=system_u:system_r:httpd_t:s0
tcontext=system_u:object_r:default_t:s0 tclass=sock_file
Obtained using sudo cat /var/log/audit/audit.log | grep nginx | grep denied as explained above.
So I solved them one at a time, toggling the flags on one at a time.
setsebool httpd_can_network_connect on -P
Then running the commands specified by @sorin and @Joseph above
sudo cat /var/log/audit/audit.log | grep nginx | grep denied |
audit2allow -M mynginx
sudo semodule -i mynginx.pp
Basically you can check the permissions set on setsebool and correlate that with the error obtained from grepp'ing' audit.log nginx, denied
What does the percentage sign mean?
It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.
%
for Numbers: Modulo operation / Remainder / RestThe percentage sign is an operator in Python. It's described as:
x % y remainder of x / y
So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x
and a divisor y
:
x == y * (x // y) + (x % y)
For example if you divide 5 by 2:
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 * (5 // 2) + (5 % 2)
5
In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:
>>> 15 % 5 # 15 is 3 * 5
0
>>> 81 % 9 # 81 is 9 * 9
0
That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:
if n % x == 0:
break
If you feel that n % x == 0
isn't very descriptive you could put it in another function with a more descriptive name:
def is_multiple(number, divisor):
return number % divisor == 0
...
if is_multiple(n, x):
break
Instead of is_multiple
it could also be named evenly_divides
or something similar. That's what is tested here.
Similar to that it's often used to determine if a number is "odd" or "even":
def is_odd(number):
return number % 2 == 1
def is_even(number):
return number % 2 == 0
And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:
>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
... print(l[index % length])
0
1
2
0
1
2
0
1
2
0
Note that there is also a function for this operator in the standard library operator.mod
(and the alias operator.__mod__
):
>>> import operator
>>> operator.mod(5, 2) # equivalent to 5 % 2
1
But there is also the augmented assignment %=
which assigns the result back to the variable:
>>> a = 5
>>> a %= 2 # identical to: a = a % 2
>>> a
1
%
for strings: printf
-style String FormattingFor strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:
>>> "%s is %s." % ("this", "good")
'this is good'
Here the %
in the string represents a placeholder followed by a formatting specification. In this case I used %s
which means that it expects a string. Then the string is followed by a %
which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s
is replaced by the first argument this
and the second %s
is replaced by the second argument (good
).
Note that there are much better (probably opinion-based) ways to format strings:
>>> "{} is {}.".format("this", "good")
'this is good.'
%
in Jupyter/IPython: magic commandsTo quote the docs:
To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the
%
syntax element for magics as%
is not a valid unary operator in Python. While, the syntax element has meaning in other languages.
This is regularly used in Jupyter notebooks and similar:
In [1]: a = 10
b = 20
%timeit a + b # one % -> line-magic
54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %%timeit # two %% -> cell magic
a ** b
362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%
operator on arrays (in the NumPy / Pandas ecosystem)The %
operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
%
operator for your own classesOf course you can customize how your own classes work when the %
operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.
Just to provide a simple example that shows how it works:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__
is called when %
is applied to an instance:
>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0
Note that it also works for %=
without explicitly needing to implement __imod__
:
>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'
>>> a
0
However you could also implement __imod__
explicitly to overwrite the augmented assignment:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __imod__(self, other):
print("__imod__ called on '{!r}'".format(self))
self.value %= other
return self
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
Now %=
is explicitly overwritten to work in-place:
>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'
>>> a
MyNumber(0)
Not PIL, but scipy.misc.imread
might still be interesting:
import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So you can iterate over it by
for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.
$(document).on('change', 'input[type="file"]', function (event) { _x000D_
var filename = $(this).val();_x000D_
if (filename == undefined || filename == ""){_x000D_
$(this).next('.custom-file-label').html('No file chosen');_x000D_
}_x000D_
else _x000D_
{ $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
});
_x000D_
input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
outline:none!important;_x000D_
border-color: transparent;_x000D_
box-shadow: none!important;_x000D_
}_x000D_
.custom-file,_x000D_
.custom-file-label,_x000D_
.custom-file-input {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container py-5">_x000D_
<div class="input-group mb-3">_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text">Upload</span>_x000D_
</div>_x000D_
<div class="custom-file">_x000D_
<input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can try:
top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1"%"}'
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
As a supplementary, on Amazon EC2, what I need to do is:
sudo yum install freetype-devel
sudo yum install libpng-devel
sudo pip install matplotlib
With Javascript/Jquery:
img
div
and set width, height and backgroundremove the original img
$(document).ready(function() {
var image = $("<img>");
var div = $("<div>")
image.load(function() {
div.css({
"width": this.width,
"height": this.height,
"background-image": "url(" + this.src + ")"
});
$("#container").append(div);
});
image.attr("src", "test0.png");
});
git diff HEAD origin/master
Where origin
is the remote repository and master
is the default branch where you will push. Also, do a git fetch
before the diff
so that you are not diffing against a stale origin/master.
P.S. I am also new to git, so in case the above is wrong, please rectify.
I've built upon Ð?c Thanh Nguy?n's fantastic answer to allow this method to work with 64-bit versions of Excel. I'm running Excel 2010 64-Bit on 64-Bit Windows 7.
Create a new xlsm file and store this code in Module1
Option Explicit
Private Const PAGE_EXECUTE_READWRITE = &H40
Private Declare PtrSafe Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As LongPtr, Source As LongPtr, ByVal Length As LongPtr)
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As LongPtr, _
ByVal dwSize As LongPtr, ByVal flNewProtect As LongPtr, lpflOldProtect As LongPtr) As LongPtr
Private Declare PtrSafe Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As LongPtr
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, _
ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As LongPtr, _
ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
Dim HookBytes(0 To 5) As Byte
Dim OriginBytes(0 To 5) As Byte
Dim pFunc As LongPtr
Dim Flag As Boolean
Private Function GetPtr(ByVal Value As LongPtr) As LongPtr
GetPtr = Value
End Function
Public Sub RecoverBytes()
If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
End Sub
Public Function Hook() As Boolean
Dim TmpBytes(0 To 5) As Byte
Dim p As LongPtr
Dim OriginProtect As LongPtr
Hook = False
pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
If TmpBytes(0) <> &H68 Then
MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6
p = GetPtr(AddressOf MyDialogBoxParam)
HookBytes(0) = &H68
MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
HookBytes(5) = &HC3
MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
Flag = True
Hook = True
End If
End If
End Function
Private Function MyDialogBoxParam(ByVal hInstance As LongPtr, _
ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
If pTemplateName = 4070 Then
MyDialogBoxParam = 1
Else
RecoverBytes
MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
hWndParent, lpDialogFunc, dwInitParam)
Hook
End If
End Function
Paste this code in Module2 and run it
Sub unprotected()
If Hook Then
MsgBox "VBA Project is unprotected!", vbInformation, "*****"
End If
End Sub
DISCLAIMER This worked for me and I have documented it here in the hope it will help someone out. I have not fully tested it. Please be sure to save all open files before proceeding with this option.
Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.
Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.
To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.
@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
.Name("Status.StatusId")
.DataTextField("StatusName")
.DataValueField("StatusId")
.BindTo(...)
)
//So that your ViewModel gets bound properly on the post, naming is a bit
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');
ddl.select(function(dataItem) {
return dataItem.StatusName === "Active";
});
In modern browsers you can use the ::marker CSS pseudo-element like this:
.farParentDiv ul li::marker {
font-size: 0.8em;
}
For browser support, please refer to: Can I Use ::marker pseudo-element
Drop the 's' off of the package name.
You want sudo apt-get install build-essential
You may also need to run sudo apt-get update
to make sure that your package index is up to date.
For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).
If you want to use property_exists
, you'll need to get the name of the class with get_class()
In this case it would be :
if( property_exists( get_class($response), 'records' ) ){
$role_arr = getRole($response->records);
}
else
{
...
}
SELECT Q.FK
,ISNULL(T1.Field1, T2.Field2) AS Field
FROM (SELECT FK FROM Table1
UNION
SELECT FK FROM Table2) AS Q
LEFT JOIN Table1 AS T1 ON T1.FK = Q.FK
LEFT JOIN Table2 AS T2 ON T2.FK = Q.FK
If there is one table, write Table1 instead of Table2
Can't stand aside,
So we have linear system:
A1 * x + B1 * y = C1
A2 * x + B2 * y = C2
let's do it with Cramer's rule, so solution can be found in determinants:
x = Dx/D
y = Dy/D
where D is main determinant of the system:
A1 B1
A2 B2
and Dx and Dy can be found from matricies:
C1 B1
C2 B2
and
A1 C1
A2 C2
(notice, as C column consequently substitues the coef. columns of x and y)
So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L
for storing our coefs A, B, C of the line equations and intestead of pretty x
, y
we'll have [0]
, [1]
, but anyway. Thus, what I wrote above will have the following form further in the code:
for D
L1[0] L1[1]
L2[0] L2[1]
for Dx
L1[2] L1[1]
L2[2] L2[1]
for Dy
L1[0] L1[2]
L2[0] L2[2]
Now go for coding:
line
- produces coefs A, B, C of line equation by two points provided,
intersection
- finds intersection point (if any) of two lines provided by coefs.
from __future__ import division
def line(p1, p2):
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return A, B, -C
def intersection(L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x,y
else:
return False
Usage example:
L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])
R = intersection(L1, L2)
if R:
print "Intersection detected:", R
else:
print "No single intersection point detected"
In my opinion, there is no problem in using var
heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.
Like any other time saver (such as auto properties for example), it is a good idea to understand what it is and how it works before using it everywhere.
If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct()
extension method does internally, i.e. use a HashSet to check for uniqueness:
HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));
The List class provides this convenient RemoveAll(predicate)
method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add()
method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.
Dump your database : pg_dump database_name_name > backup.sql
Import your database back: psql db_name < backup.sql
The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
Then render it at the top of your app, but below Router:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>
^ copied directly from the documentation
Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.
I just discovered that you can also use "-d "
:
cut "-d "
$ cat a
hello how are you
I am fine
$ cut "-d " -f2 a
how
am
This is awesome one:
string.Format("{0:00}:{1:00}:{2:00}",
(int)myTimeSpan.TotalHours,
myTimeSpan.Minutes,
myTimeSpan.Seconds);
I'll toss mine into the ring. It's a simple decorator.
from abc import ABC
def singleton(real_cls):
class SingletonFactory(ABC):
instance = None
def __new__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = real_cls(*args, **kwargs)
return cls.instance
SingletonFactory.register(real_cls)
return SingletonFactory
# Usage
@singleton
class YourClass:
... # Your normal implementation, no special requirements.
Benefits I think it has over some of the other solutions:
YourClass
. This includes not needing to use a metaclass for your class (note that the metaclass above is on the factory, not the "real" class).YourClass
, it looks like a class (because it is), and they use it normally. No need to adapt callers to a factory function.YourClass()
instantiates is still a true instance of the YourClass
you implemented, not a proxy of any kind, so no chance of side effects resulting from that.isinstance(instance, YourClass)
and similar operations still work as expected (though this bit does require abc so precludes Python <2.6).One downside does occur to me: classmethods and staticmethods of the real class are not transparently callable via the factory class hiding it. I've used this rarely enough that I've never happen to run into that need, but it would be easily rectified by using a custom metaclass on the factory that implements __getattr__()
to delegate all-ish attribute access to the real class.
A related pattern I've actually found more useful (not that I'm saying these kinds of things are required very often at all) is a "Unique" pattern where instantiating the class with the same arguments results in getting back the same instance. I.e. a "singleton per arguments". The above adapts to this well and becomes even more concise:
def unique(real_cls):
class UniqueFactory(ABC):
@functools.lru_cache(None) # Handy for 3.2+, but use any memoization decorator you like
def __new__(cls, *args, **kwargs):
return real_cls(*args, **kwargs)
UniqueFactory.register(real_cls)
return UniqueFactory
All that said, I do agree with the general advice that if you think you need one of these things, you really should probably stop for a moment and ask yourself if you really do. 99% of the time, YAGNI.
You need to Go to My Computer->properties -> Advanced system setting
Now click on Environment Variables..
Add ;C:\xampp\php in path variable value
Now restart command prompt DONE!
Note: Make sure you run CMD via run as administrator
ENV['RAILS_ENV']
is now deprecated.
You should use Rails.env
which is clearly much nicer.
This seems to be a common problem. I had to uninstall the latest Connector/NET driver (6.7.4) and install an older version (6.6.5) for it to work. Others report 6.6.6 working for them.
See other topic with more info: MySQL Data Source not appearing in Visual Studio
Getting
java.nio.file.AccessDeniedException
when trying to write to a folder
Unobviously, Comodo antivirus has an "Auto-Containment" setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe
and javaw.exe
processes cannot).
In this edge-case scenario, adding an exception for the process and/or folder should help.
Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.
I post this not because I use or prefer Comodo, but because it's a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.
this solution work only .if your want to ignore this Warning
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="GoogleAppIndexingWarning"
package="com.example.saloononlinesolution">
You can also set the forms activecontrol
property to null
like
ActiveControl = null;
First I need to explain what serialization is.
Serialization allows to convert an object to a stream, for sending that object over the network OR Save to file OR save into DB for letter usage.
There are some rules for serialization.
An object is serializable only if its class or its superclass implements the Serializable interface
An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the first superclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a java.io.InvalidClassException in runtime
All primitive types are serializable.
Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializable must mark transient fields of classes that do not support serialization (e.g., a file stream).
Static fields (with static modifier) are not serialized.
When Object
is serialized, Java Runtime associates the serial version number aka, the serialVersionID
.
Where we need serialVersionID:
During the deserialization to verify that sender and receiver are compatible with respect to serialization. If the receiver loaded the class with a different serialVersionID
then deserialization will end with InvalidClassCastException
.
A serializable class can declare its own serialVersionUID
explicitly by declaring a field named serialVersionUID
that must be static, final, and of type long.
Let's try this with an example.
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String empname;
private byte empage;
public String getEmpName() {
return name;
}
public void setEmpName(String empname) {
this.empname = empname;
}
public byte getEmpAge() {
return empage;
}
public void setEmpAge(byte empage) {
this.empage = empage;
}
public String whoIsThis() {
return getEmpName() + " is " + getEmpAge() + "years old";
}
}
Create Serialize Object
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Writer {
public static void main(String[] args) throws IOException {
Employee employee = new Employee();
employee.setEmpName("Jagdish");
employee.setEmpAge((byte) 30);
FileOutputStream fout = new
FileOutputStream("/users/Jagdish.vala/employee.obj");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(employee);
oos.close();
System.out.println("Process complete");
}
}
Deserialize the object
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Reader {
public static void main(String[] args) throws ClassNotFoundException, IOException {
Employee employee = new Employee();
FileInputStream fin = new FileInputStream("/users/Jagdish.vala/employee.obj");
ObjectInputStream ois = new ObjectInputStream(fin);
employee = (Employee) ois.readObject();
ois.close();
System.out.println(employee.whoIsThis());
}
}
NOTE: Now change the serialVersionUID of the Employee class and save:
private static final long serialVersionUID = 4L;
And execute the Reader class. Not to execute the Writer class and you will get the exception.
Exception in thread "main" java.io.InvalidClassException:
com.jagdish.vala.java.serialVersion.Employee; local class incompatible:
stream classdesc serialVersionUID = 1, local class serialVersionUID = 4
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at com.krishantha.sample.java.serialVersion.Reader.main(Reader.java:14)
I solved the problem for me by addressing also the worksheet first:
ws.rows(x & ":" & y).Select
without the reference to the worksheet (ws) I got an error.
For me, none of the answers worked for ranges that include both virgin cells and cells that are empty based on a formula (e.g. =IF(1=2;"";"")
)
What solved it for me is this:
=COUNTA(FILTER(range, range <> ""))
I found this thread looking to create an ajax page refresh button with jQuery Mobile.
@sgissinger had the closest answer to what I was looking for, but it was outdated.
I updated for jQuery Mobile 1.4
function refreshPage() {
jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
// 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
});
}
// Run it with .on
$(document).on( "click", '#refresh', function() {
refreshPage();
});
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
$('#select_id').on('change', function()
{
alert(this.value); //or alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select_id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Here's a very simple, fast dplyr
/tidy
solution:
Remove rows that are entirely the same:
library(dplyr)
iris %>%
distinct(.keep_all = TRUE)
Remove rows that are the same only in certain columns:
iris %>%
distinct(Sepal.Length, Sepal.Width, .keep_all = TRUE)
554 is commonly used by dns blacklists when shooing away blacklisted servers. I'm assuming
Mon 2008-10-20 16:11:36: * relays.ordb.org - failed
in the log you included is to blame.
Here's an example to make it clear how things work with GCC when static libraries are involved. So let's assume we have the following scenario:
myprog.o
- containing main()
function, dependent on libmysqlclient
libmysqlclient
- static, for the sake of the example (you'd prefer the shared library, of course, as the libmysqlclient
is huge); in /usr/local/lib
; and dependent on stuff from libz
libz
(dynamic)How do we link this? (Note: examples from compiling on Cygwin using gcc 4.3.4)
gcc -L/usr/local/lib -lmysqlclient myprog.o
# undefined reference to `_mysql_init'
# myprog depends on libmysqlclient
# so myprog has to come earlier on the command line
gcc myprog.o -L/usr/local/lib -lmysqlclient
# undefined reference to `_uncompress'
# we have to link with libz, too
gcc myprog.o -lz -L/usr/local/lib -lmysqlclient
# undefined reference to `_uncompress'
# libz is needed by libmysqlclient
# so it has to appear *after* it on the command line
gcc myprog.o -L/usr/local/lib -lmysqlclient -lz
# this works
While:
entry control loop
condition is checked before loop execution
never execute loop if condition is false
there is no semicolon at the end of while statement
Do-while:
exit control loop
condition is checked at the end of loop
executes false condition at least once since condition is checked later
there is semicolon at the end of while statement.
If you are currently using the MongoDB 3.3 Repository (as officially currently suggested by MongoDB website) you should take in consideration that the package name used for version 3.3 is:
mongodb-org-unstable
Then the proper installation command for this version will be:
sudo apt-get install -y mongodb-org-unstable
Considering this, I will rather suggest to use the current latest stable version (v3.2) until the v3.3 becomes stable, the commands to install it are listed below:
Download the v3.2 Repository key:
wget -qO - https://www.mongodb.org/static/pgp/server-3.2.asc | sudo apt-key add -
If you work with Ubuntu 12.04 or Mint 13 add the following repository:
echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
If you work with Ubuntu 14.04 or Mint 17 add the following repository:
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
If you work with Ubuntu 16.04 or Mint 18 add the following repository:
echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
Update the package list and install mongo:
sudo apt-get update
sudo apt-get install -y mongodb-org
I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.
The JS part:
$('[data-toggle="ajaxModal"]').on('click',
function(e) {
$('#ajaxModal').remove();
e.preventDefault();
var $this = $(this)
, $remote = $this.data('remote') || $this.attr('href')
, $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
$('body').append($modal);
$modal.modal({backdrop: 'static', keyboard: false});
$modal.load($remote);
}
);
Finally, in the remote content, you need to put the entire structure to work.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
<a href="#" class="btn btn-primary">Button</a>
<a href="#" class="btn btn-primary">Another button...</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
I fixed it just by editing the gradle-wrapper.properties
file.
You must go to the project folder, then /android/grandle/wrapper/gradle-wrapper.properties
.
In DistributionUrl, change to https \: //services.gradle.org/distributions/gradle-6.4.1-all.zip
.
You can install TortoiseGit for Windows and include integration in context menu. I consider it the best tool to work with Git on Windows.
Take a look at java.text.DateFormat. Easier to use (with a bit less power) is the derived class, java.text.SimpleDateFormat
And here is a good intro to Java internationalization: http://java.sun.com/docs/books/tutorial/i18n/index.html (the "Formatting" section addressing your problem, and more).
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {_x000D_
return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
var minutes = Math.floor(secs / 60);_x000D_
secs = secs%60;_x000D_
var hours = Math.floor(minutes/60)_x000D_
minutes = minutes%60;_x000D_
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
var d = new Date();_x000D_
var d1 = new Date(d.getTime()+s*1000);_x000D_
var hms = hhmmss(s);_x000D_
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
} _x000D_
*/
_x000D_
Step 1: You need to append one blank option
with a blank value in your select tag.
Step 2: Add data-placeholder
attribute in select tag with a placeholder value
HTML
<select class="select2" data-placeholder='--Select--'>
<option value=''>--Select--</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
</select>
Jquery
$('.select2').select2({
placeholder: $(this).data('placeholder')
});
OR
$('.select2').select2({
placeholder: 'Custom placeholder text'
});
the key point is finding the right path where your grunt was installed.
I installed grunt through npm, but my grunt path was /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin/grunt
. So after I added /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin
to ~/.bash_profile
,and source ~/.bash_profile
, It worked.
So the steps are as followings:
1. find the path where your grunt was installed(when you installed grunt, it told you. if you don't remember, you can install it one more time)
2. vi ~/.bash_profile
3. export PATH=$PATH:/your/path/where/grunt/was/installed
4. source ~/.bash_profile
You can refer http://www.hongkiat.com/blog/grunt-command-not-found/
There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.
int i = 0;
bool bi = !!i;
int j = 1;
bool bj = !!j;
Put this in your title popover constructor...
'<button class="btn btn-danger btn-xs pull-right"
onclick="$(this).parent().parent().parent().hide()"><span class="glyphicon
glyphicon-remove"></span></button>some text'
...to get a small red 'x' button on top-right corner
//$('[data-toggle=popover]').popover({title:that string here})
I see what's up with the maps in the OP:
Look at the route with the intermediate point specified: The route goes slightly backwards due to that road that isn't straight.
If their algorithm won't backtrack it won't see the shorter route.
You can do it using streams map function like below, get result in new stream for further processing.
Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
newFruits.forEach(fruit->{
System.out.println(fruit.name);
});
Using display:inline-block
#element1 {display:inline-block;margin-right:10px;}
#element2 {display:inline-block;}
You can use the following methods to specify C:\Program Files without a space in it for programs that can't handle spaces in file paths:
'Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~1\continuum_reports\" or
RepPath = C:\Program Files\Continuum_Reports 'si es para 64 bits.
' Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~2\continuum_reports\" 'or
RepPath = C:\Program Files (x86)\Continuum_Reports 'si es para 32 bits.
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
In your onTestClick
function, pass in the event argument and call preventDefault()
on it.
function onTestClick(e) {
e.preventDefault();
}
If you want to overwrite the element with key 0
function[0] = 42;
Otherwise:
function.insert(std::make_pair(0, 42));
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
If a header file contains a function, and is included by multiple .c
files, each .c
file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
It is technically possible to create static
functions in a header file for inclusion in multiple .c
files. Though this is generally not done because it breaks from the convention that code is found in .c
files and declarations are found in .h
files.
See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
app.controller('usersCtrl', function($scope, $http) {_x000D_
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
console.log(response.data)_x000D_
_x000D_
$scope.users = response.data;_x000D_
$scope.setKey = function (userId){_x000D_
alert(userId)_x000D_
if(localStorage){_x000D_
localStorage.setItem("userId", userId)_x000D_
} else {_x000D_
alert("No support of localStorage")_x000D_
return_x000D_
}_x000D_
}//function closed _x000D_
});_x000D_
});
_x000D_
#header{_x000D_
color: green;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>HyperCrud</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<!-- NAVBAR STARTS -->_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">HyperCrud</a>_x000D_
</div>_x000D_
<div id="navbar" class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="/">Home</a></li>_x000D_
<li><a href="/about/">About</a></li>_x000D_
<li><a href="/contact/">Contact</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="/qAlarm/details/">qAlarm »</a></li>_x000D_
<li><a href="/YtEdit/details/">YtEdit »</a></li>_x000D_
<li><a href="/GWeather/details/">GWeather »</a></li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li><a href="/WadStore/details/">WadStore »</a></li>_x000D_
<li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/login/">Login</a></li>_x000D_
<li><a href="/register/">Register</a></li>_x000D_
<li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
<!--NAVBAR ENDS-->_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm-12 col-md-12">_x000D_
<center>_x000D_
<h1 id="header"> Users </h1>_x000D_
</center>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row" >_x000D_
<!--ITERATING USERS LIST-->_x000D_
<div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
<div class="thumbnail">_x000D_
<center>_x000D_
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
<hr>_x000D_
</center>_x000D_
<div class="caption">_x000D_
<center>_x000D_
<h3>{{user.name}}</h3>_x000D_
<p>{{user.email}}</p>_x000D_
<p>+91 {{user.phone}}</p>_x000D_
<p>{{user.address.city}}</p>_x000D_
</center>_x000D_
</div>_x000D_
<div class="caption">_x000D_
<a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
<a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="col-sm-6 col-md-4">_x000D_
<div class="thumbnail">_x000D_
<a href="/regiser/">_x000D_
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!--ROW ENDS-->_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
I've written an article which contains a proof of concept, support classes and a test class which demonstrates how Super Type Tokens can be retrieved by your classes at runtime. In a nutshell, it allows you to delegate to alternative implementations depending on actual generic parameters passed by the caller. Example:
TimeSeries<Double>
delegates to a private inner class which uses double[]
TimeSeries<OHLC>
delegates to a private inner class which uses ArrayList<OHLC>
See:
Thanks
Richard Gomes - Blog
I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.
C# Websocket server :
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
namespace WebSocketServer
{
class Program
{
static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static void Main(string[] args)
{
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
serverSocket.Listen(1); //just one socket
serverSocket.BeginAccept(null, 0, OnAccept, null);
Console.Read();
}
private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
string headerResponse = "";
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
var i = client.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
// write received data to the console
Console.WriteLine(headerResponse);
Console.WriteLine("=====================");
}
if (client != null)
{
/* Handshaking and managing ClientSocket */
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1] // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0] // dGhlIHNhbXBsZSBub25jZQ==
.Trim();
// key should now equal dGhlIHNhbXBsZSBub25jZQ==
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
//+ "Sec-WebSocket-Version: 13" + newLine
;
client.Send(System.Text.Encoding.UTF8.GetBytes(response));
var i = client.Receive(buffer); // wait for client to send a message
string browserSent = GetDecodedData(buffer, i);
Console.WriteLine("BrowserSent: " + browserSent);
Console.WriteLine("=====================");
//now send message to client
client.Send(GetFrameFromString("This is message from server to client."));
System.Threading.Thread.Sleep(10000);//wait for message to be sent
}
}
catch (SocketException exception)
{
throw exception;
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}
public static T[] SubArray<T>(T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}
static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
//Needed to decode frame
public static string GetDecodedData(byte[] buffer, int length)
{
byte b = buffer[1];
int dataLength = 0;
int totalLength = 0;
int keyIndex = 0;
if (b - 128 <= 125)
{
dataLength = b - 128;
keyIndex = 2;
totalLength = dataLength + 6;
}
if (b - 128 == 126)
{
dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
keyIndex = 4;
totalLength = dataLength + 8;
}
if (b - 128 == 127)
{
dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
keyIndex = 10;
totalLength = dataLength + 14;
}
if (totalLength > length)
throw new Exception("The buffer length is small than the data length");
byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };
int dataIndex = keyIndex + 4;
int count = 0;
for (int i = dataIndex; i < totalLength; i++)
{
buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
count++;
}
return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
}
//function to create frames to send to client
/// <summary>
/// Enum for opcode types
/// </summary>
public enum EOpcodeType
{
/* Denotes a continuation code */
Fragment = 0,
/* Denotes a text code */
Text = 1,
/* Denotes a binary code */
Binary = 2,
/* Denotes a closed connection */
ClosedConnection = 8,
/* Denotes a ping*/
Ping = 9,
/* Denotes a pong */
Pong = 10
}
/// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
/// <param name="Message">The message to encode into the frame</param>
/// <param name="Opcode">The opcode of the frame</param>
/// <returns>Byte array in form of a websocket frame</returns>
public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
{
byte[] response;
byte[] bytesRaw = Encoding.Default.GetBytes(Message);
byte[] frame = new byte[10];
int indexStartRawData = -1;
int length = bytesRaw.Length;
frame[0] = (byte)(128 + (int)Opcode);
if (length <= 125)
{
frame[1] = (byte)length;
indexStartRawData = 2;
}
else if (length >= 126 && length <= 65535)
{
frame[1] = (byte)126;
frame[2] = (byte)((length >> 8) & 255);
frame[3] = (byte)(length & 255);
indexStartRawData = 4;
}
else
{
frame[1] = (byte)127;
frame[2] = (byte)((length >> 56) & 255);
frame[3] = (byte)((length >> 48) & 255);
frame[4] = (byte)((length >> 40) & 255);
frame[5] = (byte)((length >> 32) & 255);
frame[6] = (byte)((length >> 24) & 255);
frame[7] = (byte)((length >> 16) & 255);
frame[8] = (byte)((length >> 8) & 255);
frame[9] = (byte)(length & 255);
indexStartRawData = 10;
}
response = new byte[indexStartRawData + length];
int i, reponseIdx = 0;
//Add the frame bytes to the reponse
for (i = 0; i < indexStartRawData; i++)
{
response[reponseIdx] = frame[i];
reponseIdx++;
}
//Add the data bytes to the response
for (i = 0; i < length; i++)
{
response[reponseIdx] = bytesRaw[i];
reponseIdx++;
}
return response;
}
}
}
Client html and javascript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
socket.onopen = function() {_x000D_
// alert('handshake successfully established. May send data now...');_x000D_
socket.send("Hi there from browser.");_x000D_
};_x000D_
socket.onmessage = function (evt) {_x000D_
//alert("About to receive data");_x000D_
var received_msg = evt.data;_x000D_
alert("Message received = "+received_msg);_x000D_
};_x000D_
socket.onclose = function() {_x000D_
alert('connection closed');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
The getrows()
function below should get the specific rows you want.
For completeness, I have written down the full code in order to reproduce the output.
# Create SparkSession
from pyspark.sql import SparkSession
spark = SparkSession.builder.master('local').appName('scratch').getOrCreate()
# Create the dataframe
df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["letter", "name"])
# Function to get rows at `rownums`
def getrows(df, rownums=None):
return df.rdd.zipWithIndex().filter(lambda x: x[1] in rownums).map(lambda x: x[0])
# Get rows at positions 0 and 2.
getrows(df, rownums=[0, 2]).collect()
# Output:
#> [(Row(letter='a', name=1)), (Row(letter='c', name=3))]
You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.
For example socket.connect(otherAddress, timeout)
Or socket.setSoTimeout(timeout)
for setting a timeout on read()
operations.
See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
There are a lot of good options for your case here. Still you should considering using the POST body.
The query string is perfect for your example, but if you have something more complicated, e.g. an arbitrary long list of items or boolean conditionals, you might want to define the post as a document, that the client sends over POST.
This allows a more flexible description of the search, as well as avoids the Server URL length limit.
Please use the 4th parameter of moment.isBetween function (inclusivity). Example:
var startDate = moment("15/02/2013", "DD/MM/YYYY");
var endDate = moment("20/02/2013", "DD/MM/YYYY");
var testDate = moment("15/02/2013", "DD/MM/YYYY");
testDate.isBetween(startDate, endDate, 'days', true); // will return true
testDate.isBetween(startDate, endDate, 'days', false); // will return false
For anybody using logging.config.dictConfig
you can alter the requests library log level in the dictionary like this:
'loggers': {
'': {
'handlers': ['file'],
'level': level,
'propagate': False
},
'requests.packages.urllib3': {
'handlers': ['file'],
'level': logging.WARNING
}
}
GestureDetector is the best solution.
Here is an interesting alternative. In onTouchEvent on every ACTION_DOWN schedule a Runnable to run in 1 second. On every ACTION_UP or ACTION_MOVE, cancel scheduled Runnable. If cancelation happens less than 1s from ACTION_DOWN event, Runnable won't run.
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
Log.i("", "Long press!");
}
};
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView){
if(event.getAction() == MotionEvent.ACTION_DOWN)
handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP))
handler.removeCallbacks(mLongPressed);
return super.onTouchEvent(event, mapView);
}
Short answer is: You don't have any choice other than:
arr[4] = 5;
import numpy as np
def Haversine(lat1,lon1,lat2,lon2, **kwarg):
"""
This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is,
the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points
(ignoring any hills they fly over, of course!).
Haversine
formula: a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
c = 2 · atan2( va, v(1-a) )
d = R · c
where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!
"""
R = 6371.0088
lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
d = R * c
return round(d,4)
You can use scalar multiplication to modify each element in your vector.
> r <- 0:10
> r <- r * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
or
> r <- 0:10 * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
You can use extension methods to achive this.
public static ObjRemoverExtension {
public static void DeleteObj<T>(this T obj) where T: new()
{
obj = null;
}
}
And then you just import it in a desired source file and use on any object. GC will collect it. Like this:Car.DeleteObj()
EDIT Sorry didn't notice the method of class/all references part, but i'll leave it anyway.
In Java, integer literals are of type int by default. For some other types, you may suffix the literal with a case-insensitive letter like L
, D
, F
to specify a long, double, or float, respectively. Note it is common practice to use uppercase letters for better readability.
The Java Language Specification does not provide the same syntactic sugar for byte or short types. Instead, you may declare it as such using explicit casting:
byte foo = (byte)0;
short bar = (short)0;
In your setLongValue(100L)
method call, you don't have to necessarily include the L
suffix because in this case the int literal is automatically widened to a long. This is called widening primitive conversion in the Java Language Specification.
To have multiple Inline styles in React.
<div onClick={eleTemplate} style={{'width': '50%', textAlign: 'center'}}/>
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?
No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:
var someVar = options.filters.firstName; //Returns 'abc'
Or by iterating over them using the for ... in
loop:
for(var p in options.filters) {
var someVar = options.filters[p]; //Returns the property being iterated
}
function useAdress () {
var id = $("#choose-address-table").find(".nr:first").text();
alert (id);
$("#resultas").append(id); // Testing: append the contents of the td to a div
};
then on your button:
onclick="useAdress()"
If there is a huge amount of files on a network folder using the wildcard is questionable (speed, or command line arguments overflow).
I ended up with:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name \*.ext -print -quit)" ] ; then
echo Such file exists
fi
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}
I would try fossil scm and the Chisel hosting service
simple, self contained and easily interchangeable with git should you desire in future
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.
>>> hash("Look at me!!")
6941904779894686356
These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set
and dict
. In a list
, if you want to check if a value is in the list, with if x in values:
, Python needs to go through the whole list and compare x
with each value in the list values
. This can take a long time for a long list
. In a set
, Python keeps track of each hash, and when you type if x in values:
, Python will get the hash-value for x
, look that up in an internal structure and then only compare x
with the values that have the same hash as x
.
The same methodology is used for dictionary lookup. This makes lookup in set
and dict
very fast, while lookup in list
is slow. It also means you can have non-hashable objects in a list
, but not in a set
or as keys in a dict
. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.
Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>>
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299
This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.
Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.
Another option is using the map function of the purrr package.
library(purrr)
map(df,class)
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}
It is very simple just do the following steps:
<activity
android:name=".Test"
android:configChanges="orientation|screenSize"
android:screenOrientation="landscape" >
</activity>
This works for me :
Note: orientation depends on your requitement
I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info
on the console.
To get INFO
, WARNING
, and ERROR
messages in the console, the dictConfig
object can be used to create logging configuration for all logs (source):
from logging.config import dictConfig
from flask import Flask
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'INFO',
'handlers': ['wsgi']
}
})
app = Flask(__name__)
@app.route('/')
def index():
return "Hello from Flask's test environment"
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
stock an increment in the .data ()
of element scrolled, you will then be able to test number of times the scroll reached top.
Simple code that gives you the difference with multiple items if you want that:
a=[1,2,3,3,4]
b=[2,4]
tmp = copy.deepcopy(a)
for k in b:
if k in tmp:
tmp.remove(k)
print(tmp)
I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.
See below link for more details.
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900
If your date is text and you need to convert it then DATEVALUE
will do this:
As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root
for git rebase
:
"git rebase [-i] --root $tip
" can now be used to rewrite all the history leading to "$tip
" down to the root commit.
That new behavior was initially discussed here:
I personally think "
git rebase -i --root
" should be made to just work without requiring "--onto
" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.
The patch followed.
(original answer, February 2010)
As mentioned in the Git FAQ (and this SO question), the idea is:
git reset --hard
Rebase branch on top of changed commit, using:
git rebase --onto <tmp branch> <commit after changed> <branch>`
The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter
to make sure the content of that file does not contain in any commit the sensible information.
In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.
Comparing TCP with UDP, connection-less protocols like UDP assure speed, but not reliability of packet transmission. For example in video games typically don't need a reliable network but the speed is the most important and using UDP for games has the advantage of reducing network delay.
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
update for Angular 1.2+ (v1.2.6 at the time of this post):
.stuff-to-show {
position: relative;
height: 100px;
-webkit-transition: top linear 1.5s;
transition: top linear 1.5s;
top: 0;
}
.stuff-to-show.ng-hide {
top: -100px;
}
.stuff-to-show.ng-hide-add,
.stuff-to-show.ng-hide-remove {
display: block!important;
}
(plunker)
The issue is with
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ...
to be equivalent to export default ...
and exports.foo ...
to be equivalent to export const foo = ...
. That's not quite true though, or at least not how Babel does it.
ES6 default
exports are actually also named exports, except that default
is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports
object, just like foo
.
We can import the module in two ways: Either using CommonJS or using ES6 import
syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar
is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default
property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar
is converted to access .default
.
Try following code. It is working for me....
UPDATE TableOne
SET
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT TableTwo.id
FROM TableTwo
WHERE TableOne.id = TableTwo.id)
For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).
You can read more about History.js here: https://github.com/browserstate/history.js
For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
(Alt + Shift + X) , then M
to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations
An Ad-Hoc Query is a query that cannot be determined prior to the moment the query is issued. It is created in order to get information when need arises and it consists of dynamically constructed SQL which is usually constructed by desktop-resident query tools. An ad hoc query does not reside in the computer or the database manager but is dynamically created depending on the needs of the data user.
In SQL, an ad hoc query is a loosely typed command/query whose value depends upon some variable. Each time the command is executed, the result is different, depending on the value of the variable. It cannot be predetermined and usually comes under dynamic programming SQL query. An ad hoc query is short lived and is created at runtime.
I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.
Open Installation Details:
Choose Plug-ins tab => type org.eclipse.platform => check Version column.
You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse
For example, check out GitEye (Git GUI client)
Or checkout DBBeaver (DB manager):
In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).
Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.
For me the filename involved was appended with a querystring, which this function didn't like.
$path = 'path/to/my/file.js?v=2'
Solution was to chop that off first:
$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);
Since you don't know how many comma-delimited entries you can find, you may need to create a function with 'charindex' and 'substring' SQL Server functions. Values, as returned by the function could be used in a 'in' expression.
You function can be recursively invoked or you can create loop, searching for entries until no more entries are present in the string. Every call to the function uses the previous found index as the starting point of the next call. The first call starts at 0.
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
If you have resharper, remove all unused reference on your solution.
Other way to do it using jQuery CSS method:
$("#id").css({display: "none"});
$("#id").css({display: "block"});
My solution is: date('Y-m-d', time()-60*60*24*365);
You can make it more "readable" with defines:
define('ONE_SECOND', 1);
define('ONE_MINUTE', 60 * ONE_SECOND);
define('ONE_HOUR', 60 * ONE_MINUTE);
define('ONE_DAY', 24 * ONE_HOUR);
define('ONE_YEAR', 365 * ONE_DAY);
date('Y-m-d', time()-ONE_YEAR);
Do use this:
highp float rand(vec2 co)
{
highp float a = 12.9898;
highp float b = 78.233;
highp float c = 43758.5453;
highp float dt= dot(co.xy ,vec2(a,b));
highp float sn= mod(dt,3.14);
return fract(sin(sn) * c);
}
Don't use this:
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
You can find the explanation in Improvements to the canonical one-liner GLSL rand() for OpenGL ES 2.0
Don't use stream.stop()
, it's deprecated
Use stream.getTracks().forEach(track => track.stop())
Inspired by Nelson's and Chris' comments, I've found a way to workaround the same origin policy with a div
and an iframe
:
HTML:
<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>
CSS:
#div_iframe {
border-style: inset;
border-color: grey;
overflow: scroll;
height: 500px;
width: 90%
}
#frame {
width: 100%;
height: 1000%; /* 10x the div height to embrace the whole page */
}
Now suppose I want to skip the first 438 (vertical) pixels of the iframe page, by scrolling to that position.
JS solution:
document.getElementById('div_iframe').scrollTop = 438
JQuery solution:
$('#div_iframe').scrollTop(438)
CSS solution:
#frame { margin-top: -438px }
(Each solution alone is enough, and the effect of the CSS one is a little different since you can't scroll up to see the top of the iframed page.)
NSPredicate
is only available in iPhone 3.0.
You won't notice that until try to run on device.
adding mode:no-cors
can avoid cors issue in the api.
fetch(sign_in, {
mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
You can do like this
$q = $this->db->get()->row();
return $q->campaign_id;
Documentation : http://www.codeigniter.com/user_guide/database/results.html
In my case laravel 4.2 delete all rows ,but not truncate table
DB::table('your_table')->delete();
For a more modern solution check out https://stackoverflow.com/a/12514384/270274
Quote:
I'm sticking to the shared local data solution mentioned in the question using
localStorage
. It seems to be the best solution in terms of reliability, performance, and browser compatibility.
localStorage
is implemented in all modern browsers.The
storage
event fires when other tabs makes changes tolocalStorage
. This is quite handy for communication purposes.Reference:
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event
As of the Windows 10 "Anniversary" update (Version 1607), you can now run an Ubuntu subsystem from directly inside of Windows by enabling a feature called Developer mode.
To enable developer mode, go to Start > Settings then typing "Use developer features" in the search box to find the setting. On the left hand navigation, you will then see a tab titled For developers. From within this tab, you will see a radio box to enable Developer mode.
After developer mode is enabled, you will then be able to enable the Linux subsystem feature. To do so, go to Control Panel > Programs > Turn Windows features on or off > and check the box that says Windows Subsystem for Linux (Beta)
Now, rather than using Cygwin or a console emulator, you can run tmux through bash on the Ubuntu subsystem directly from Windows through the traditional apt package (sudo apt-get install tmux
).
In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this
mdataset.remove(holder.getadapterposition());
Try this:
created_at.strftime('%FT%T')
It's a time formatting function which provides you a way to present the string representation of the date. (http://ruby-doc.org/core-2.2.1/Time.html#method-i-strftime).
From APIdock:
%Y%m%d => 20071119 Calendar date (basic)
%F => 2007-11-19 Calendar date (extended)
%Y-%m => 2007-11 Calendar date, reduced accuracy, specific month
%Y => 2007 Calendar date, reduced accuracy, specific year
%C => 20 Calendar date, reduced accuracy, specific century
%Y%j => 2007323 Ordinal date (basic)
%Y-%j => 2007-323 Ordinal date (extended)
%GW%V%u => 2007W471 Week date (basic)
%G-W%V-%u => 2007-W47-1 Week date (extended)
%GW%V => 2007W47 Week date, reduced accuracy, specific week (basic)
%G-W%V => 2007-W47 Week date, reduced accuracy, specific week (extended)
%H%M%S => 083748 Local time (basic)
%T => 08:37:48 Local time (extended)
%H%M => 0837 Local time, reduced accuracy, specific minute (basic)
%H:%M => 08:37 Local time, reduced accuracy, specific minute (extended)
%H => 08 Local time, reduced accuracy, specific hour
%H%M%S,%L => 083748,000 Local time with decimal fraction, comma as decimal sign (basic)
%T,%L => 08:37:48,000 Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L => 083748.000 Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L => 08:37:48.000 Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z => 083748-0600 Local time and the difference from UTC (basic)
%T%:z => 08:37:48-06:00 Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z => 20071119T083748-0600 Date and time of day for calendar date (basic)
%FT%T%:z => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z => 2007323T083748-0600 Date and time of day for ordinal date (basic)
%Y-%jT%T%:z => 2007-323T08:37:48-06:00 Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600 Date and time of day for week date (basic)
%G-W%V-%uT%T%:z => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M => 20071119T0837 Calendar date and local time (basic)
%FT%R => 2007-11-19T08:37 Calendar date and local time (extended)
%Y%jT%H%MZ => 2007323T0837Z Ordinal date and UTC of day (basic)
%Y-%jT%RZ => 2007-323T08:37Z Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z => 2007W471T0837-0600 Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z => 2007-W47-1T08:37-06:00 Week date and local time and difference from UTC (extended)
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
Found under "app/code/core/Mage/Page/Block/Html/Header.php":
public function getWelcome()
{
if (empty($this->_data['welcome'])) {
if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
} else {
$this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
}
}
return $this->_data['welcome'];
}
So it looks like Mage::getSingleton('customer/session')->getCustomer()
will get your current logged in customer ;)
To get the currently logged in admin:
Mage::getSingleton('admin/session')->getUser();
I wrote a working CodePen example to demonstrate a great way of filtering numeric user input. The directive currently only allows positive integers, but the regex can easily be updated to support any desired numeric format.
My directive is easy to use:
<input type="text" ng-model="employee.age" valid-number />
The directive is very easy to understand:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace( /[^0-9]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
I want to emphasize that keeping model references out of the directive is important.
I hope you find this helpful.
Big thanks to Sean Christe and Chris Grimes for introducing me to the ngModelController
PyXML works well.
You didn't say what platform you're using, however if you're on Ubuntu you can get it with sudo apt-get install python-xml
. I'm sure other Linux distros have it as well.
If you're on a Mac, xpath is already installed but not immediately accessible. You can set PY_USE_XMLPLUS
in your environment or do it the Python way before you import xml.xpath:
if sys.platform.startswith('darwin'):
os.environ['PY_USE_XMLPLUS'] = '1'
In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are here.
Generally git pull
is enough, but I'm not sure what layout you have chosen (or has github chosen for you).
In a few words,
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
When a URL is like this http://stackoverflow.com?param1=value
You can get the param 1 by the following code:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: '',
templateUrl: './abc.html',
styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// get param
let param1 = this.route.snapshot.queryParams["param1"];
}
}
I answered something similar here: LaTeX breaking up too many words
I said:
you should set a hyphenation penalty somewhere in your preamble:
\hyphenpenalty=750
The value of 750 suited my needs for a two column layout on letter paper (8.5x11 in) with a 12 pt font. Adjust the value to suit your needs. The higher the number, the less hyphenation will occur. You may also want to have a look at the hyphenatpackage, it provides a bit more than just hyphenation penalty
When Spring loads your bean definitions, and has been configured to look for @Transactional
annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional
, Spring will create a TransactionInterceptor
, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor
(which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor
commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help?
AFAIK there isn't a way to do this. You could use a dashed border or perhaps increase the width of the border a bit, but just getting more spaced out dots is impossible with CSS.
On Linux and macOS you can run simple command to the shell:
subprocess.run('rm /tmp/*.bak', shell=True)
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
<style type="text/css">
div.inline { display:inline; }
</style>
<div class="inline">a</div>
<div class="inline">b</div>
<div class="inline">c</div>
You can use git stash - if something goes wrong, you can still revert from the stash. Similar to some other answer here, but this one also removes all unstaged files and also all unstaged deletes:
git add .
git stash
if you check that everything is OK, throw the stash away:
git stash drop
The answer from Bilal Maqsood with git clean
also worked for me, but with the stash I have more control - if I do sth accidentally, I can still get my changes back
UPDATE
I think there is 1 more change (don't know why this worked for me before):
git add . -A
instead of git add .
without the -A
the removed files will not be staged
Your Custom AuthenticationProvider class should be annotated with the following:
@Transactional
This will make sure the presence of the hibernate session there as well.
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Yes you can usually see what SOAP version is supported based on the WSDL.
Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.
JAXB is simple to use and is included in Java 6 SE. With JAXB, or other XML data binding such as Simple, you don't have to handle the XML yourself, most of the work is done by the library. The basic usage is to add annotation to your existing POJO. These annotation are then used to generate an XML Schema for you data and also when reading/writing your data from/to a file.
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
INTERNAL : Table is created First and Data is loaded later
EXTERNAL : Data is present and Table is created on top of it.
I just use contentsMargin
to fix the aspect ratio.
#pragma once
#include <QLabel>
class AspectRatioLabel : public QLabel
{
public:
explicit AspectRatioLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
~AspectRatioLabel();
public slots:
void setPixmap(const QPixmap& pm);
protected:
void resizeEvent(QResizeEvent* event) override;
private:
void updateMargins();
int pixmapWidth = 0;
int pixmapHeight = 0;
};
#include "AspectRatioLabel.h"
AspectRatioLabel::AspectRatioLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f)
{
}
AspectRatioLabel::~AspectRatioLabel()
{
}
void AspectRatioLabel::setPixmap(const QPixmap& pm)
{
pixmapWidth = pm.width();
pixmapHeight = pm.height();
updateMargins();
QLabel::setPixmap(pm);
}
void AspectRatioLabel::resizeEvent(QResizeEvent* event)
{
updateMargins();
QLabel::resizeEvent(event);
}
void AspectRatioLabel::updateMargins()
{
if (pixmapWidth <= 0 || pixmapHeight <= 0)
return;
int w = this->width();
int h = this->height();
if (w <= 0 || h <= 0)
return;
if (w * pixmapHeight > h * pixmapWidth)
{
int m = (w - (pixmapWidth * h / pixmapHeight)) / 2;
setContentsMargins(m, 0, m, 0);
}
else
{
int m = (h - (pixmapHeight * w / pixmapWidth)) / 2;
setContentsMargins(0, m, 0, m);
}
}
Works perfectly for me so far. You're welcome.
Use access modifier before the member definition:
private $connection;
As you cannot use function call in member definition in PHP, do it in constructor:
public function __construct() {
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
Under dependencyServices nothing of the above helped me, i ended up doing like below:
class Static_Toast_Android
{
private static Context _context
{
get { return Android.App.Application.Context; }
}
public static void StaticDisplayToast(string message)
{
Toast.MakeText(_context, message, ToastLength.Long).Show();
}
}
public class Toast_Android : IToast
{
public void DisplayToast(string message)
{
Static_Toast_Android.StaticDisplayToast(message);
}
}
I must use the "double-class" because an interface cannot be static. L-
This is a working script that will scroll the page to the anchor. To setup just give the anchor link an id that matches the name attribute of the anchor that you want to scroll to.
<script>
jQuery(document).ready(function ($){
$('a').click(function (){
var id = $(this).attr('id');
console.log(id);
if ( id == 'cet' || id == 'protein' ) {
$('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow');
}
});
});
</script>
You can do this with git rebase -i
, passing in the revision that you want to use as the 'root':
git rebase -i origin/master
will open an editor window showing all of the commits you have made after the last commit in origin/master
. You can reject commits, squash commits into a single commit, or edit previous commits.
There are a few resources that can probably explain this in a better way, and show some other examples:
http://book.git-scm.com/4_interactive_rebasing.html
and
http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
are the first two good pages I could find.
I had the same error and was able to run the app only through Xcode. react-native run-ios
did not work. To resolve the issue you need to remove the build
folder at YOUR_PROJECT/ios/build/
. After this you should be able to run your app through react-native run-ios
again. Hope this helps.
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
First thing, at the time the question was asked, uintptr_t
was not in C++. It's in C99, in <stdint.h>
, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>
, where again it is optional, and which refers to C99 for the definition.
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
Take this to mean what it says. It doesn't say anything about size.
uintptr_t
might be the same size as a void*
. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void*
is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t
which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.
It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827
Firefox is around the same value I think as well.
Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.
You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
The dict literal might be a tiny bit faster as its bytecode is shorter:
In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()
In [4]: dis.dis(a)
1 0 BUILD_MAP 0
3 RETURN_VALUE
In [5]: dis.dis(b)
1 0 LOAD_GLOBAL 0 (dict)
3 CALL_FUNCTION 0
6 RETURN_VALUE
Same applies to the list
vs []
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
con.Open();
sql = "select *from Table_Name;
cmd = new SqlCommand(sql, con);
SqlDataReader sdr = null;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
col.Add(sdr["Column_Name"].ToString());
}
sdr.Close();
textBox1.AutoCompleteCustomSource = col;
con.Close();
}
catch
{
}
}
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
When you want one element placed at the bottom other element you use this code in CSS. It is used for floats.
If you float content you can float left or right... so in a common layout you might have a left nav, a content div and a footer.
To ensure the footer stays below both of these floats (if you have floated left and right) then you put the footer as clear: both
.
This way it will stay below both floats.
(If you are only clearing left then you only really need to clear: left;
.)
Go through this tutorial:
Some Linux distributions such as Arch Linux have Node.js in their package repositories. On such systems it is better to use a standard package update procedure, such as pacman -Suy
or analogous apt-get
or yum
commands.
As of now (Nov 2016) EPEL7 offers a pretty recent version of Node.js (6.9.1 which is an up-to-date LTS version offered on the Node.js home page). So on CentOS 7 and derivatives you can just add EPEL repository by yum install epel-release
and yum install nodejs
.
CentOS 6/EPEL6 has 0.10.x which isn't supported upstream since Oct 2016.
The content is put after the HTTP headers. The format of an HTTP POST is to have the HTTP headers, followed by a blank line, followed by the request body. The POST variables are stored as key-value pairs in the body.
You can see this in the raw content of an HTTP Post, shown below:
POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
You can see this using a tool like Fiddler, which you can use to watch the raw HTTP request and response payloads being sent across the wire.
Check out this one, it's open source http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=EclipseHTMLEditor
Go to localhost/phpmyadmin and press enter key. Now select:
database --> table_name --->Structure --->Action ---> Primary -->click on Primary
Or about the best module I have found http://pypi.python.org/pypi/colorama
I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:
XmlDocument xd = new XmlDocument();
xd.LoadXml(xmlContent);
context.Response.Clear();
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
xd.Save(context.Response.Output);
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.
SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
AND CompletedDate in
(Select Max(CompletedDate) from HR_EmployeeTrainings B
where B.TrainingID = ET.TrainingID)
If you also want to match by AntiRecID you should include that in the subselect as well.
Return false if you click on .form_wrapper:
$('body').click(function() {
$('.form_wrapper').click(function(){
return false
});
$('.form_wrapper').hide();
});
//$('.form_wrapper').click(function(event){
// event.stopPropagation();
//});
The greps can be chained. For example:
tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"
The Android Asset Packaging Tool (aapt
) has become very strict in its latest release and is now used for all Android versions. The aapt-error you're getting is generated because it no longer allows non-positional format specifiers.
Here are a few ideas how you can include the %-symbol in your resource strings.
If you don't need any format specifiers or substitutions in your string you can simply make use of the formatted
attribute and set it to false
:
<string formatted="false">%a + %a == 2%a</string>
In this case the string is not used as a format string for the Formatter
so you don't have to escape your %-symbols. The resulting string is "%a + %a == 2%a".
If you omit the formatted="false"
attribute, the string is used as a format string and you have to escape the %-symbols. This is correctly done with double-%:
<string>%%a + %%a == 2%%a</string>
Now aapt
gives you no errors but depending on how you use it, the resulting string can be "%%a + %%a == 2%%a" if a Formatter
is invoked without any format arguments:
Resources res = context.getResources();
String s1 = res.getString(R.string.str);
// s1 == "%%a + %%a == 2%%a"
String s2 = res.getString(R.string.str, null);
// s2 == "%a + %a == 2%a"
Without any xml and code it is difficult to say what exactly your problem is but hopefully this helps you understand the mechanisms a little better.
You can also use:
img{
filter:grayscale(100%);
}
img:hover{
filter:none;
}
You can filter your elment from all hovered elements. Problematic code:
element.filter(':hover')
Save code:
jQuery(':hover').filter(element)
To return boolean:
jQuery(':hover').filter(element).length===0
You could use Synonyms part in the database.
Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply.
It's usually based on significant figures of both the exponent and significand in base 2, not base 10. From what I can tell in the C99 standard, however, there is no specified precision for floats and doubles (other than the fact that 1 and 1 + 1E-5
/ 1 + 1E-7
are distinguishable [float
and double
repsectively]). However, the number of significant figures is left to the implementer (as well as which base they use internally, so in other words, an implementation could decide to make it based on 18 digits of precision in base 3). [1]
If you need to know these values, the constants FLT_RADIX
and FLT_MANT_DIG
(and DBL_MANT_DIG
/ LDBL_MANT_DIG
) are defined in float.h.
The reason it's called a double
is because the number of bytes used to store it is double the number of a float (but this includes both the exponent and significand). The IEEE 754 standard (used by most compilers) allocate relatively more bits for the significand than the exponent (23 to 9 for float
vs. 52 to 12 for double
), which is why the precision is more than doubled.
1: Section 5.2.4.2.2 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf )
My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:
We can also use -
$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth') <!-- Width -->
This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));
Meaning For dummies:
IAAS (Infrastructure As A Service) :
The base layer
Deals with Virtual Machines, Storage (Hard Disks), Servers, Network, Load Balancers etc
PAAS (Platform As A Service) :
A layer on top of IAAS
Runtimes (like java runtimes), Databases (like mySql, Oracle), Web Servers (tomcat etc)
SAAS (Software As A Service) :
A layer on top on PAAS
Applications like email (Gmail, Yahoo mail etc), Social Networking sites (Facebook etc)
To quickly relate consider the below Google's offerings:
IAAS : Google Compute Engine (One can develop programs to be run on high performing google's computing infrastructure)
PAAS : Google App Engine (One can develop applications and let them execute on top of Google app engine which take care of the execution)
SAAS : Gmail, Google+ etc (One can use email services and extend email/google+ based applications to form newer applications)
Popularity
Company Wise Popularity
Cloud computing is dominated by
Most of the popularity around these services owe to the reputation of the company and the amount of investments being made by these companies around the cloud space.
Type of Service Wise Popularity
A note to this old question:
My reset.css had set border-spacing: 0
, causing the corners to get cut off. I had to set it to 3px
for my radius to work properly (value will depend on the radius in question).
just do this:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
a * b
I know it has been a long time since the original question was posted. But i think for slow ones like me a bit of explanation of @Heisenberg's answer would help.
Declare two variable in the adapter class as
private int mExpandedPosition= -1;
private RecyclerView recyclerView = null;
Then in onBindViewHolder following as given in the original answer.
// This line checks if the item displayed on screen
// was expanded or not (Remembering the fact that Recycler View )
// reuses views so onBindViewHolder will be called for all
// items visible on screen.
final boolean isExpanded = position==mExpandedPosition;
//This line hides or shows the layout in question
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
// I do not know what the heck this is :)
holder.itemView.setActivated(isExpanded);
// Click event for each item (itemView is an in-built variable of holder class)
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if the clicked item is already expaned then return -1
//else return the position (this works with notifyDatasetchanged )
mExpandedPosition = isExpanded ? -1:position;
// fancy animations can skip if like
TransitionManager.beginDelayedTransition(recyclerView);
//This will call the onBindViewHolder for all the itemViews on Screen
notifyDataSetChanged();
}
});
And lastly to get the recyclerView object in the adapter override
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
}
Hope this Helps.
You can use sets:
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
resultList= list(set(first_list) | set(second_list))
print(resultList)
# Results in : resultList = [1,2,5,7,9]
Head First SQL is a great introduction.
Generic command would be
find /path/to/files -name '<search>*' -exec bash -c 'mv $0 ${0/<search>/<replace>}' {} \;
where <search>
and <replace>
should be replaced with your source and target respectively.
As a more specific example tailored to your problem (should be run from the same folder where your files are), the above command would look like:
find . -name 'gfh*' -exec bash -c 'mv $0 ${0/gfh/jkl}' {} \;
For a "dry run" add echo
before mv
, so that you'd see what commands are generated:
find . -name 'gfh*' -exec bash -c 'echo mv $0 ${0/gfh/jkl}' {} \;