No there is no built-in support for this.
You have to make your own "INIFileReader". Maybe something like this?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
Edit: Updated to reflect Paul's comment.
You can do this using del
and the /S
flag (to tell it to recurse all files from all subdirectories):
del /S C:\Path\to\directory\*
The RD command can also be used. Recursively delete quietly without a prompt:
@RD /S /Q %VAR_PATH%
In my case it was the security constraints defined in web.xml. Make sure they have the same roles you use in your tomcat-users.xml
file.
For example, this is one of the out-of-the-box tags and will work with the standard tomcat-users.xml.
<security-constraint>
<web-resource-collection>
<web-resource-name>HTML Manager interface (for humans)</web-resource-name>
<url-pattern>/html/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>manager-gui</role-name>
</auth-constraint>
</security-constraint>
In my case an admin had used a different role-name which prevented me from accessing the manager.
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
That loads all the DLLs present in your executable's folder.
In my case I was trying to use Reflection
to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.
EDIT: I timed it, and it only seems to load them the first time.
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
stopwatch.Restart();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
Output: 34 0 0 0
So one could potentially run that code before any Reflection searches just in case.
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
you can use both use array like :
$array = array('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE' );
and direct assign like:
$this->db->where('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE');
I wish help you.
Here goes what O'reilly Enterprise JavaBeans, 3.0 says
JDBC has special types for these very large objects. The java.sql.Blob type represents binary data, and java.sql.Clob represents character data.
Here goes PostgreSQLDialect source code
public PostgreSQLDialect() {
super();
...
registerColumnType(Types.VARBINARY, "bytea");
/**
* Notice it maps java.sql.Types.BLOB as oid
*/
registerColumnType(Types.BLOB, "oid");
}
So what you can do
Override PostgreSQLDialect as follows
public class CustomPostgreSQLDialect extends PostgreSQLDialect {
public CustomPostgreSQLDialect() {
super();
registerColumnType(Types.BLOB, "bytea");
}
}
Now just define your custom dialect
<property name="hibernate.dialect" value="br.com.ar.dialect.CustomPostgreSQLDialect"/>
And use your portable JPA @Lob annotation
@Lob
public byte[] getValueBuffer() {
UPDATE
Here has been extracted here
I have an application running in hibernate 3.3.2 and the applications works fine, with all blob fields using oid (byte[] in java)
...
Migrating to hibernate 3.5 all blob fields not work anymore, and the server log shows: ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: column is of type oid but expression is of type bytea
which can be explained here
This generaly is not bug in PG JDBC, but change of default implementation of Hibernate in 3.5 version. In my situation setting compatible property on connection did not helped.
...
Much more this what I saw in 3.5 - beta 2, and i do not know if this was fixed is Hibernate - without @Type annotation - will auto-create column of type oid, but will try to read this as bytea
Interesting is because when he maps Types.BOLB as bytea (See CustomPostgreSQLDialect) He get
Could not execute JDBC batch update
when inserting or updating
Please see my answer below, inspired by answers above but a bit more detailed...
// Get The Json Response (With Try Catch)
try {
String s = null;
if (response.body() != null) {
s = response.body().string();
// Convert Response Into Json Object (With Try Catch)
JSONObject json = null;
try {
json = new JSONObject(s);
// Extract The User Id From Json Object (With Try Catch)
String stringToExtract = null;
try {
stringToExtract = json.getString("NeededString");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line. Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the CSS
and HTML
code from that example:
.centered-and-cropped { object-fit: cover }
_x000D_
<h1>original</h1>_x000D_
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">_x000D_
_x000D_
<h1>object-fit: cover</h1>_x000D_
<img class="centered-and-cropped" width="200" height="200" _x000D_
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
_x000D_
The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.
Isnull() syntax is built in for this kind of thing.
declare @Int int = null;
declare @Values table ( id int, def varchar(8) )
insert into @Values values (8, 'I am 8');
-- fails
select *
from @Values
where id = @Int
-- works fine
select *
from @Values
where id = isnull(@Int, 8);
For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.
declare @Int int = null;
declare @Values table ( id int, def varchar(16) )
insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');
select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')
I use git from cygwin on Windows, the git apply
solution doesn't work for me. Here is my solution, run chmod
on every file to reset its permissions.
#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
eval $c
done
unset IFS
These solutions Failed in my case with Relative Layout and If KeyBoard is Open
android:scrollbars="none"
&
android:scrollbarStyle="insideOverlay"
also not working.
toolbar is gone, my done button is gone.
This one is Working for me
myScrollView.setVerticalScrollBarEnabled(false);
As duplicate comment keys are removed running package.json tools (npm, yarn, etc.), I came to using a hashed version which allows for better reading as multiple lines and keys like:
"//": {
"alpaca": "we use the bootstrap version",
"eonasdan-bootstrap-datetimepicker": "instead of bootstrap-datetimepicker",
"moment-with-locales": "is part of moment"
},
which is 'valid' according to my IDE as a root key, but within dependencies
it complains expecting a string value.
Another simple example:
Search: style="(.+?)"
Replace: css={css`$1`}
Useful for converting HTML to JSX with emotion/css!
I suppose https://get-ytt.io/ would be an acceptable solution to your problem
Make a state machine that operates on one basic principle: is the current character a number.
Optimizations are possible.
This is a simple solution with the function aggregate
:
aggregate(order_no ~ name, myvec, function(x) length(unique(x)))
You could also import all operators this way:
import {Observable} from 'rxjs/Rx';
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC
tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => '[email protected]'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
Do you mean to property files located in src/main/resources
? Then you should exclude them using the maven-resource-plugin. See the following page for details:
http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html
The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):
Using Array.from, Array.prototype.forEach(), and arrow functions:
Iterate over the keys:
Array.from(myMap.keys()).forEach(key => console.log(key));
Iterate over the values:
Array.from(myMap.values()).forEach(value => console.log(value));
Iterate over the entries:
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
In production code I would simply write
1 <= x && x <= 100
This is easy to understand and very readable.
Starting with C#9.0 we can write
x is >= 1 and <= 100 // Note that we must write x only once.
// "is" introduces a pattern matching expression.
// "and" is part of the pattern matching unlike the logical "&&".
// With "&&" we would have to write: x is >= 1 && x is <= 100
Here is a clever method that reduces the number of comparisons from two to one by using some math. The idea is that one of the two factors becomes negative if the number lies outside of the range and zero if the number is equal to one of the bounds:
If the bounds are inclusive:
(x - 1) * (100 - x) >= 0
or
(x - min) * (max - x) >= 0
If the bounds are exclusive:
(x - 1) * (100 - x) > 0
or
(x - min) * (max - x) > 0
Use dataType:"json"
for json
data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
Use Array.prototype.keys
:
for (const index of [1, 2, 3, 4, 5].keys()) {_x000D_
console.log(index);_x000D_
}
_x000D_
If you want to access both the key and the value, you can use Array.prototype.entries()
with destructuring:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {_x000D_
console.log(index, value);_x000D_
}
_x000D_
Say you have a download function to download a file from network, and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
// How to use it.
downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
})
Hope it helps.
Add some css either in the head or in a external document. asp:TextBox are rendered as input :
input {
width:100%;
}
Your html should look like : http://jsfiddle.net/c5WXA/
Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.
.divClass input {
width:100%;
}
The InstallUtil.exe
tool is simply a wrapper around some reflection calls against the installer component(s) in your service. As such, it really doesn't do much but exercise the functionality these installer components provide. Marc Gravell's solution simply provides a means to do this from the command line so that you no longer have to rely on having InstallUtil.exe
on the target machine.
Here's my step-by-step that based on Marc Gravell's solution.
How to make a .NET Windows Service start right after the installation?
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
As some of our friends suggested, I removed previous two answers and I consolidate here.
This gives you the clear understanding.
What the general algorithm is....
Algorithm:
solve(n,s,i,d) //solve n discs from s to d, s-source i-intermediate d-destination
{
if(n==0)return;
solve(n-1,s,d,i); // solve n-1 discs from s to i Note:recursive call, not just move
move from s to d; // after moving n-1 discs from s to d, a left disc in s is moved to d
solve(n-1,i,s,d); // we have left n-1 disc in 'i', so bringing it to from i to d (recursive call)
}
here is the working example Click here
The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.
How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
dim mydate = from cv in mydata.t1s
select cv.date1 asc
datetime mindata = mydate[0];
It will group by the column position you put after the group by clause.
for example if you run 'SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1
'
it will group by SALESMAN_NAME
.
One risk on doing that is if you run 'Select *
' and for some reason you recreate the table with columns on a different order, it will give you a different result than you would expect.
For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access. This is done with the "enable less secure apps" and also using this link: https://accounts.google.com/b/0/DisplayUnlockCaptcha
Because linux
is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.
There are a lot of such predefined macros. With GCC, you can use:
cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c
to get a list of macros. (I've not managed to persuade GCC to accept /dev/null
directly, but
the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:
#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3
That's 236 macros from an empty file. When I added #include <stdio.h>
to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.
In general, to provide your own formula you should use arguments x
and y
that will correspond to values you provided in ggplot()
- in this case x
will be interpreted as x.plot
and y
as y.plot
. You can find more information about smoothing methods and formula via the help page of function stat_smooth()
as it is the default stat used by geom_smooth()
.
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data=mean_cl_normal) +
geom_smooth(method='lm', formula= y~x)
If you are using the same x and y values that you supplied in the ggplot()
call and need to plot the linear regression line then you don't need to use the formula inside geom_smooth()
, just supply the method="lm"
.
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data= mean_cl_normal) +
geom_smooth(method='lm')
var objectA = {}
is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.
we can do this like
.left {
float:left;
margin:3px;
}
<div class="left">foo</div>
<div class="left">bar</div>
<div class="left">baz</div>
you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".
Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.
If you use Spring you can:
1) create a log4j configuration file, e.g. "/WEB-INF/classes/log4j-myapp.properties" DO NOT name it "log4j.properties"
Example:
log4j.rootLogger=ERROR, stdout, rollingFile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=${myWebapp-instance-root}/WEB-INF/logs/application.log
log4j.appender.rollingFile.MaxFileSize=512KB
log4j.appender.rollingFile.MaxBackupIndex=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.rollingFile.Encoding=UTF-8
We'll define "myWebapp-instance-root" later on point (3)
2) Specify config location in web.xml:
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j-myapp.properties</param-value>
</context-param>
3) Specify a unique variable name for your webapp's root, e.g. "myWebapp-instance-root"
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myWebapp-instance-root</param-value>
</context-param>
4) Add a Log4jConfigListener:
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
If you choose a different name, remember to change it in log4j-myapp.properties, too.
See my article (Italian only... but it should be understandable): http://www.megadix.it/content/configurare-path-relativi-log4j-utilizzando-spring
UPDATE (2009/08/01) I've translated my article to English: http://www.megadix.it/node/136
I learned a new idiom for this today while watching Raymond Hettinger's Transforming Code into Beautiful, Idiomatic Python:
import functools
with open(filename) as f:
f_read_ch = functools.partial(f.read, 1)
for ch in iter(f_read_ch, ''):
print 'Read a character:', repr(ch)
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized
if you want it to be thread safe.
In order to understand the use of curly braces in import
statements, first, you have to understand the concept of destructuring introduced in ES6
Object destructuring
var bodyBuilder = {
firstname: 'Kai',
lastname: 'Greene',
nickname: 'The Predator'
};
var {firstname, lastname} = bodyBuilder;
console.log(firstname, lastname); // Kai Greene
firstname = 'Morgan';
lastname = 'Aste';
console.log(firstname, lastname); // Morgan Aste
Array destructuring
var [firstGame] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(firstGame); // Gran Turismo
Using list matching
var [,secondGame] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(secondGame); // Burnout
Using the spread operator
var [firstGame, ...rest] = ['Gran Turismo', 'Burnout', 'GTA'];
console.log(firstGame);// Gran Turismo
console.log(rest);// ['Burnout', 'GTA'];
Now that we've got that out of our way, in ES6 you can export multiple modules. You can then make use of object destructuring like below.
Let's assume you have a module called module.js
export const printFirstname(firstname) => console.log(firstname);
export const printLastname(lastname) => console.log(lastname);
You would like to import the exported functions into index.js
;
import {printFirstname, printLastname} from './module.js'
printFirstname('Taylor');
printLastname('Swift');
You can also use different variable names like so
import {printFirstname as pFname, printLastname as pLname} from './module.js'
pFname('Taylor');
pLanme('Swift');
Anyone working on Jupyter Notebook to print DataFrame without index column, this worked for me:
display(table.hide_index())
Here is the function for to check is String is Integer or not ?
public static boolean isStringInteger(String number ){
try{
Integer.parseInt(number);
}catch(Exception e ){
return false;
}
return true;
}
Use the -j
option:
-j Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current path).
Beware: some phones have 2 sdcards , an internal fixed one and a removable card. You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? ) When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" . Suppose I want to open a text-file "MyBooks.txt" I would use something as :
String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
File file = new File(fname);...etc...
I disagree with this kind of path
GET /companies/{companyId}/departments
If you want to get departments, I think it's better to use a /departments resource
GET /departments?companyId=123
I suppose you have a companies
table and a departments
table then classes to map them in the programming language you use. I also assume that departments could be attached to other entities than companies, so a /departments resource is straightforward, it's convenient to have resources mapped to tables and also you don't need as many endpoints since you can reuse
GET /departments?companyId=123
for any kind of search, for instance
GET /departments?name=xxx
GET /departments?companyId=123&name=xxx
etc.
If you want to create a department, the
POST /departments
resource should be used and the request body should contain the company ID (if the department can be linked to only one company).
You just missed an initialization step I think.
You can see what fonts you have available with the command windowsFonts()
. For example mine looks like this when I started looking at this:
> windowsFonts()
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
After intalling the package extraFont and running font_import
like this (it took like 5 minutes):
library(extrafont)
font_import()
loadfonts(device = "win")
I had many more available - arguable too many, certainly too many to list here.
Then I tried your code:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="Comic Sans MS"))
print(a)
yielding this:
You can find the name of a font you need for the family
parameter of element_text
with the following code snippet:
> names(wf[wf=="TT Times New Roman"])
[1] "serif"
And then:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="serif"))
print(a)
Location:
C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe
You can see here http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx
See the remarks and example section there.
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
First call startactivity()
then use finish()
You can also use Laravel helper which I'm using. Just create Helpers folder under App folder then add the following code:
namespace App\Helpers;
Use SettingModel;
class SiteHelper
{
public static function settings()
{
if(null !== session('settings')){
$settings = session('settings');
}else{
$settings = SettingModel::all();
session(['settings' => $settings]);
}
return $settings;
}
}
then add it on you config > app.php under alliases
'aliases' => [
....
'Site' => App\Helpers\SiteHelper::class,
]
1. To Use in Controller
use Site;
class SettingsController extends Controller
{
public function index()
{
$settings = Site::settings();
return $settings;
}
}
2. To Use in View:
Site::settings()
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
you must check this selection must be single selection and editing must be no seleciton during edition and you change setting in uttableviewcell properties also you edit in table view cell style must be custom and identifier must be Rid and section is none
I think the error because the elements are undefined ,so you need to add window.onload
event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
yourElement.setAttribute("style", "background-color:red; font-size:2em;");
Or you could write the element as pure HTML and use .innerHTML = [raw html code]
... that's very ugly though.
In answer to your first question, first you use var myElement = createElement(...);
, then you do document.body.appendChild(myElement);
.
May be you can just use the split method to eliminate the '/myapp' for example:
string[] uris=request.getRequestURI().split("/");
string uri="/"+uri[1]+"/"+uris[2];
Synchronizing with threads. 1) NEVER use synchronized(this) in a thread it doesn't work. Synchronizing with (this) uses the current thread as the locking thread object. Since each thread is independent of other threads, there is NO coordination of synchronization. 2) Tests of code show that in Java 1.6 on a Mac the method synchronization does not work. 3) synchronized(lockObj) where lockObj is a common shared object of all threads synchronizing on it will work. 4) ReenterantLock.lock() and .unlock() work. See Java tutorials for this.
The following code shows these points. It also contains the thread-safe Vector which would be substituted for the ArrayList, to show that many threads adding to a Vector do not lose any information, while the same with an ArrayList can lose information. 0) Current code shows loss of information due to race conditions A) Comment the current labeled A line, and uncomment the A line above it, then run, method loses data but it shouldn't. B) Reverse step A, uncomment B and // end block }. Then run to see results no loss of data C) Comment out B, uncomment C. Run, see synchronizing on (this) loses data, as expected. Don't have time to complete all the variations, hope this helps. If synchronizing on (this), or the method synchronization works, please state what version of Java and OS you tested. Thank you.
import java.util.*;
/** RaceCondition - Shows that when multiple threads compete for resources
thread one may grab the resource expecting to update a particular
area but is removed from the CPU before finishing. Thread one still
points to that resource. Then thread two grabs that resource and
completes the update. Then thread one gets to complete the update,
which over writes thread two's work.
DEMO: 1) Run as is - see missing counts from race condition, Run severa times, values change
2) Uncomment "synchronized(countLock){ }" - see counts work
Synchronized creates a lock on that block of code, no other threads can
execute code within a block that another thread has a lock.
3) Comment ArrayList, unComment Vector - See no loss in collection
Vectors work like ArrayList, but Vectors are "Thread Safe"
May use this code as long as attribution to the author remains intact.
/mf
*/
public class RaceCondition {
private ArrayList<Integer> raceList = new ArrayList<Integer>(); // simple add(#)
// private Vector<Integer> raceList = new Vector<Integer>(); // simple add(#)
private String countLock="lock"; // Object use for locking the raceCount
private int raceCount = 0; // simple add 1 to this counter
private int MAX = 10000; // Do this 10,000 times
private int NUM_THREADS = 100; // Create 100 threads
public static void main(String [] args) {
new RaceCondition();
}
public RaceCondition() {
ArrayList<Thread> arT = new ArrayList<Thread>();
// Create thread objects, add them to an array list
for( int i=0; i<NUM_THREADS; i++){
Thread rt = new RaceThread( ); // i );
arT.add( rt );
}
// Start all object at once.
for( Thread rt : arT ){
rt.start();
}
// Wait for all threads to finish before we can print totals created by threads
for( int i=0; i<NUM_THREADS; i++){
try { arT.get(i).join(); }
catch( InterruptedException ie ) { System.out.println("Interrupted thread "+i); }
}
// All threads finished, print the summary information.
// (Try to print this informaiton without the join loop above)
System.out.printf("\nRace condition, should have %,d. Really have %,d in array, and count of %,d.\n",
MAX*NUM_THREADS, raceList.size(), raceCount );
System.out.printf("Array lost %,d. Count lost %,d\n",
MAX*NUM_THREADS-raceList.size(), MAX*NUM_THREADS-raceCount );
} // end RaceCondition constructor
class RaceThread extends Thread {
public void run() {
for ( int i=0; i<MAX; i++){
try {
update( i );
} // These catches show when one thread steps on another's values
catch( ArrayIndexOutOfBoundsException ai ){ System.out.print("A"); }
catch( OutOfMemoryError oome ) { System.out.print("O"); }
}
}
// so we don't lose counts, need to synchronize on some object, not primitive
// Created "countLock" to show how this can work.
// Comment out the synchronized and ending {, see that we lose counts.
// public synchronized void update(int i){ // use A
public void update(int i){ // remove this when adding A
// synchronized(countLock){ // or B
// synchronized(this){ // or C
raceCount = raceCount + 1;
raceList.add( i ); // use Vector
// } // end block for B or C
} // end update
} // end RaceThread inner class
} // end RaceCondition outter class
If your app is AndroidX, This response may apply to your problem:
npm install --save-dev jetifier
npx jetify (may take a while)
npx react-native run-android
For SQL Server 2012, or later, an easier solution is to use FORMAT ()
Documentation.
EG:
SELECT Format(1234567.8, '##,##0')
Results in: 1,234,568
private void OnDropDownClosed(object sender, EventArgs e)
{
if (combobox.SelectedItem == null) return;
// Do actions
}
You can try this:
db.Account.find().sort("UserName")
db.Account.find().sort("UserName",pymongo.ASCENDING)
db.Account.find().sort("UserName",pymongo.DESCENDING)
Get the .column
parent of the this
element, get its previous sibling, then find any input there:
$(this).closest(".column").prev().find("input:first").val();
Try this for including submodules in git repository.
git clone -b <branch_name> --recursive <remote> <directory>
or
git clone --recurse-submodules
(Ctrl+H) -> Find and Replace window opens -> Find what "0" ,Replace with " "(leave it blank )-> click options tick match entire cell contents -> click "Replace All" button .
Seems like you need to strip the URL from the URL, so you can do it in a following way:
request.getRequestURL().toString().replace(request.getRequestURI(), "")
<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>
--
$('#vehicleChkBox').change(function(){
if(this.checked)
$('#vehicleChkBox').val('TRUE');
else
$('#vehicleChkBox').val('False');
});
Angular’s keyvalue
pipe can be used, but unfortunately it sorts by key. Maps already have an order and it would be great to be able to keep it!
We can define out own pipe mapkeyvalue
which preserves the order of items in the map:
import { Pipe, PipeTransform } from '@angular/core';
// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();
@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
const existing = cache.get(input);
if (existing !== undefined) {
return existing;
}
const iterable = Array.from(input, ([key, value]) => ({ key, value }));
cache.set(input, iterable);
return iterable;
}
}
It can be used like so:
<mat-select>
<mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
{{ choice.value }}
</mat-option>
</mat-select>
Try this one:
SELECT t1.* FROM Table1 t1
JOIN
(
SELECT category, MAX(date) AS MAXDATE
FROM Table1
GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE
Since SELECT INTO assumes that a single row will be returned, you can use a statement of the form:
SELECT MAX(column)
INTO var
FROM table
WHERE conditions;
IF var IS NOT NULL
THEN ...
The SELECT will give you the value if one is available, and a value of NULL instead of a NO_DATA_FOUND exception. The overhead introduced by MAX() will be minimal-to-zero since the result set contains a single row. It also has the advantage of being compact relative to a cursor-based solution, and not being vulnerable to concurrency issues like the two-step solution in the original post.
The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.
Arguably the most common way to select the values is to use Boolean indexing.
With this method, you find out where column 'a' is equal to 1
and then sum the corresponding rows of column 'b'. You can use loc
to handle the indexing of rows and columns:
>>> df.loc[df['a'] == 1, 'b'].sum()
15
The Boolean indexing can be extended to other columns. For example if df
also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:
df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()
Another way to select the data is to use query
to filter the rows you're interested in, select column 'b' and then sum:
>>> df.query("a == 1")['b'].sum()
15
Again, the method can be extended to make more complicated selections of the data:
df.query("a == 1 and c == 2")['b'].sum()
Note this is a little more concise than the Boolean indexing approach.
The alternative approach is to use groupby
to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:
>>> df.groupby('a')['b'].sum()[1]
15
This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a
:
>>> df.groupby('a')['b'].sum()
a
1 15
2 8
The code date.to_time.to_i
should work fine. The Rails console session below shows an example:
>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009
Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".
If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.
As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".
If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.
For streaming protocols such as TCP, you can pretty much set your buffer to any size. That said, common values that are powers of 2 such as 4096 or 8192 are recommended.
If there is more data then what your buffer, it will simply be saved in the kernel for your next call to recv
.
Yes, you can keep growing your buffer. You can do a recv into the middle of the buffer starting at offset idx
, you would do:
recv(socket, recv_buffer + idx, recv_buffer_size - idx, 0);
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
What you really need to do, especially if you only use JavaScript to do the Ajax request, is an internal proxy who takes your query and send it through to the remote server.
First in your JavaScript, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async:false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query but on the server side and after that, it should works fine.
If l
is your list and X
is your value:
for i in range(len(l) + 1):
print l[:i] + [X] + l[i:]
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
this.getClass().getResourceAsStream("/SomeTextFile.txt");
Here is another way...
It adds "others" to the enum definition of the column "rtipo" of the table "firmas".
set @new_enum = 'others';
set @table_name = 'firmas';
set @column_name = 'rtipo';
select column_type into @tmp from information_schema.columns
where table_name = @table_name and column_name=@column_name;
set @tmp = insert(@tmp, instr(@tmp,')'), 0, concat(',\'', @new_enum, '\'') );
set @tmp = concat('alter table ', @table_name, ' modify ', @column_name, ' ', @tmp);
prepare stmt from @tmp;
execute stmt;
deallocate prepare stmt;
Unless I am misunderstanding you, this could be as easy as inspecting (F12) the icon on the page to reveal its .svg source file path, going to that path directly (Example), and then viewing the page source code with Control+u. Then just save that code.
I would recommend reading this post. There are tons of ways to use existing HttpResponse as suggested, but if you want to take advantage of Web Api 2, then look at using some of the built-in IHttpActionResult options such as
return Ok()
or
return NotFound()
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
"
git fetch
" (hence "git pull
" as well) learned to check "fetch.prune
" and "remote.*.prune
" configuration variables and to behave as if the "--prune
" command line option was given.
That means that, if you set remote.origin.prune to true:
git config remote.origin.prune true
Any git fetch
or git pull
will automatically prune.
Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename
misbehave.
See "How do I rename a git remote?".
See more at commit 737c5a9:
Without "
git fetch --prune
", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune
".To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "
fetch.prune
" and "remote.<name>.prune
":
- "
fetch.prune
" allows to enable prune for all fetch operations.- "
remote.<name>.prune
" allows to change the behaviour per remote.The latter will naturally override the former, and the
--[no-]prune
option from the command line will override the configured default.Since
--prune
is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.
Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)
Older MySQL versions this is enough:
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice`) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
Nowdays, if you use MariaDB the subquery should be limited.
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice` LIMIT 18446744073709551615) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
I changed the Office365 password and then tried to send a test email and it worked like a charm for me.
I used the front end (database mail option) and settings as smtp.office365.com port number 587 and checked the secure connection option. use basic authentication and store the credentials. Hope this turns out useful for someone.
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
I had colorama installed via pip and I was getting "ImportError: No module named colorama"
So I searched with "find", found the absolute path and added it in the script like this:
import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama
And it worked.
In your code you are querying for the payment
element in default namespace, but in the XML response it is declared as in http://apilistener.envoyservices.com
namespace.
So, you are missing a namespace declaration:
$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');
Now you can use the envoy
namespace prefix in your xpath query:
xpath('//envoy:payment')
The full code would be:
$xml = simplexml_load_string($soap_response);
$xml->registerXPathNamespace('envoy', 'http://apilistener.envoyservices.com');
foreach ($xml->xpath('//envoy:payment') as $item)
{
print_r($item);
}
Note: I removed the soap
namespace declaration as you do not seem to be using it (it is only useful if you would use the namespace prefix in you xpath queries).
You can still use NSDictionaries in Swift:
For Swift 4
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
For Swift 3+
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
let myDict = NSDictionary(contentsOfFile: path){
// Use your myDict here
}
And older versions of Swift
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
// Use your dict here
}
The NSClasses are still available and perfectly fine to use in Swift. I think they'll probably want to shift focus to swift soon, but currently the swift APIs don't have all the functionality of the core NSClasses.
I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.
I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).
git pull
= git fetch
+ git merge origin/branch
git pull
and git pull origin branch
only differ in that the latter will only "update" origin/branch and not all origin/* as git pull
does.
git pull origin/branch
will just not work because it's trying to do a git fetch origin/branch
which is invalid.
Question related: git fetch + git merge origin/master vs git pull origin/master
One thing I didn't realize at first when reading the accepted answer was that making an inner class static is basically the same thing as moving it to its own separate class.
Thus, when getting the error
xxx is not an enclosing class
You can solve it in either of the following ways:
static
keyword to the inner class, orAs of 2018, we have several new formats, better support for previous formats and some clever hacks of using videos instead of images.
For photographs
jpg
- still the most widely supported image format.
webp
- New format from google. Good potential, though browser support is not great.
For Icons and graphics
svg
- whenever possible. It scales well in retina screens, editable in text editors and customisable via JS/CSS if loaded in DOM.
png
- if it involves raster graphics (ie when created in photoshop). Supports transparency which is very essential in this use-case.
For Animations
svg
- plus css animations for vector graphics. All advantages of svg + power of css animations.
gif
- still the most widely supported animated image format.
mp4
- if animated images are actually short video clips. Twitter / Whatsapp converts gifs to mp4.
apng
- decent browser support (i.e. no IE, Edge), but creating it is not as straightforward as gifs.
webp
- close to using mp4. Poor support
This is a nice comparison of various animated image formats.
Finally, whichever be the format, make sure to optimize it - There are tools for each format (eg SVGO, Guetzli, OptiPNG etc) and can save considerable bandwidth.
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
The jquery each
runs the inner loop; I needed the regular JavaScript for
on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
This is only 5 main lines of code but wrapped onto multiple lines for display:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
More Info
The JSON data was used in the following way:
for each category (key name the array is held under):
for each object held inside an array:
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
"\n" => Newline or Linefeed (semantics)
Unix based systems use just a "\n" to end a line of text.
I think you should cast the pointers to (void *) to get rid of the warnings.
memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);
Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.
sizeof(struct RTCclk)
You can convert Map
to JSON
using Jackson as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
The following snippet will iterate over nested objects. Objects within the objects. Feel free to change it to meet your requirements. Like if you want to add array support make if-else and make a function that loop through arrays ...
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3",_x000D_
"p4": {_x000D_
"p4": 'value 4'_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
/**_x000D_
* Printing a nested javascript object_x000D_
*/_x000D_
function jsonPrinter(obj) {_x000D_
_x000D_
for (let key in obj) {_x000D_
// checking if it's nested_x000D_
if (obj.hasOwnProperty(key) && (typeof obj[key] === "object")) {_x000D_
jsonPrinter(obj[key])_x000D_
} else {_x000D_
// printing the flat attributes_x000D_
console.log(key + " -> " + obj[key]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
jsonPrinter(p);
_x000D_
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok"))
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready()
in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close"
:
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular button anywhere on page
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Do you can want see this
that goes for cases where you used
git checkout -- .
before you commit something.
You may also want to get rid of created files that have not yet been created. And you do not want them. With :
git reset -- .
Here is a Perl script that prints out Git diff commands for a given file as found in a Git log command.
E.g.
git log pom.xml | perl gldiff.pl 3 pom.xml
Yields:
git diff 5cc287:pom.xml e8e420:pom.xml
git diff 3aa914:pom.xml 7476e1:pom.xml
git diff 422bfd:pom.xml f92ad8:pom.xml
which could then be cut and pasted in a shell window session or piped to /bin/sh
.
Notes:
Code:
# gldiff.pl
use strict;
my $max = shift;
my $file = shift;
die "not a number" unless $max =~ m/\d+/;
die "not a file" unless -f $file;
my $count;
my @lines;
while (<>) {
chomp;
next unless s/^commit\s+(.*)//;
my $commit = $1;
push @lines, sprintf "%s:%s", substr($commit,0,6),$file;
if (@lines == 2) {
printf "git diff %s %s\n", @lines;
@lines = ();
}
last if ++$count >= $max *2;
}
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal
can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
You can update with a join if you only affect one table like this:
UPDATE table1
SET table1.name = table2.name
FROM table1, table2
WHERE table1.id = table2.id
AND table2.foobar ='stuff'
But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.
However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.
But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.
You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.
Install grunt-cli with npm i -D grunt-cli
instead of installing it globally with -g
.
//package.json
...
"scripts": {
"build": "grunt"
}
Then use npm run build
to fire off grunt.
It gets revealed when you debug using the debug() function. Suppose you want to see the underlying code in t() transpose function. Just typing 't', doesn't reveal much.
>t
function (x)
UseMethod("t")
<bytecode: 0x000000003085c010>
<environment: namespace:base>
But, Using the 'debug(functionName)', it reveals the underlying code, sans the internals.
> debug(t)
> t(co2)
debugging in: t(co2)
debug: UseMethod("t")
Browse[2]>
debugging in: t.ts(co2)
debug: {
cl <- oldClass(x)
other <- !(cl %in% c("ts", "mts"))
class(x) <- if (any(other))
cl[other]
attr(x, "tsp") <- NULL
t(x)
}
Browse[3]>
debug: cl <- oldClass(x)
Browse[3]>
debug: other <- !(cl %in% c("ts", "mts"))
Browse[3]>
debug: class(x) <- if (any(other)) cl[other]
Browse[3]>
debug: attr(x, "tsp") <- NULL
Browse[3]>
debug: t(x)
EDIT: debugonce() accomplishes the same without having to use undebug()
Just set the value of cookie to false
in order to unset it,
setcookie('cookiename', false);
PS:- That's the easiest way to do it.
You can just use exec
to replace your current shell with a new shell:
Switch to bash
:
exec bash
Switch to zsh
:
exec zsh
This won't affect new terminal windows or anything, but it's convenient.
If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
A thing worth noting is that setting .State = EntityState.Deleted
does not trigger automatically detected change. (archive)
Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.
var n = 5;
for (int i = 0; i < n; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("Label {0}", i);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 20;
//Create textbox
TextBox textBox = new TextBox();
//Position textbox on screen
textBox.Left = 120;
textBox.Top = (i + 1) * 20;
//Add controls to form
this.Controls.Add(label);
this.Controls.Add(textBox);
}
This will not only add them to the form but position them decently as well.
Collection
, as its javadoc says is "The root interface in the collection hierarchy." This means that every single class implementing Collection
in any form is part of the Java Collections Framework.
The Collections Framework is Java's native implementation of data structure classes (with implementation specific properties) which represent a group of objects which are somehow related to each other and thus can be called a collection.
Collections
is merely an utility method class for doing certain operations, for example adding thread safety to your ArrayList instance by doing this:
List<MyObj> list = Collections.synchronizedList(new Arraylist<MyObj>());
The main difference in my opinion is that Collection
is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections
just provides useful operations for handling the collections.
import java.util.ArrayList;
import java.util.Iterator;
public class javaClass {
public static void main(String args[]) {
ArrayList<String> alstr = new ArrayList<>();
alstr.add("irfan");
alstr.add("yogesh");
alstr.add("kapil");
alstr.add("rajoria");
for(String str : alstr) {
System.out.println(str);
}
// update value here
alstr.set(3, "Ramveer");
System.out.println("with Iterator");
Iterator<String> itr = alstr.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
System.out.println(obj);
}
}}
I don't know for sure if the following answer wasn't provided
but I decided to add some local optimizations to the allocation of 2d array
(e.g., a square matrix is done through only one allocation):
int** mat = new int*[n];
mat[0] = new int [n * n];
However, deletion goes like this because of linearity of the allocation above:
delete [] mat[0];
delete [] mat;
You need to use either PHP's ImageMagick or GD functions to work with images.
With GD, for example, it's as simple as...
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And you could call this function, like so...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.
I have been working on a problem similar to this and it took me ages to find the problem. It is not the solution for this particular post, but hopefully adding this will save someone some time trying to find the issue when they are searching for why they might be getting a 404 error for their controller.
Basically, I had spelt "Controller" wrong at the end of my class name. Simple as that!
If you use any(lst)
you see that lst
is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None]
(which all have boolean values of False
) then any(lst)
would be False
. If lst
also contained any of the following [-1, True, "X", 0.00001]
(all of which evaluate to True
) then any(lst)
would be True
.
In the code you posted, x > 0 for x in lst
, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []
's: [x > 0 for x in lst]
. From the lst
containing [-1, -2, 10, -4, 20]
, you would get this comprehended list: [False, False, True, False, True]
. This internal value would then get passed to the any
function, which would return True
, since there is at least one True
value.
But with generator expressions, Python no longer has to create that internal list of True(s)
and False(s)
, the values will be generated as the any
function iterates through the values generated one at a time by the generator expression. And, since any
short-circuits, it will stop iterating as soon as it sees the first True
value. This would be especially handy if you created lst
using something like lst = range(-1,int(1e9))
(or xrange
if you are using Python2.x). Even though this expression will generate over a billion entries, any
only has to go as far as the third entry when it gets to 1
, which evaluates True
for x>0
, and so any
can return True
.
If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any
. But by using a generator expression, you can have Python's builtin functions like any
and all
break out early, as soon as a True
or False
value is seen.
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.
By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.
If our python list is:-
l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
To find occurrence of every items in the python list use following:-
\>>from collections import Counter
\>>c=Counter(l)
\>>print c
Counter({'1': 6, '2': 4, '7': 3, '10': 2})
To find most/highest occurrence of items in the python list:-
\>>k=c.most_common()
\>>k
[('1', 6), ('2', 4), ('7', 3), ('10', 2)]
For Highest one:-
\>>k[0][1]
6
For the item just use k[0][0]
\>>k[0][0]
'1'
For nth highest item and its no of occurrence in the list use follow:-
**for n=2 **
\>>print k[n-1][0] # For item
2
\>>print k[n-1][1] # For value
4
TL;DR ...and late to the party, but that short explanation might help future googlers..
In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.
A minimal example:
df <- data.frame(a = 1:2); df$a <- 1:3
throws the error
Error in
$<-.data.frame
(*tmp*
, a, value = 1:3) : replacement has 3 rows, data has 2
which is clear, because the vector a
of df
has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).
Using the new c# syntax with TryParse worked well for me:
// TimeOut
if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
{
this.timeOut = timeOut;
}
Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc
) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.
Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int
type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList()
. This can be called indirectly by doing a full gc.collect
.
Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.
import os
import gc
import psutil
proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss
# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss
# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss
# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss
pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)
Output:
Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%
Edit:
I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.
The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt
(M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free
.
In 3.x range
doesn't create a list, so the test above won't create 10 million int
objects. Even if it did, the int
type in 3.x is basically a 2.x long
, which doesn't implement a freelist.
Whenever possible one should avoid culture specific date/time literals.
There are some secure formats to provide a date/time as literal:
All examples for 2016-09-15 17:30:00
{ts'2016-09-15 17:30:00'}
--Time Stamp{d'2016-09-15'}
--Date only{t'17:30:00'}
--Time only'2016-09-15T17:30:00'
--be aware of the T
in the middle!'20160915'
--only for pure dateSQL-Server is well know to do things in an order of execution one might not have expected. Your written statement looks like the conversion is done before some type related action takes place, but the engine decides - why ever - to do the conversion in a later step.
Here is a great article explaining this with examples: Rusano.com: "t-sql-functions-do-no-imply-a-certain-order-of-execution" and here is the related question.
Look up NR
and FNR
in the awk manual and then ask yourself what is the condition under which NR==FNR
in the following example:
$ cat file1
a
b
c
$ cat file2
d
e
$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e
I think this is the best way to do it !
<html>
<body onload="document.getElementById('redirectForm').submit()">
<form id='redirectForm' method='POST' action='/done.html'>
<input type='hidden' name='status' value='complete'/>
<input type='hidden' name='id' value='0u812'/>
<input type='submit' value='Please Click Here To Continue'/>
</form>
</body>
</html>
This will be almost instantaneous and user won't see anything !
This way is easiest one in my opinion.
var nameList = new Array('item1','item2','item3','item4');
// Using for loop to loop through each item to check if item exist.
for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1')
{
alert('Value exist');
}else{
alert('Value doesn\'t exist');
}
And Maybe Another way to do it is.
nameList.forEach(function(ItemList)
{
if(ItemList.name == 'item1')
{
alert('Item Exist');
}
}
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
It's 2020 and many of these answers no longer apply to the Sequelize v4/v5/v6 ecosystem.
The one good answer says to use sequelize-auto-migrations
, but probably is not prescriptive enough to use in your project. So here's a bit more color...
My team uses a fork of sequelize-auto-migrations
because the original repo is has not been merged a few critical PRs. #56 #57 #58 #59
$ yarn add github:scimonster/sequelize-auto-migrations#a063aa6535a3f580623581bf866cef2d609531ba
Edit package.json:
"scripts": {
...
"db:makemigrations": "./node_modules/sequelize-auto-migrations/bin/makemigration.js",
...
}
Note: Make sure you’re using git (or some source control) and database backups so that you can undo these changes if something goes really bad.
.sync()
yarn db:makemigrations --name "mega-migration"
).01-mega-migration.js
and the _current.json
that is generated..sync()
or hand-written migrations, you need to “Fake” that mega-migration by inserting the name of it into your SequelizeMeta table. INSERT INTO SequelizeMeta Values ('01-mega-migration.js')
.$ yarn db:makemigrations --name whatever
02-whatever.js
migration and the changes to _current.json
, and _current.bak.json
.$ yarn sequelize db:migrate
.removeColumn
and addColumn
. This will lose data in production. You will need to modify the up and down actions to use renameColumn
instead.For those who confused how to use
renameColumn
, the snippet would look like this. (switch "column_name_before" and "column_name_after" for therollbackCommands
)
{
fn: "renameColumn",
params: [
"table_name",
"column_name_before",
"column_name_after",
{
transaction: transaction
}
]
}
If you have a lot of migrations, the down action may not perfectly remove items in an order consistent way.
The maintainer of this library does not actively check it. So if it doesn't work for you out of the box, you will need to find a different community fork or another solution.
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname,
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE
Lname END AS LnameTrue FROM dbo.____Fname_Lname
This is an Oracle doc explaining how to trace SQL queries, including a couple of tools (SQL Trace and tkprof)
Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.
Another option compatible to 4.0:
Before committing the changes, you can recover the new CayenneDataObject
object(s) from the collection associated to the context, like this:
CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
then access the ObjectId
for each one in the collection, like:
ObjectId objectId = dataObject.getObjectId();
Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot()
, it contains also the column name(s) associated to the PK as key(s):
objectId.getIdSnapshot().values()
Although NVARCHAR
stores Unicode, you should consider by the help of collation also you can use VARCHAR
and save your data of your local languages.
Just imagine the following scenario.
The collation of your DB is Persian and you save a value like '???' (Persian writing of Ali) in the VARCHAR(10)
datatype. There is no problem and the DBMS only uses three bytes to store it.
However, if you want to transfer your data to another database and see the correct result your destination database must have the same collation as the target which is Persian in this example.
If your target collation is different, you see some question marks(?) in the target database.
Finally, remember if you are using a huge database which is for usage of your local language, I would recommend to use location instead of using too many spaces.
I believe the design can be different. It depends on the environment you work on.
In PyUnit there's a method which compares dictionaries beautifully. I tested it using the following two dictionaries, and it does exactly what you're looking for.
d1 = {1: "value1",
2: [{"subKey1":"subValue1",
"subKey2":"subValue2"}]}
d2 = {1: "value1",
2: [{"subKey2":"subValue2",
"subKey1": "subValue1"}]
}
def assertDictEqual(self, d1, d2, msg=None):
self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
I'm not recommending importing unittest
into your production code. My thought is the source in PyUnit could be re-tooled to run in production. It uses pprint
which "pretty prints" the dictionaries. Seems pretty easy to adapt this code to be "production ready".
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
Try run the task with high privileges.
put a \ at the end of path in "start in folder" such as c:\temp\
I do not know why , but this works for me sometimes.
Just be sure that you have include python to windows PATH variable, then run python -m ensurepip
You can also use Google PDF viewer for this purpose. As far as I know it's not an official Google feature (am I wrong on this?), but it works for me very nicely and smoothly. You need to upload your PDF somewhere before and just use its URL:
<iframe src="http://docs.google.com/gview?url=http://example.com/mypdf.pdf&embedded=true" style="width:718px; height:700px;" frameborder="0"></iframe>
What is important is that it doesn't need a Flash player, it uses JavaScript.
Non-numpy functions like math.abs()
or math.log10()
don't play nicely with numpy arrays. Just replace the line raising an error with:
m = np.log10(np.abs(x))
Apart from that the np.polyfit()
call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).
You could use SysInternal's PsExec.
Apple has changed the interface.
The team ID could be found via this link: https://developer.apple.com/account/#/membership
For Xcode 5 I add:
####
# Xcode 5 - VCS metadata
#
*.xccheckout
From Berik's Answer
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
<div class="row">
<div class="col-md-6">
<img src="/assets/images/ebook2.png" alt="" class="img-fluid">
</div>
<div class="col-md-6 my-auto">
<h3>Heading</h3>
<p>Some text.</p>
</div>
</div>
This line is where the magic happens <div class="col-md-6 my-auto">
, the my-auto
will center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.
If you want exactly 40 spaces before the string then you should just do:
printf(" %s\n", myStr );
If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces):
printf("%40s%s", "", myStr );
If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this:
printf("%40s", myStr);
You can also put "up to" 40 spaces AfTER the string by doing:
printf("%-40s", myStr);
The answer probably depends on what format your date is in, but here is an example using the Date
class:
dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")
You can even play with different units like weeks.
I just confirmed that:
cat file.txt | sed "s/\s/,/g"
successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.
You can use Include Directives
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<%@include file="<%="includes/" + p +".jsp"%>"%>
<%
}
%>
or JSP Include Action
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<jsp:include page="<%="includes/"+p+".jsp"%>"/>
<%
}
%>
the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested
I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.
example:
www.yourwebsite.com/products
instead of
www.yourwebsite.com/?p=products
Watch this video Spring MVC Framework
When you get a UnicodeEncodeError
, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)
To avoid that, you must use explicit decoding.
If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.
def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
If you do not know original encoding and do not care for non ascii character, you can set the optional errors
parameter of the decode
method to replace
. Any offending byte will be replaced (from the standard library documentation):
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
bs.decode(errors='replace')
Right click project solution
Properties -> Configuration Properties -> C/C++ -> Precompiled Headers
Click on "Precompiled Headers" change to "Not Using Precompiled Headers".
Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.
Then you can feel free to delete the pch./stdafx. files in your project
I find the following function sufficient:
'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double
If x = Round(x, digits) Then
RoundUp = x
Else
RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
End If
End Function
function convertDatePickerTimeToMySQLTime(str) {
var month, day, year, hours, minutes, seconds;
var date = new Date(str),
month = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
seconds = ("0" + date.getSeconds()).slice(-2);
var mySQLDate = [date.getFullYear(), month, day].join("-");
var mySQLTime = [hours, minutes, seconds].join(":");
return [mySQLDate, mySQLTime].join(" ");
}
You can use the following query to create a table to a particular database in MySql.
create database if not exists `test`;
USE `test`;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*Table structure for table `test` */
CREATE TABLE IF NOT EXISTS `tblsample` (
`id` int(11) NOT NULL auto_increment,
`recid` int(11) NOT NULL default '0',
`cvfilename` varchar(250) NOT NULL default '',
`cvpagenumber` int(11) NULL,
`cilineno` int(11) NULL,
`batchname` varchar(100) NOT NULL default '',
`type` varchar(20) NOT NULL default '',
`data` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
);
There are 2 steps to resolve this:
Add UseAccessibleHeader="true"
to Gridview tag:
<asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
Add the following Code to the PreRender
event:
Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
Try
MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
Catch ex As Exception
End Try
End Sub
Note setting Header Row in DataBound()
works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.
You need to do two additional things after following the link that you have mentioned in your post:
One have to map the changed login cridentials in phpmyadmin's config.inc.php
and second, you need to restart your web and mysql servers..
php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php
and in that file put your current mysql password at line
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here
#include "header.h"
int estimatedPopulation (int currentPopulation, float growthRate)
{
return currentPopulation + currentPopulation * growthRate / 100;
}
You can also see the error in the Build window by clicking on the toggle button.
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
If your SSH agent is running, it is
ssh-add -l
to list RSA fingerprints of all identities, or -L
for listing public keys.
If your agent is not running, try:
ssh-agent sh -c 'ssh-add; ssh-add -l'
And for your public keys:
ssh-agent sh -c 'ssh-add; ssh-add -L'
If you get the message: 'The agent has no identities.', then you have to generate your RSA key by ssh-keygen
first.
In the past I have created my XML Schema, then used a tool to generate C# classes which will serialize to that schema. The XML Schema Definition Tool is one example
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
Probably the easiest way is:
SELECT EXTRACT(epoch FROM my_interval)/3600
CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows: Replace character entities with characters,
Ignore line feeds,
Replace each carriage return or tab with a single space.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
private final Lock _mutex = new ReentrantLock(true);
_mutex.lock();
// your protected code here
_mutex.unlock();
For anyone on Mac OS X, you can find netbeans.conf
here:
/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf
In case anyone needs to know :)
Here's a simple example with no jQuery. Use URL.createObjectURL
, which
creates a DOMString containing a URL representing the object given in the parameter
Then, you can simply set the src
of the image to that url:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img');
img.onload = () => {
URL.revokeObjectURL(img.src); // no longer needed, free memory
}
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
}
});
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
Javascript is a dynamic programming language which supports the object oriented programming paradigm, and it use used for creating new instances of object.
Classes are not necessary for objects - Javascript is a prototype based language.
The answer is due to the fact that Google Chrome uses an SQLite file to save cookies. It resides under:
C:\Users\<your_username>\AppData\Local\Google\Chrome\User Data\Default\
inside Cookies
file. (which is an SQLite database file)
So it's not a file stored on hard drive but a row in an SQLite database file which can be read by a third party program such as: SQLite Database Browser
EDIT: Thanks to @Chexpir, it is also good to know that the values are stored encrypted.
Run below commands in Terminal:
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:
1: use --allow-root option for bower install command
"postinstall": "./node_modules/bower/bin/bower --allow-root install"
2: use --unsafe-perm option for npm install command
npm install --unsafe-perm
Ambu,
I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.
DataTable dt = new DataTable();
// add the columns to the datatable
if (GridView1.HeaderRow != null)
{
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
{
dr[i] = GridView1.FooterRow.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
Let's say you have this image:
to make a circle out of this you only need to add
.circle {
border-radius: 50%;
width: 100px;
height: 100px;
}
So if you have a div you can do the same thing.
Check the example below:
.circle {_x000D_
border-radius: 50%;_x000D_
width: 100px;_x000D_
height: 100px; _x000D_
animation: stackoverflow-example infinite 20s linear;_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
@keyframes stackoverflow-example {_x000D_
from {_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}
_x000D_
<div>_x000D_
<img class="circle" src="https://www.sitepoint.com/wp-content/themes/sitepoint/assets/images/icon.javascript.png">_x000D_
</div>
_x000D_
Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.
lubridate
contains a number of functions that make parsing dates into POSIXct
or Date
objects easy. Here we use dmy
which automatically parses dates in Day, Month, Year
formats. Once your data is in a date format, you can sort it with dplyr::arrange
(or any other ordering function) as desired:
d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)
Open tmux configuration file with the following command:
vim ~/.tmux.conf
In the configuration file add the following line:
set -g history-limit 5000
Log out and log in again, start a new tmux windows and your limit is 5000 now.
For me just removed the OLE DB source from SSIS and added again. Worked!
Create an XML file named border.xml in the drawable folder and put the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
Then add a background to your linear layout like this:
android:background="@drawable/border"
EDIT :
This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:
ALSO
tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :
Finally its works perfectly with all APIs
EDIT 2 :
It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="0dp" android:right="0dp" android:top="0dp"
android:bottom="-10dp">
<shape android:shape="rectangle">
<stroke android:width="10dp" android:color="#B22222" />
</shape>
</item>
</layer-list>
hope this help .
// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:
var scrollBarWidth = element.offsetWidth - element.clientWidth;
Its possible to make this even shorter with C# 6:
public string NullToString(string Value)
{
return value?.ToString() ?? "";
}
Here are basic Two
methods:
1) Use of 'out
' as parameter
You can use 'out' for both 4.0 and minor versions too.
Example of 'out':
using System;
namespace out_parameter
{
class Program
{
//Accept two input parameter and returns two out value
public static void rect(int len, int width, out int area, out int perimeter)
{
area = len * width;
perimeter = 2 * (len + width);
}
static void Main(string[] args)
{
int area, perimeter;
// passing two parameter and getting two returning value
Program.rect(5, 4, out area, out perimeter);
Console.WriteLine("Area of Rectangle is {0}\t",area);
Console.WriteLine("Perimeter of Rectangle is {0}\t", perimeter);
Console.ReadLine();
}
}
}
Output:
Area of Rectangle is 20
Perimeter of Rectangle is 18
*Note:*The out
-keyword describes parameters whose actual variable locations are copied onto the stack of the called method, where those same locations can be rewritten. This means that the calling method will access the changed parameter.
2) Tuple<T>
Example of Tuple:
Returning Multiple DataType values using Tuple<T>
using System;
class Program
{
static void Main()
{
// Create four-item tuple; use var implicit type.
var tuple = new Tuple<string, string[], int, int[]>("perl",
new string[] { "java", "c#" },
1,
new int[] { 2, 3 });
// Pass tuple as argument.
M(tuple);
}
static void M(Tuple<string, string[], int, int[]> tuple)
{
// Evaluate the tuple's items.
Console.WriteLine(tuple.Item1);
foreach (string value in tuple.Item2)
{
Console.WriteLine(value);
}
Console.WriteLine(tuple.Item3);
foreach (int value in tuple.Item4)
{
Console.WriteLine(value);
}
}
}
Output
perl
java
c#
1
2
3
NOTE: Use of Tuple is valid from Framework 4.0 and above.Tuple
type is a class
. It will be allocated in a separate location on the managed heap in memory. Once you create the Tuple
, you cannot change the values of its fields
. This makes the Tuple
more like a struct
.
It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)
You can get the exact same error message also, if you use any other built-in method as variable name.
If c
is a set then you can check whether it's empty by doing: return not c
.
If c
is empty then not c
will be True
.
Otherwise, if c
contains any elements not c
will be False
.
Remove the comma?
select /*+USE_HASH( a b ) */ to_char(date, 'MM/DD/YYYY HH24:MI:SS') as LABEL,
ltrim(rtrim(substr(oled, 9, 16))) as VALUE
from rrfh a, rrf b
where ltrim(rtrim(substr(oled, 1, 9))) = 'stata kish'
and a.xyz = b.xyz
Have a look at FROM
SELECTING from multiple tables You can include multiple tables in the FROM clause by listing the tables with a comma in between each table name
The json.load()
method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
You were using the json.loads()
method, which is used for string arguments only.
Edit: The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.
There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.
I use combination of several plugins - for the basic assignment of roles and permission I use Role Strategy Plugin.
When I need to split some role depending on parameters (e.g. everybody with job-runner is able to run jobs, but user only user UUU is allowed to run the deployment job to deploy on machine MMM), I use Python Plugin and define a python script as first build step and end with sys.exit(-1) when the job is forbidden to be run with the given combination of parameters.
Build User Vars Plugin provides me the information about the user executing the job as environment variables.
E.g:
import os
import sys
print os.environ["BUILD_USER"], "deploying to", os.environ["target_host"]
# only some users are allowed to deploy to servers "MMM"
mmm_users = ["UUU"]
if os.environ["target_host"] != "MMM" or os.environ["BUILD_USER"] in mmm_users:
print "access granted"
else:
print "access denied"
sys.exit(-1)
If you have more than 2-3 columns, SetOrdinal
is not the way to go. A DataView's ToTable
method accepts a parameter array of column names. Order your columns there:
DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");
Update: check for existence using TryGetValue
to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string>
as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>
, favour the constructor that takes the initial list capacity: new List<int>(100);
.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
set title color
btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).
One idea might be to add clases to the body, then use CSS to style the document accordingly.
This script helps to change the image on click the text:
<script>
$(document).ready(function(){
$('li').click(function(){
var imgpath = $(this).attr('dir');
$('#image').html('<img src='+imgpath+'>');
});
$('.btn').click(function(){
$('#thumbs').fadeIn(500);
$('#image').animate({marginTop:'10px'},200);
$(this).hide();
$('#hide').fadeIn('slow');
});
$('#hide').click(function(){
$('#thumbs').fadeOut(500,function (){
$('#image').animate({marginTop:'50px'},200);
});
$(this).hide();
$('#show').fadeIn('slow');
});
});
</script>
<div class="sandiv">
<h1 style="text-align:center;">The Human Body Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>
see the demo here