It is worth to mention that with modern frameworks like reactJS, AngularJS, VueJS, etc, there are easy solutions for this problem, when dealing with fixed position elements. Examples are side panels or overlaid elements.
The technique is called a "Portal", which means that one of the components used in the app, without the need to actually extract it from where you are using it, will mount its children at the bottom of the body element, outside of the parent you are trying to avoid scrolling.
Note that it will not avoid scrolling the body element itself. You can combine this technique and mounting your app in a scrolling div to achieve the expected result.
Example Portal implementation in React's material-ui: https://material-ui-next.com/api/portal/
As stated in Date and Time Literals:
MySQL recognizes
DATE
values in these formats:
As a string in either
'YYYY-MM-DD'
or'YY-MM-DD'
format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example,'2012-12-31'
,'2012/12/31'
,'2012^12^31'
, and'2012@12@31'
are equivalent.As a string with no delimiters in either
'YYYYMMDD'
or'YYMMDD'
format, provided that the string makes sense as a date. For example,'20070523'
and'070523'
are interpreted as'2007-05-23'
, but'071332'
is illegal (it has nonsensical month and day parts) and becomes'0000-00-00'
.As a number in either
YYYYMMDD
orYYMMDD
format, provided that the number makes sense as a date. For example,19830905
and830905
are interpreted as'1983-09-05'
.
Therefore, the string '08/25/2012'
is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField
together with its altFormat
option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD
format, simply set the dateFormat
option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE()
function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime
object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME()
function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_*
functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME
or TIMESTAMP
column for holding a date value; I recommend you consider using MySQL's DATE
type instead. As explained in The DATE
, DATETIME
, and TIMESTAMP
Types:
The
DATE
type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in'YYYY-MM-DD'
format. The supported range is'1000-01-01'
to'9999-12-31'
.The
DATETIME
type is used for values that contain both date and time parts. MySQL retrieves and displaysDATETIME
values in'YYYY-MM-DD HH:MM:SS'
format. The supported range is'1000-01-01 00:00:00'
to'9999-12-31 23:59:59'
.The
TIMESTAMP
data type is used for values that contain both date and time parts.TIMESTAMP
has a range of'1970-01-01 00:00:01'
UTC to'2038-01-19 03:14:07'
UTC.
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
You should chain your Lambda functions
via SNS
. This approach provides good performance, latency and scalability for minimal effort.
Your first Lambda
publishes messages to your SNS Topic
and the second Lambda
is subscribed to this topic. As soon as messages arrive in the topic, second Lambda
gets executed with the message as it's input parameter.
See Invoking Lambda functions using Amazon SNS notifications.
You can also use this approach to Invoke cross-account Lambda functions via SNS.
I also faced the similar problem. I googled but couldn't find the solution. So I tried on my own and here is my solution.
Open you solution file in notepad. Make 2 changes
Hope this helps u as well..........
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
One of the Honeycomb samples refers to ?android:attr/actionBarSize
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.
using CustomerList = System.Collections.Generic.List<Customer>;
but that will only impact that source file. In C and C++, my experience is that typedef
is usually used within .h files which are included widely - so a single typedef
can be used over a whole project. That ability does not exist in C#, because there's no #include
functionality in C# that would allow you to include the using
directives from one file in another.
Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:
gcInt.MyEvent += gcInt_MyEvent;
:)
let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)
There is one big difference between malloc
and new
. malloc
allocates memory. This is fine for C, because in C, a lump of memory is an object.
In C++, if you're not dealing with POD types (which are similar to C types) you must call a constructor on a memory location to actually have an object there. Non-POD types are very common in C++, as many C++ features make an object automatically non-POD.
new
allocates memory and creates an object on that memory location. For non-POD types this means calling a constructor.
If you do something like this:
non_pod_type* p = (non_pod_type*) malloc(sizeof *p);
The pointer you obtain cannot be dereferenced because it does not point to an object. You'd need to call a constructor on it before you can use it (and this is done using placement new
).
If, on the other hand, you do:
non_pod_type* p = new non_pod_type();
You get a pointer that is always valid, because new
created an object.
Even for POD types, there's a significant difference between the two:
pod_type* p = (pod_type*) malloc(sizeof *p);
std::cout << p->foo;
This piece of code would print an unspecified value, because the POD objects created by malloc
are not initialised.
With new
, you could specify a constructor to call, and thus get a well defined value.
pod_type* p = new pod_type();
std::cout << p->foo; // prints 0
If you really want it, you can use use new
to obtain uninitialised POD objects. See this other answer for more information on that.
Another difference is the behaviour upon failure. When it fails to allocate memory, malloc
returns a null pointer, while new
throws an exception.
The former requires you to test every pointer returned before using it, while the later will always produce valid pointers.
For these reasons, in C++ code you should use new
, and not malloc
. But even then, you should not use new
"in the open", because it acquires resources you need to release later on. When you use new
you should pass its result immediately into a resource managing class:
std::unique_ptr<T> p = std::unique_ptr<T>(new T()); // this won't leak
To scale an image by keeping its aspect ratio
Try this,
img {
max-width:100%;
height:auto;
}
DO NOT use this:
System.Environment.GetEnvironmentVariable("TEMP")
Environment variables can be overridden, so the TEMP
variable is not necessarily the directory.
The correct way is to use System.IO.Path.GetTempPath()
as in the accepted answer.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.
It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.
An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:
com.awesomeapps.thebestapp
In this case the suffix is thebestapp
.
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
Works fine for me
See example here. http://jsfiddle.net/blowsie/c6VAy/
Make sure your jquery is inside $(document).ready
function or similar.
Also you can improve your code by using jquery data
$('#amount').data('min','1000');
<div id="amount" data-min=""></div>
Update,
A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/
I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.
It is not hard to understand...
Anyway, I just put something like this inside my tag:
style='padding:5px 10px 5px 5px'
Where the order represents top, right, bottom and left.
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
class Object
def nil_zero?
self.nil? || self == 0
end
end
# which lets you do
nil.nil_zero? # returns true
0.nil_zero? # returns true
1.nil_zero? # returns false
"a".nil_zero? # returns false
unless discount.nil_zero?
# do stuff...
end
Beware of the usual disclaimers... great power/responsibility, monkey patching leading to the dark side etc.
Check the collation type of each table, and make sure that they have the same collation.
After that check also the collation type of each table field that you have use in operation.
I had encountered the same error, and that tricks works on me.
The worksheet formula, =CELL("color",D3)
returns 1
if the cell is formatted with color for negative values (else returns 0
).
You can solve this with a bit of VBA. Insert this into a VBA code module:
Function CellColor(xlRange As Excel.Range)
CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function
Then use the function =CellColor(D3)
to display the .ColorIndex
of D3
If you use df.replace([None], np.nan, inplace=True), this changed all datetime objects with missing data to object dtypes. So now you may have broken queries unless you change them back to datetime which can be taxing depending on the size of your data.
If you want to use this method, you can first identify the object dtype fields in your df and then replace the None:
obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)
Do you really need that plugin? You can just animate the scrollTop
property:
$("#nav ul li a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
Since the exact question is "what does enable bitcode do", I'd like to give a few thin technical details I've figured out thus far. Most of this is practically impossible to figure out with 100% certainty until Apple releases the source code for this compiler
First, Apple's bitcode does not appear to be the same thing as LLVM bytecode. At least, I've not been able to figure out any resemblance between them. It appears to have a proprietary header (always starts with "xar!") and probably some link-time reference magic that prevents data duplications. If you write out a hardcoded string, this string will only be put into the data once, rather than twice as would be expected if it was normal LLVM bytecode.
Second, bitcode is not really shipped in the binary archive as a separate architecture as might be expected. It is not shipped in the same way as say x86 and ARM are put into one binary (FAT archive). Instead, they use a special section in the architecture specific MachO binary named "__LLVM" which is shipped with every architecture supported (ie, duplicated). I assume this is a short coming with their compiler system and may be fixed in the future to avoid the duplication.
C code (compiled with clang -fembed-bitcode hi.c -S -emit-llvm
):
#include <stdio.h>
int main() {
printf("hi there!");
return 0;
}
LLVM IR output:
; ModuleID = '/var/folders/rd/sv6v2_f50nzbrn4f64gnd4gh0000gq/T/hi-a8c16c.bc'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
@llvm.embedded.module = appending constant [1600 x i8] c"\DE\C0\17\0B\00\00\00\00\14\00\00\00$\06\00\00\07\00\00\01BC\C0\DE!\0C\00\00\86\01\00\00\0B\82 \00\02\00\00\00\12\00\00\00\07\81#\91A\C8\04I\06\1029\92\01\84\0C%\05\08\19\1E\04\8Bb\80\10E\02B\92\0BB\84\102\148\08\18I\0A2D$H\0A\90!#\C4R\80\0C\19!r$\07\C8\08\11b\A8\A0\A8@\C6\F0\01\00\00\00Q\18\00\00\C7\00\00\00\1Bp$\F8\FF\FF\FF\FF\01\90\00\0D\08\03\82\1D\CAa\1E\E6\A1\0D\E0A\1E\CAa\1C\D2a\1E\CA\A1\0D\CC\01\1E\DA!\1C\C8\010\87p`\87y(\07\80p\87wh\03s\90\87ph\87rh\03xx\87tp\07z(\07yh\83r`\87th\07\80\1E\E4\A1\1E\CA\01\18\DC\E1\1D\DA\C0\1C\E4!\1C\DA\A1\1C\DA\00\1E\DE!\1D\DC\81\1E\CAA\1E\DA\A0\1C\D8!\1D\DA\A1\0D\DC\E1\1D\DC\A1\0D\D8\A1\1C\C2\C1\1C\00\C2\1D\DE\A1\0D\D2\C1\1D\CCa\1E\DA\C0\1C\E0\A1\0D\DA!\1C\E8\01\1D\00s\08\07v\98\87r\00\08wx\876p\87pp\87yh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \E6\81\1E\C2a\1C\D6\A1\0D\E0A\1E\DE\81\1E\CAa\1C\E8\E1\1D\E4\A1\0D\C4\A1\1E\CC\C1\1C\CAA\1E\DA`\1E\D2A\1F\CA\01\C0\03\80\A0\87p\90\87s(\07zh\83q\80\87z\00\C6\E1\1D\E4\A1\1C\E4\00 \E8!\1C\E4\E1\1C\CA\81\1E\DA\C0\1C\CA!\1C\E8\A1\1E\E4\A1\1C\E6\01X\83y\98\87y(\879`\835\18\07|\88\03;`\835\98\87y(\076X\83y\98\87r\90\036X\83y\98\87r\98\03\80\A8\07w\98\87p0\87rh\03s\80\876h\87p\A0\07t\00\CC!\1C\D8a\1E\CA\01 \EAa\1E\CA\A1\0D\E6\E1\1D\CC\81\1E\DA\C0\1C\D8\E1\1D\C2\81\1E\00s\08\07v\98\87r\006\C8\88\F0\FF\FF\FF\FF\03\C1\0E\E50\0F\F3\D0\06\F0 \0F\E50\0E\E90\0F\E5\D0\06\E6\00\0F\ED\10\0E\E4\00\98C8\B0\C3<\94\03@\B8\C3;\B4\819\C8C8\B4C9\B4\01<\BCC:\B8\03=\94\83<\B4A9\B0C:\B4\03@\0F\F2P\0F\E5\00\0C\EE\F0\0Em`\0E\F2\10\0E\EDP\0Em\00\0F\EF\90\0E\EE@\0F\E5 \0FmP\0E\EC\90\0E\ED\D0\06\EE\F0\0E\EE\D0\06\ECP\0E\E1`\0E\00\E1\0E\EF\D0\06\E9\E0\0E\E60\0Fm`\0E\F0\D0\06\ED\10\0E\F4\80\0E\809\84\03;\CCC9\00\84;\BCC\1B\B8C8\B8\C3<\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F3@\0F\E10\0E\EB\D0\06\F0 \0F\EF@\0F\E50\0E\F4\F0\0E\F2\D0\06\E2P\0F\E6`\0E\E5 \0Fm0\0F\E9\A0\0F\E5\00\E0\01@\D0C8\C8\C39\94\03=\B4\C18\C0C=\00\E3\F0\0E\F2P\0Er\00\10\F4\10\0E\F2p\0E\E5@\0Fm`\0E\E5\10\0E\F4P\0F\F2P\0E\F3\00\AC\C1<\CC\C3<\94\C3\1C\B0\C1\1A\8C\03>\C4\81\1D\B0\C1\1A\CC\C3<\94\03\1B\AC\C1<\CCC9\C8\01\1B\AC\C1<\CCC9\CC\01@\D4\83;\CCC8\98C9\B4\819\C0C\1B\B4C8\D0\03:\00\E6\10\0E\EC0\0F\E5\00\10\F50\0F\E5\D0\06\F3\F0\0E\E6@\0Fm`\0E\EC\F0\0E\E1@\0F\809\84\03;\CCC9\00\00I\18\00\00\02\00\00\00\13\82`B \00\00\00\89 \00\00\0D\00\00\002\22\08\09 d\85\04\13\22\A4\84\04\13\22\E3\84\A1\90\14\12L\88\8C\0B\84\84L\100s\04H*\00\C5\1C\01\18\94`\88\08\AA0F7\10@3\02\00\134|\C0\03;\F8\05;\A0\836\08\07x\80\07v(\876h\87p\18\87w\98\07|\88\038p\838\80\037\80\83\0DeP\0Em\D0\0Ez\F0\0Em\90\0Ev@\07z`\07t\D0\06\E6\80\07p\A0\07q \07x\D0\06\EE\80\07z\10\07v\A0\07s \07z`\07t\D0\06\B3\10\07r\80\07:\0FDH #EB\80\1D\8C\10\18I\00\00@\00\00\C0\10\A7\00\00 \00\00\00\00\00\00\00\868\08\10\00\02\00\00\00\00\00\00\90\05\02\00\00\08\00\00\002\1E\98\0C\19\11L\90\8C\09&G\C6\04C\9A\22(\01\0AM\D0i\10\1D]\96\97C\00\00\00y\18\00\00\1C\00\00\00\1A\03L\90F\02\134A\18\08&PIC Level\13\84a\D80\04\C2\C05\08\82\83c+\03ab\B2j\02\B1+\93\9BK{s\03\B9q\81q\81\01A\19c\0Bs;k\B9\81\81q\81q\A9\99q\99I\D9\10\14\8D\D8\D8\EC\DA\5C\DA\DE\C8\EA\D8\CA\5C\CC\D8\C2\CE\E6\A6\04C\1566\BB6\974\B227\BA)A\01\00y\18\00\002\00\00\003\08\80\1C\C4\E1\1Cf\14\01=\88C8\84\C3\8CB\80\07yx\07s\98q\0C\E6\00\0F\ED\10\0E\F4\80\0E3\0CB\1E\C2\C1\1D\CE\A1\1Cf0\05=\88C8\84\83\1B\CC\03=\C8C=\8C\03=\CCx\8Ctp\07{\08\07yH\87pp\07zp\03vx\87p \87\19\CC\11\0E\EC\90\0E\E10\0Fn0\0F\E3\F0\0E\F0P\0E3\10\C4\1D\DE!\1C\D8!\1D\C2a\1Ef0\89;\BC\83;\D0C9\B4\03<\BC\83<\84\03;\CC\F0\14v`\07{h\077h\87rh\077\80\87p\90\87p`\07v(\07v\F8\05vx\87w\80\87_\08\87q\18\87r\98\87y\98\81,\EE\F0\0E\EE\E0\0E\F5\C0\0E\EC\00q \00\00\05\00\00\00&`<\11\D2L\85\05\10\0C\804\06@\F8\D2\14\01\00\00a \00\00\0B\00\00\00\13\04A,\10\00\00\00\03\00\00\004#\00dC\19\020\18\83\01\003\11\CA@\0C\83\11\C1\00\00#\06\04\00\1CB\12\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00", section "__LLVM,__bitcode"
@llvm.cmdline = appending constant [67 x i8] c"-triple\00x86_64-apple-macosx10.10.0\00-emit-llvm\00-disable-llvm-optzns\00", section "__LLVM,__cmdline"
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.0.53.3)"}
The data array that is in the IR also changes depending on the optimization and other code generation settings of clang. It's completely unknown to me what format or anything that this is in.
EDIT:
Following the hint on Twitter, I decided to revisit this and to confirm it. I followed this blog post and used his bitcode extractor tool to get the Apple Archive binary out of the MachO executable. And after extracting the Apple Archive with the xar utility, I got this (converted to text with llvm-dis of course)
; ModuleID = '1'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"
@.str = private unnamed_addr constant [10 x i8] c"hi there!\00", align 1
; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
declare i32 @printf(i8*, ...) #1
attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+ssse3,+cx16,+sse,+sse2,+sse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"Apple LLVM version 7.0.0 (clang-700.1.76)"}
The only notable difference really between the non-bitcode IR and the bitcode IR is that filenames have been stripped to just 1, 2, etc for each architecture.
I also confirmed that the bitcode embedded in a binary is generated after optimizations. If you compile with -O3 and extract out the bitcode, it'll be different than if you compile with -O0.
And just to get extra credit, I also confirmed that Apple does not ship bitcode to devices when you download an iOS 9 app. They include a number of other strange sections that I don't recognized like __LINKEDIT, but they do not include __LLVM.__bundle, and thus do not appear to include bitcode in the final binary that runs on a device. Oddly enough, Apple still ships fat binaries with separate 32/64bit code to iOS 8 devices though.
Don't use list
as a variable name for it shadows the builtin.
And there is no need to determine the length of the list. Just iterate over it.
def printer(data):
for element in data:
print(element[0])
Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.
You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial
The image below is from the article written by Erwin van der Valk:
The article explains the differences and gives some code examples in C#
As for me I've solved this problem by next way - as developer.android.com says, after adding google-play-services_lib you should add <meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
in your manifest, but on the new SDK you'll always get an error:
Error: No resource found that matches the given name (at 'value' with value '@integer/ google_play_services_version').
To solve that error many people advise to use a raw value, 4030500, instead of @integer/google_play_services_version
, but it is correct ONLY for Google services revision 13.
If you use any older version or version for Froyo (like me) you should put another value in it. To know what value you should put just open a Google Play services manifest and copy-paste a version_code value. For Froyo services, it is 3265130. After adding this I've stopped getting this error, and I've began to receive coordinates in my application at last.
I wrote something like this for Sails a while back, in case it saves you some time:
Example usage:
// Delete the user with id=4
User.findAndDelete(4,function(error,result){
// all done
});
// Delete all users with type === 'suspended'
User.findAndDelete({
type: 'suspended'
},function(error,result){
// all done
});
Source:
/**
* Retrieve models which match `where`, then delete them
*/
function findAndDelete (where,callback) {
// Handle *where* argument which is specified as an integer
if (_.isFinite(+where)) {
where = {
id: where
};
}
Model.findAll({
where:where
}).success(function(collection) {
if (collection) {
if (_.isArray(collection)) {
Model.deleteAll(collection, callback);
}
else {
collection.destroy().
success(_.unprefix(callback)).
error(callback);
}
}
else {
callback(null,collection);
}
}).error(callback);
}
/**
* Delete all `models` using the query chainer
*/
deleteAll: function (models) {
var chainer = new Sequelize.Utils.QueryChainer();
_.each(models,function(m,index) {
chainer.add(m.destroy());
});
return chainer.run();
}
from: orm.js.
Hope that helps!
The only thing that worked for me in this situation was the self-created openssl.cnf file.
Here are the basics needed for this exercise (edit as needed):
#
# OpenSSL configuration file.
#
# Establish working directory.
dir = .
[ ca ]
default_ca = CA_default
[ CA_default ]
serial = $dir/serial
database = $dir/certindex.txt
new_certs_dir = $dir/certs
certificate = $dir/cacert.pem
private_key = $dir/private/cakey.pem
default_days = 365
default_md = md5
preserve = no
email_in_dn = no
nameopt = default_ca
certopt = default_ca
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
default_bits = 1024 # Size of keys
default_keyfile = key.pem # name of generated keys
default_md = md5 # message digest algorithm
string_mask = nombstr # permitted characters
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
# Variable name Prompt string
#------------------------- ----------------------------------
0.organizationName = Organization Name (company)
organizationalUnitName = Organizational Unit Name (department, division)
emailAddress = Email Address
emailAddress_max = 40
localityName = Locality Name (city, district)
stateOrProvinceName = State or Province Name (full name)
countryName = Country Name (2 letter code)
countryName_min = 2
countryName_max = 2
commonName = Common Name (hostname, IP, or your name)
commonName_max = 64
# Default values for the above, for consistency and less typing.
# Variable name Value
#------------------------ ------------------------------
0.organizationName_default = My Company
localityName_default = My Town
stateOrProvinceName_default = State or Providence
countryName_default = US
[ v3_ca ]
basicConstraints = CA:TRUE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
[ v3_req ]
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
I hope that helps.
Please check if you are disable error reporting somewhere in your code.
There was a place in my code where I have disabled it, so I added the debug code after it:
require_once("inc/req.php"); <-- Error reporting is disabled here
// overwrite it
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
The Status Value being returned by a Stored Procedure can only be an INT datatype. You cannot return other datatypes in the RETURN statement.
From Lesson 2: Designing Stored Procedures:
Every stored procedure can return an integer value known as the execution status value or return code.
If you still want a table returned from the SP, you'll either have to work the record set returned from a SELECT within the SP or tie into an OUTPUT variable that passes an XML datatype.
HTH,
John
If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:
declare const modal: IModal;
If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.
const modal: IModal = {
content: '',
form: '',
href: '',
$form: null,
$message: null,
$modal: null,
$submits: null
};
Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content
and so on (properties that the contract says will be there).
const modal = {} as IModal;
Example Class
class Modal implements IModal {
content: string;
form: string;
href: string;
$form: JQuery;
$message: JQuery;
$modal: JQuery;
$submits: JQuery;
}
const modal = new Modal();
You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...
const modal: Modal = new Modal();
Rather than
const modal: IModal = new Modal();
Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style
Check out its already been answered, click here
Did you try:
$(this).is(':focus');
Take a look at Using jQuery to test if an input has focus it features some more examples
If you use the BOOLEAN type, this is aliased to TINYINT(1). This is best if you want to use standardised SQL and don't mind that the field could contain an out of range value (basically anything that isn't 0 will be 'true').
ENUM('False', 'True') will let you use the strings in your SQL, and MySQL will store the field internally as an integer where 'False'=0 and 'True'=1 based on the order the Enum is specified.
In MySQL 5+ you can use a BIT(1) field to indicate a 1-bit numeric type. I don't believe this actually uses any less space in the storage but again allows you to constrain the possible values to 1 or 0.
All of the above will use approximately the same amount of storage, so it's best to pick the one you find easiest to work with.
Set LDFLAGS and CFLAGS when you run make:
$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make
If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib
If you open the Event Log viewer before the event source is created, for example while installing a service, you'll get that error message. You don't need to restart the OS: you simply have to close and open the event viewer.
NOTE: I don't provide a custom messages file. The creation of the event source uses the default configuration, as shown on Matt's answer.
These functions, based on the above, seem to work well for getting characters from the keyboard (blocking and non-blocking):
import termios, fcntl, sys, os
def get_char_keyboard():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
c = None
try:
c = sys.stdin.read(1)
except IOError: pass
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return c
def get_char_keyboard_nonblock():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
c = None
try:
c = sys.stdin.read(1)
except IOError: pass
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
return c
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18
.
If you are using anaconda distribution, you can do the following to use python 3.5 on the new environnement "tensorflow":
conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
# or
# pip install tensorflow-gpu
It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.
Source: https://github.com/tensorflow/tensorflow/issues/6999#issuecomment-278459224
Finally I solve the issues using below code. This type of error will happen when there is a mismatch between In/Out parameter as declare in procedure and in java code declareParameters
. Here we need to defined oracle return tab
public class ManualSaleStoredProcedureDao {
private SimpleJdbcCall getAllSytemUsers;
public List<SystemUser> getAllSytemUsers(String clientCode) {
MapSqlParameterSource in = new MapSqlParameterSource();
in.addValue("pi_client_code", clientCode);
Map<String, Object> result = getAllSytemUsers.execute(in);
@SuppressWarnings("unchecked")
List<SystemUser> systemUsers = (List<SystemUser>) result
.get(VSCConstants.GET_SYSTEM_USER_OUT_PARAM1);
return systemUsers;
}
public void setDataSource(DataSource dataSource) {
getAllSytemUsers = new SimpleJdbcCall(dataSource)
.withSchemaName(VSCConstants.SCHEMA)
.withProcedureName(VSCConstants.GET_SYSTEM_USER_PROC_NAME)
.declareParameters(
new SqlParameter(
"pi_client_code",
OracleTypes.NUMBER,
"pi_client_code"),
new SqlInOutParameter(
"po_system_users",
OracleTypes.ARRAY,
"T_SYSTEM_USER_TAB",
new OracleSystemUser()));
}
Pure bash
, no basename
, no variable juggling. Set a string and echo
:
p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"
Output:
foo
Note: the bash
extglob option must be "on", (Ubuntu sets extglob "on" by default), if it's not, do:
shopt -s extglob
Walking through the ${p//+(*\/|.*)}
:
${p
-- start with $p.//
substitute every instance of the pattern that follows.+(
match one or more of the pattern list in parenthesis, (i.e. until item #7 below).*\/
matches anything before a literal "/
" char. |
which in this instance acts like a logical OR..*
matches anything after a literal ".
" -- that is, in bash
the ".
" is just a period char, and not a regex dot.)
end pattern list.}
end parameter expansion. With a string substitution, there's usually another /
there, followed by a replacement string. But since there's no /
there, the matched patterns are substituted with nothing; this deletes the matches.Relevant man bash
background:
${parameter/pattern/string} Pattern substitution. The pattern is expanded to produce a pat tern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the begin- ning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / fol lowing pattern may be omitted. If parameter is @ or *, the sub stitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the fol lowing sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns
I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.
The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)
From: http://technet.microsoft.com/en-us/library/ee681792.aspx:
"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."
Edit:
Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE
returned.
If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week
which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll
.
Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206
I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.
Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.
GoJS supports this, with its State Chart example, that supports dragging and dropping of elements, and editing of connections.
This answer is based off of Walter Northwoods' answer.
Other than the append
function, if by "multiple values" you mean another list, you can simply concatenate them like so.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
I don't think it is very important to find the location of Svcutil.exe. You can use Visual Studio Command prompt to execute directly without its absolute path,
Syntax:
svcutil.exe /language:[vb|cs] /out:[YourClassName].[cs|vb] /config:[YourAppConfigFile.config] [YourServiceAddress]
example:
svcutil.exe /language:cs /out:MyClientClass.cs /config:app.config http://localhost:8370/MyService/
i will explain Depth Details of interface and Abstract class.if you know overview about interface and abstract class, then first question arrive in your mind when we should use Interface and when we should use Abstract class. So please check below explanation of Interface and Abstract class.
When we should use Interface?
if you don't know about implementation just we have requirement specification then we go with Interface
When we should use Abstract Class?
if you know implementation but not completely (partially implementation) then we go with Abstract class.
Interface
every method by default public abstract means interface is 100% pure abstract.
Abstract
can have Concrete method and Abstract method, what is Concrete method, which have implementation in Abstract class, An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Interface
We cannot declared interface as a private, protected
Q. Why we are not declaring Interface a private and protected?
Because by default interface method is public abstract so and so that reason that we are not declaring the interface as private and protected.
Interface method
also we cannot declared interface as private,protected,final,static,synchronized,native.....
i will give the reason: why we are not declaring synchronized method because we cannot create object of interface and synchronize are work on object so and son reason that we are not declaring the synchronized method Transient concept are also not applicable because transient work with synchronized.
Abstract
we are happily use with public,private final static.... means no restriction are applicable in abstract.
Interface
Variables are declared in Interface as a by default public static final so we are also not declared variable as a private, protected.
Volatile modifier is also not applicable in interface because interface variable is by default public static final and final variable you cannot change the value once it assign the value into variable and once you declared variable into interface you must to assign the variable.
And volatile variable is keep on changes so it is opp. to final that is reason we are not use volatile variable in interface.
Abstract
Abstract variable no need to declared public static final.
i hope this article is useful.
I think you can use this code also: and you can manage your class css better
<style>
.navigationClass{
display: inline-block;
padding: 0px 0px 0px 6px;
background-color: whitesmoke;
border-radius: 2px;
}
</style>
<div id="header" class="row">
<div id="logo" class="col_12">And the winner is<span>n't...</span></div>
<div id="navigation" class="row">
<ul id="pirra">
<li><a href="#">Why?</a></li>
<li><a href="#">Synopsis</a></li>
<li><a href="#">Stills/Photos</a></li>
<li><a href="#">Videos/clips</a></li>
<li><a href="#">Quotes</a></li>
<li><a href="#">Quiz</a></li>
</ul>
</div>
<script>
$(document).ready(function() {
$('#navigation ul li').addClass('navigationClass'); //add class navigationClass to the #navigation .
});
</script>
if you really want to get rid of the scrollbar, split the information up into two separate pages.
Usability guidelines on scrollbars by Jakob Nielsen:
There are five essential usability guidelines for scrolling and scrollbars:
- Offer a scrollbar if an area has scrolling content. Don't rely on auto-scrolling or on dragging, which people might not notice.
- Hide scrollbars if all content is visible. If people see a scrollbar, they assume there's additional content and will be frustrated if they can't scroll.
- Comply with GUI standards and use scrollbars that look like scrollbars.
- Avoid horizontal scrolling on Web pages and minimize it elsewhere.
- Display all important information above the fold. Users often decide whether to stay or leave based on what they can see without scrolling. Plus they only allocate 20% of their attention below the fold.
To make your scrollbar only visible when it is needed (i.e. when there is content to scroll down to), use overflow: auto
.
I have connection string Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;
and even a .NET 3.5 program connects and execute SQL successfully.
But many people say .NET 4.0.2 or 4.5 is required.
The following code changes the hexadecimal string to a byte array by parsing the string byte-by-byte.
public static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
There's no built in Stopwatch utility but as of JSR-310 (Java 8 Time) you can do this simply.
ZonedDateTime now = ZonedDateTime.now();
// Do stuff
long seconds = now.until(ZonedDateTime.now(), ChronoUnit.SECONDS);
I haven't benchmarked this properly but I would guess using Guava's Stopwatch is more effective.
I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.
def check(count):
lowercase = 0
uppercase = 0
other = 0
low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
for n in count:
if n in low:
lowercase += 1
elif n in upper:
uppercase += 1
else:
other += 1
print("There are " + str(lowercase) + " lowercase letters.")
print("There are " + str(uppercase) + " uppercase letters.")
print("There are " + str(other) + " other elements to this sentence.")
I use Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);
. Hope this helps.
Breakdown:
Collection?.Any()
will return null
if Collection is null, and false
if Collection is empty.
Collection?.Any()??false
will give us false
if Collection is empty, and false
if Collection is null
.
Complement of that will give us IsEmptyOrNull
.
As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:
// 3. Pass the connection to a command object
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
//
// 4. Use the connection
//
By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).
Use MimeTypeMap package, which provides a huge two-way mapping of file extensions to mime types and mime types to file extensions
using MimeTypes;
Getting the mime type to an extension
Console.WriteLine("txt -> " + MimeTypeMap.GetMimeType("txt")); // "text/plain"
Getting the extension to a mime type
Console.WriteLine("audio/wav -> " + MimeTypeMap.GetExtension("audio/wav")); // ".wav"
GitHub Url: https://github.com/samuelneff/MimeTypeMap
a = [[1,'aa',3,12,'a','b','c','s'],[],[],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]
b=[]
for lng in range(len(a)):
if(len(a[lng])>=1):b.append(a[lng])
a=b
print(a)
Output:
[[1,'aa',3,12,'a','b','c','s'],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]
You need to modify the jenkins.xml file. Specifically you need to change
<arguments>-Xrs -Xmx256m
-Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle
-jar "%BASE%\jenkins.war" --httpPort=8080</arguments>
to
<arguments>-Xrs -Xmx2048m -XX:MaxPermSize=512m
-Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle
-jar "%BASE%\jenkins.war" --httpPort=8080</arguments>
You can also verify the Java options that Jenkins is using by installing the Jenkins monitor plugin via Manage Jenkins / Manage Plugins and then navigating to Managing Jenkins / Monitoring of Hudson / Jenkins master to use monitoring to determine how much memory is available to Jenkins.
If you are getting an out of memory error when Jenkins calls Maven, it may be necessary to set MAVEN_OPTS via Manage Jenkins / Configure System e.g. if you are running on a version of Java prior to JDK 1.8 (the values are suggestions):
-Xmx2048m -XX:MaxPermSize=512m
If you are using JDK 1.8:
-Xmx2048m
simply add + "<br />" +
is enough for a line break
An example that works and are compliant with all browsers :
var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...
change
});
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
to
})(jQuery); //<-- ADD THIS
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
This is needed because, you need to call the anonymous function that you created with
(function($){
and notice that it expects an argument that it will use internally as $
, so you need to pass a reference to the jQuery object.
Additionally, you will need to change all the this.
to $(this).
, except the first one, in which you do return this.each
In the first one (where you do not need the $()
) it is because in the plugin body, this
holds a reference to the jQuery object matching your selector, but anywhere deeper than that, this
refers to the specific DOM element, so you need to wrap it in $()
.
Full code at http://jsfiddle.net/gaby/NXESk/
You can also start a server without python using php interpreter.
E.g:
cd /your/path/to/website/root
php -S localhost:8000
This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).
This is what your are looking for:
from numpy import array
a=array([1,2,3])
b=array([4,5,6])
a + 1j*b
->array([ 1.+4.j, 2.+5.j, 3.+6.j])
I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.
The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".
Programmatically use : editText.setBackground(null)
From xml
use: android:background="@null"
This CSS seems to work in Safari and Chrome:
div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}
and in the body:
<div id="div2"><img src="image.jpg" ></div>
But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.
You have to find where the Git executable is and then add the folder to the PATH environment variable in file .bash_profile.
Using terminal:
Search for Git:
sudo find / -name git
Edit the .bash_profile file. Add:
PATH="<Directory of Git>:$PATH"
Git is back :-)
Anyway, I suggest you to install Git using MacPorts. In this way you can easily upgrade your Git instance to the newest release.
You used to be able to do this, but GitHub removed this feature at some point mid-2013. To achieve this locally, you can do:
git log -g --grep=STRING
(Use the -g
flag if you want to search other branches and dangling commits.)
-g, --walk-reflogs
Instead of walking the commit ancestry chain, walk reflog entries from
the most recent one to older ones.
If you have separate layout files for portrait and landscape modes and are getting an inflation error whenever you change orientation after clicking an item, there is most likely a discrepancy between your layout files.
When you get the error, is it only when you click the item in landscape mode or only in portrait mode or both? Does your TaskDetailsFragment activity use a layout file that could have discrepancies between landscape and portrait modes?
sudo npm install -g yarnpkg
npm WARN deprecated [email protected]: Please use the `yarn` package instead of `yarnpkg`
so this works for me
sudo npm install -g yarn
Some of these examples are more complicated than you might need. To remove a single slash, from anywhere (leading or trailing), you could get away with something as simple as this:
let no_trailing_slash_url = site.replace('/', '');
Complete example:
let site1 = "www.somesite.com";
let site2 = "www.somesite.com/";
function someFunction(site)
{
let no_trailing_slash_url = site.replace('/', '');
return no_trailing_slash_url;
}
console.log(someFunction(site2)); // www.somesite.com
Note that .replace(...)
returns a string, it does not modify the string it is called on.
If you want to redirect the output to a log file to look for errors or something. You can do something like this.
sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF
A helpful step in tracking down this problem is to identify which bind-address MySQL is actually set to. You can do this with netstat:
netstat -nat |grep :3306
This helped me zero in on my problem, because there are multiple mysql config files, and I had edited the wrong one. Netstat showed mysql was still using the wrong config:
ubuntu@myhost:~$ netstat -nat |grep :3306
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
So I grepped the config directories for any other files which might be overriding my setting and found:
ubuntu@myhost:~$ sudo grep -R bind /etc/mysql
/etc/mysql/mysql.conf.d/mysqld.cnf:bind-address = 127.0.0.1
/etc/mysql/mysql.cnf:bind-address = 0.0.0.0
/etc/mysql/my.cnf:bind-address = 0.0.0.0
D'oh! This showed me the setting I had adjusted was the wrong config file, so I edited the RIGHT file this time, confirmed it with netstat, and was in business.
Here is a UDF I built to detectc columns with extended ascii charaters. It is quick and you can extended the character set you want to check. The second parameter allows you to switch between checking anything outside the standard character set or allowing an extended set:
create function [dbo].[udf_ContainsNonASCIIChars]
(
@string nvarchar(4000),
@checkExtendedCharset bit
)
returns bit
as
begin
declare @pos int = 0;
declare @char varchar(1);
declare @return bit = 0;
while @pos < len(@string)
begin
select @char = substring(@string, @pos, 1)
if ascii(@char) < 32 or ascii(@char) > 126
begin
if @checkExtendedCharset = 1
begin
if ascii(@char) not in (9,124,130,138,142,146,150,154,158,160,170,176,180,181,183,184,185,186,192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,209,210,211,212,213,214,216,217,218,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255)
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
else
begin
select @pos = @pos + 1
end
end
else
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
end
else
begin
select @pos = @pos + 1
end
end
return @return;
end
USAGE:
select Address1
from PropertyFile_English
where udf_ContainsNonASCIIChars(Address1, 1) = 1
This should be working. Please have a look at this fiddle.
$(function() {
$( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code
Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
One possible solution that I use is to use python3. It seems to solve many utf issues.
Sorry for the late answer, but it may help people in the future.
For example,
#!/usr/bin/env python3
import json
# your code follows
Here
{int y=((year-1)%100);int c=(year-1)/100;}
you declare and initialize the variables y, c
, but you don't used them at all before they run out of scope. That's why you get the unused
message.
Later in the function, y, c
are undeclared, because the declarations you made only hold inside the block they were made in (the block between the braces {...}
).
The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
Here is Whatangs answer if you want to get both sorted lists (python3).
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Zx, Zy = zip(*[(x, y) for x, y in sorted(zip(Y, X))])
print(list(Zx)) # [0, 0, 0, 1, 1, 1, 1, 2, 2]
print(list(Zy)) # ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Just remember Zx and Zy are tuples. I am also wandering if there is a better way to do that.
Warning: If you run it with empty lists it crashes.
String.contains
works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.
Note that String.contains
does not check for word boundary; it simply checks for substring.
Regex is more powerful than String.contains
, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.
Use String.matches
with the following regex:
"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"
The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):
(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*
The \b
checks for word boundary, so that you don't get a match for restores store products
. Note that stores 3store_product
is also rejected, since digit and _
are considered part of a word, but I doubt this case appear in natural text.
Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product
will not match the regex above, since you are searching for the word store
without s
.
.
normally match any character except a number of new line characters. (?s)
at the beginning makes .
matches any character without exception (thanks to Tim Pietzcker for pointing this out).
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
Could be that using the numeral code is more universal, as it's a direct reference to a character in the html entity table, but I guess they both work everywhere. The first notation is just massively easier to remember for a lot of characters.
Try this:
arr = [5, 6, 7, 8]
arr.inject{ |sum, el| sum + el }.to_f / arr.size
=> 6.5
Note the .to_f
, which you'll want for avoiding any problems from integer division. You can also do:
arr = [5, 6, 7, 8]
arr.inject(0.0) { |sum, el| sum + el } / arr.size
=> 6.5
You can define it as part of Array
as another commenter has suggested, but you need to avoid integer division or your results will be wrong. Also, this isn't generally applicable to every possible element type (obviously, an average only makes sense for things that can be averaged). But if you want to go that route, use this:
class Array
def sum
inject(0.0) { |result, el| result + el }
end
def mean
sum / size
end
end
If you haven't seen inject
before, it's not as magical as it might appear. It iterates over each element and then applies an accumulator value to it. The accumulator is then handed to the next element. In this case, our accumulator is simply an integer that reflects the sum of all the previous elements.
Edit: Commenter Dave Ray proposed a nice improvement.
Edit: Commenter Glenn Jackman's proposal, using arr.inject(:+).to_f
, is nice too but perhaps a bit too clever if you don't know what's going on. The :+
is a symbol; when passed to inject, it applies the method named by the symbol (in this case, the addition operation) to each element against the accumulator value.
height:100% works if the parent container has a specified height property else, it won't work
For me, it was wrong login and password.
If an URL pattern starts with /
, then it's relative to the context root. The /Admin/*
URL pattern would only match pages on http://localhost:8080/EMS2/Admin/*
(assuming that /EMS2
is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*
, so your URL pattern never matches.
You need to prefix your URL patterns with /faces/Html
as well like so:
<url-pattern>/faces/Html/Admin/*</url-pattern>
You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html
path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml
.
Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping>
with multiple <url-pattern>
entries:
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>
The following code emulates exactly the behavior of pointers in C:
from collections import deque # more efficient than list for appending things
pointer_storage = deque()
pointer_address = 0
class new:
def __init__(self):
global pointer_storage
global pointer_address
self.address = pointer_address
self.val = None
pointer_storage.append(self)
pointer_address += 1
def get_pointer(address):
return pointer_storage[address]
def get_address(p):
return p.address
null = new() # create a null pointer, whose address is 0
Here are examples of use:
p = new()
p.val = 'hello'
q = new()
q.val = p
r = new()
r.val = 33
p = get_pointer(3)
print(p.val, flush = True)
p.val = 43
print(get_pointer(3).val, flush = True)
But it's now time to give a more professional code, including the option of deleting pointers, that I've just found in my personal library:
# C pointer emulation:
from collections import deque # more efficient than list for appending things
from sortedcontainers import SortedList #perform add and discard in log(n) times
class new:
# C pointer emulation:
# use as : p = new()
# p.val
# p.val = something
# p.address
# get_address(p)
# del_pointer(p)
# null (a null pointer)
__pointer_storage__ = SortedList(key = lambda p: p.address)
__to_delete_pointers__ = deque()
__pointer_address__ = 0
def __init__(self):
self.val = None
if new.__to_delete_pointers__:
p = new.__to_delete_pointers__.pop()
self.address = p.address
new.__pointer_storage__.discard(p) # performed in log(n) time thanks to sortedcontainers
new.__pointer_storage__.add(self) # idem
else:
self.address = new.__pointer_address__
new.__pointer_storage__.add(self)
new.__pointer_address__ += 1
def get_pointer(address):
return new.__pointer_storage__[address]
def get_address(p):
return p.address
def del_pointer(p):
new.__to_delete_pointers__.append(p)
null = new() # create a null pointer, whose address is 0
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
JavaScript has a Number
type which is a 64 bit floating point number*.
If you're looking to convert a string to a number, use
parseInt
or parseFloat
. If using parseInt
, I'd recommend always passing the radix too.+
operator e.g. +"123456"
Number
constructor e.g. var n = Number("12343")
*there are situations where the number will internally be held as an integer.
I have it working in only JavaScript. Firefox won't let you update the keyCode, so all you can do is trap keyCode 13 and force it to focus on the next element by tabIndex as if keyCode 9 was pressed. The tricky part is finding the next tabIndex. I have tested this only on IE8-IE10 and Firefox and it works:
function ModifyEnterKeyPressAsTab(event)
{
var caller;
var key;
if (window.event)
{
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
}
else
{
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
if (key == 13) //Enter key was pressed.
{
cTab = caller.tabIndex; //caller tabIndex.
maxTab = 0; //highest tabIndex (start at 0 to change)
minTab = cTab; //lowest tabIndex (this may change, but start at caller)
allById = document.getElementsByTagName("input"); //Get input elements.
allByIndex = []; //Storage for elements by index.
c = 0; //index of the caller in allByIndex (start at 0 to change)
i = 0; //generic indexer for allByIndex;
for (id in allById) //Loop through all the input elements by id.
{
allByIndex[i] = allById[id]; //Set allByIndex.
tab = allByIndex[i].tabIndex;
if (caller == allByIndex[i])
c = i; //Get the index of the caller.
if (tab > maxTab)
maxTab = tab; //Get the highest tabIndex on the page.
if (tab < minTab && tab >= 0)
minTab = tab; //Get the lowest positive tabIndex on the page.
i++;
}
//Loop through tab indexes from caller to highest.
for (tab = cTab; tab <= maxTab; tab++)
{
//Look for this tabIndex from the caller to the end of page.
for (i = c + 1; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == tab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Look for the next tabIndex from the start of page to the caller.
for (i = 0; i < c; i++)
{
if (allByIndex[i].tabIndex == tab + 1)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Continue searching from the caller for the next tabIndex.
}
//The caller was the last element with the highest tabIndex,
//so find the first element with the lowest tabIndex.
for (i = 0; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == minTab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
}
}
To use this code, add it to your html input tag:
<input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >
Or add it to an element in javascript:
document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;
A couple other notes:
I only needed it to work on my input elements, but you could extend it to other document elements if you need to. For this, getElementsByClassName is very helpful, but that is a whole other topic.
A limitation is that it only tabs between the elements that you have added to your allById array. It does not tab around to the other things that your browser might, like toolbars and menus outside your html document. Perhaps this is a feature instead of a limitation. If you like, trap keyCode 9 and this behavior will work with the tab key too.
You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:
**
operator does exponentiation. a ** b
is a
raised to the b
power. The same **
symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).^
operator does a binary xor. a ^ b
will return a value with only the bits set in a
or in b
but not both. This one is simple!%
operator is mostly to find the modulus of two integers. a % b
returns the remainder after dividing a
by b
. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b
, rather than the same sign as a
. The same operator is also used for the "old" style of string formatting, so a % b
can return a string if a
is a format string and b
is a value (or tuple of values) which can be inserted into a
.//
operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b)
. In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /
). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division
at the top of your files. I strongly recommend it!)You should move your switch into the template by using the 'ng-switch' directive:
module.directive('testForm', function() {
return {
restrict: 'E',
controllerAs: 'form',
controller: function ($scope) {
console.log("Form controller initialization");
var self = this;
this.fields = {};
this.addField = function(field) {
console.log("New field: ", field);
self.fields[field.name] = field;
};
}
}
});
module.directive('formField', function () {
return {
require: "^testForm",
template:
'<div ng-switch="field.fieldType">' +
' <span>{{title}}:</span>' +
' <input' +
' ng-switch-when="text"' +
' name="{{field.name}}"' +
' type="text"' +
' ng-model="field.value"' +
' />' +
' <select' +
' ng-switch-when="select"' +
' name="{{field.name}}"' +
' ng-model="field.value"' +
' ng-options="option for option in options">' +
' <option value=""></option>' +
' </select>' +
'</div>',
restrict: 'E',
replace: true,
scope: {
fieldType: "@",
title: "@",
name: "@",
value: "@",
options: "=",
},
link: function($scope, $element, $attrs, form) {
$scope.field = $scope;
form.addField($scope);
}
};
});
It can be use like this:
<test-form>
<div>
User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
</div>
<form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
<form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
<form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>
rekaszeru
I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..
Im using a EditText as an example
// GIVE TARGET TEXT BOX A NAME
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// STRING TO REPLACE
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// REPLACE STRINGS WITH RETURNED STRINGS
String returnedString = textBoxText.replace( oldText, newText );
// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX
textbox.setText(returnedString);
This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !
Obviously this example requires that you have a EditText with the ID set to your_textboxID
Updated : Angular is now providing the pipe for lopping through the json Object via keyvalue
:
<div *ngFor="let item of myDict | keyvalue">
{{item.key}}:{{item.value}}
</div>
WORKING DEMO , and for more detail Read
Previously (For Older Version) : Till now the best / shortest answer I found is ( Without any Pipe Filter or Custom function from Component Side )
Component side :
objectKeys = Object.keys;
Template side :
<div *ngFor='let key of objectKeys(jsonObj)'>
Key: {{key}}
<div *ngFor='let obj of jsonObj[key]'>
{{ obj.title }}
{{ obj.desc }}
</div>
</div>
While using Spring Boot 2.2 I run into a similiar error message and while googling my error message
No converter for [class java.util.ArrayList] with preset Content-Type 'null'
this question here is on top, but all answers here did not work for me, so I think it's a good idea to add the answer I found myself:
I had to add the following dependencies to the pom.xml
:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
After this I need to add the following to the WebApplication class:
@SpringBootApplication
public class WebApplication
{
// ...
@Bean
public HttpMessageConverter<Object> createXmlHttpMessageConverter()
{
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xstreamMarshaller.setAutodetectAnnotations(true);
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
}
Last but not least within my @Controller
I used:
@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType. APPLICATION_JSON_VALUE})
@ResponseBody
public List<MeterTypeEntity> listXmlJson(final Model model)
{
return this.service.list();
}
So now I got JSON and XML return values depending on the requests Accept
header.
To make the XML output more readable (remove the complete package name from tag names) you could also add @XStreamAlias
the following to your entity class:
@Table("ExampleTypes")
@XStreamAlias("ExampleType")
public class ExampleTypeEntity
{
// ...
}
Hopefully this will help others with the same problem.
You could use a CSS pre-processor to do your skinning. With Sass you can do something similar to this:
_theme1.scss:
$theme-primary-color: #a00;
$theme-secondary-color: #d00;
// etc.
_theme2.scss:
$theme-primary-color: #666;
$theme-secondary-color: #ccc;
// etc.
styles.scss:
// import whichever theme you want to use
@import 'theme2';
-webkit-box-shadow: inset 0px 0px 2px $theme-primary-color;
-moz-box-shadow: inset 0px 0px 2px $theme-primary-color;
If it's not site wide theming but class based theming you need, then you can do this: http://codepen.io/jjenzz/pen/EaAzo
I created a small working example that copies a source folder to another destination folder in just a few steps (based on shift66's answer using ncp):
Step 1 - Install ncp module:
npm install ncp --save
Step 2 - create copy.js (modify the srcPath and destPath variables to whatever you need):
var path = require('path');
var ncp = require('ncp').ncp;
ncp.limit = 16;
var srcPath = path.dirname(require.main.filename); // Current folder
var destPath = '/path/to/destination/folder'; // Any destination folder
console.log('Copying files...');
ncp(srcPath, destPath, function (err) {
if (err) {
return console.error(err);
}
console.log('Copying files complete.');
});
Step 3 - run
node copy.js
The title of your question is:
How to join a slice of strings into a single string?
but in fact, reg
is not a slice, but a length-three array. [...]string
is just syntactic sugar for (in this case) [3]string
.
To get an actual slice, you should write:
reg := []string {"a","b","c"}
(Try it out: https://play.golang.org/p/vqU5VtDilJ.)
Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:]
, like so:
fmt.Println(strings.Join(reg[:], ","))
(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...
Ctrl+Shift+P
Package Control: Remove Package
If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.
First navigate to
C:\users\[Name]\AppData\Roaming\Sublime Text [version]\
There will be 4 directories:
First open ..\Packages folder and locate the folder named the same as your package; Delete it.
Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user
Third, locate the line where the package name you want to "uninstall"
{
"installed_packages":
[
"Alignment",
"All Autocomplete",
"AngularJS",
"AutoFileName",
"BracketHighlighter",
"Browser Support",
"Case Conversion",
"ColorPicker",
"Emmet",
"FileDiffs",
"Format SQL",
"Git",
"Github Tools",
"HTML-CSS-JS Prettify",
"HTML5",
"HTMLBeautify",
"jQuery",
"JsFormat",
"JSHint",
"JsMinifier",
"LiveReload",
"LoremIpsum",
"LoremPixel",
"Oracle PL SQL",
"Package Control",
"Placehold.it Image Tag Generator",
"Placeholders",
"Prefixr",
"Search Stack Overflow",
"SublimeAStyleFormatter",
"SublimeCodeIntel",
"Tag",
"Theme - Centurion",
"TortoiseSVN",
"Zen Tabs"
]
}
NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.
Thus concludes the easiest way to remove or Install a Sublime Text Package.
You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.
So try:
sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
If this doesn't work, try adapting the permissions:
sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
For generating the KML file from your CSV file (or XLS), you can use MyGeodata online GIS Data Converter. Here is the CSV to KML How-To.
The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1
Can't copy the icons here, but here are the descriptions:
Show: Present the content in the detail or master area depending on the content of the screen.
If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.
Show Detail: Present the content in the detail area.
If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.
Present Modally: Present the content modally.
Present as Popover: Present the content as a popover anchored to an existing view.
Custom: Create your own behaviors by using a custom segue.
If you like php, take a look at php.JS - JavaScript explode
Or in normal JavaScript functionality: `
var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
I would call it nib.py. And I would also name the class Nib.
In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following:
from nib import Nib
from foo import Foo
from spam.eggs import Eggs, FriedEggs
It's a bit like emulating the Java way. One class per file. But with the added flexibility, that you can allways add another class to a single file if it makes sense.
Delegates and Datasources of UICollectionView
//MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
configureCell(cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.blackColor()
//Customise your cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
Supports entering y|ye|yes and case insensitive.
switch -regex ($someString.ToLower()) {
"^y(es?)?$" {
"You entered Yes."
}
default { "You entered No." }
}
I tried to use dplyr::rename and I get an error:
occ_5d <- dplyr::rename(occ_5d, rowname='code_5d')
Error: Unknown column `code_5d`
Call `rlang::last_error()` to see a backtrace
I instead used the base R function which turns out to be quite simple and effective:
names(occ_5d)[1] = "code_5d"
one url to the same view! like so!
urls.py
url(r'^$', views.landing.as_view(), name = 'landing'),
views.py
class landing(View):
template_name = '/home.html'
form_class1 = forms.pynamehere1
form_class2 = forms.pynamehere2
def get(self, request):
form1 = self.form_class1(None)
form2 = self.form_class2(None)
return render(request, self.template_name, { 'register':form1, 'login':form2,})
def post(self, request):
if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
## do what ever you want to do for first function ####
if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
## do what ever you want to do for second function ####
## return def post###
return render(request, self.template_name, {'form':form,})
/home.html
<!-- #### form 1 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ register.as_p }}
<button type="submit" name="htmlsubmitbutton1">Login</button>
</form>
<!--#### form 2 #### -->
<form action="" method="POST" >
{% csrf_token %}
{{ login.as_p }}
<button type="submit" name="htmlsubmitbutton2">Login</button>
</form>
Double quote (" ") the entire URL
.It works.
curl "http://www.mysite.com?name=john&passwd=@31&3*J"
Looks like PILlow may have changed tostring()
to tobytes()
. When trying to extract RGBA pixels to get them into an OpenGL texture, the following worked for me (within the glTexImage2D
call which I omit for brevity).
from PIL import Image
img = Image.open("mandrill.png").rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
# use img.convert("RGBA").tobytes() as texels
I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:
public static class Extensions
{
public static int IndexOf<T>(
this IEnumerable<T> list,
Predicate<T> condition) {
int i = -1;
return list.Any(x => { i++; return condition(x); }) ? i : -1;
}
}
void Main()
{
TestGetsFirstItem();
TestGetsLastItem();
TestGetsMinusOneOnNotFound();
TestGetsMiddleItem();
TestGetsMinusOneOnEmptyList();
}
void TestGetsFirstItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("a"));
// Assert
if(index != 0)
{
throw new Exception("Index should be 0 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsLastItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("d"));
// Assert
if(index != 3)
{
throw new Exception("Index should be 3 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnNotFound()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnEmptyList()
{
// Arrange
var list = new string[] { };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMiddleItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d", "e" };
// Act
int index = list.IndexOf(item => item.Equals("c"));
// Assert
if(index != 2)
{
throw new Exception("Index should be 2 but is: " + index);
}
"Test Successful".Dump();
}
I had this error in Visual Studio 2013, with an SSIS project. I set Project, Properties, Debugging, Run64BitRuntime = false and then the SSIS package ran. However, when I deployed the package to the server I had to set the value to true (Server is 64 bit Windows 2012 / Sql 2014 ).
I think the reasoning behind this is that Visual Studio is a 32 bit application.
Building on other answers, here's another variant that takes an optional flag to choose a strategy (keep first occurrence or keep last):
Without extending Array.prototype
function unique(arr, keepLast) {
return arr.filter(function (value, index, array) {
return keepLast ? array.indexOf(value, index + 1) < 0 : array.indexOf(value) === index;
});
};
// Usage
unique(['a', 1, 2, '1', 1, 3, 2, 6]); // -> ['a', 1, 2, '1', 3, 6]
unique(['a', 1, 2, '1', 1, 3, 2, 6], true); // -> ['a', '1', 1, 3, 2, 6]
Extending Array.prototype
Array.prototype.unique = function (keepLast) {
return this.filter(function (value, index, array) {
return keepLast ? array.indexOf(value, index + 1) < 0 : array.indexOf(value) === index;
});
};
// Usage
['a', 1, 2, '1', 1, 3, 2, 6].unique(); // -> ['a', 1, 2, '1', 3, 6]
['a', 1, 2, '1', 1, 3, 2, 6].unique(true); // -> ['a', '1', 1, 3, 2, 6]
Quickfix
I had similar issue and I resolved it doing the following
Alternative 1: Disable sandbox
As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.
Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script:
Alternative 2: Disable script security
As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:
-Dpermissive-script-security.enabled=true
So you jenkins.xml will look something like this:
<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>
Make sure you know what you are doing if you implement this!
In fact you need the # (hashtag) for non HTML5 browsers.
Otherwise they will just do an HTTP call to the server at the mentioned href. The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.
You can use $locationProvider.html5Mode(true)
to tell angular to use HTML5 strategy if available.
Here the list of browser that support HTML5 strategy: http://caniuse.com/#feat=history
If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:
interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim
Encrypt something with the public key, and see which private key decrypts it.
This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.
Use
DefaultTableModel model = (DefaultTableModel) MyJTable.getModel();
Vector row = new Vector();
row.add("Enter data to column 1");
row.add("Enter data to column 2");
row.add("Enter data to column 3");
model.addRow(row);
get the model with DefaultTableModel modelName = (DefaultTableModel) JTabelName.getModel();
Create a Vector with Vector vectorName = new Vector();
add so many row.add
as comumns
add soon just add it with modelName.addRow(Vector name);
To fix the indentation and formatting in all files of your solution:
2
);This will recursively open and save all files in your solution, setting the indentation you defined above.
You might want to check other programming languages tabs (Options...) for Code Style > Formatting as well.
http://callmenick.com/2014/02/18/create-an-animated-resizing-header-on-scroll/
This link has a great tutorial with source code that you can play with, showing how to make elements within the header smaller as well as the header itself.
Use .stem
from pathlib
in Python 3.4+
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
will return
'file'
Note that if your file has multiple extensions .stem
will only remove the last extension. For example, Path('file.tar.gz').stem
will return 'file.tar'
.
+"\n" + can be added in print command to display the code block after it in next line
E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.
You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
public V getDefault(K key, V defaultValue) {
if (containsKey(key)) {
return get(key);
}
return defaultValue;
}
}
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).
To complement Michael's answer, and according to this answer, a safe way to deal with the problem is to use the following arguments:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -XX:+UseConcMarkSweepGC
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
In my case, i got this error because i was just in the wrong directory. So node couldnt find the module that i wanted to run. Just be sure your node file is in your Desktop directory.
You could use AsyncTask
, you'll have to customize to fit your needs, but something like the following
Async task has three primary methods:
onPreExecute()
- most commonly used for setting up and starting a progress dialog
doInBackground()
- Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).
onPostExecute()
- Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.First we will start the class, initialize a String
to hold the results outside of the methods but inside the class, then run the onPreExecute()
method setting up a simple progress dialog.
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
Then we need to set up the connection and how we want to handle the response:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
If you're wondering why the original answer is not working. Well it might be that you're not in the home directory. Try this:
$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
Had the same problem in Eclipse STS. Changing the scope in the pom from "provided" to "compile" fixed the problem and when I changed it back everything was still OK.
You can just:
var f = new Date(from.split('-').reverse().join('/'));
You cannot launch a web page from an elevated application. This will raise a 0x800004005 exception, probably because explorer.exe and the browser are running non-elevated.
To launch a web page from an elevated application in a non-elevated web browser, use the code made by Mike Feng. I tried to pass the URL to lpApplicationName but that didn't work. Also not when I use CreateProcessWithTokenW with lpApplicationName = "explorer.exe" (or iexplore.exe) and lpCommandLine = url.
The following workaround does work: Create a small EXE-project that has one task: Process.Start(url), use CreateProcessWithTokenW to run this .EXE. On my Windows 8 RC this works fine and opens the web page in Google Chrome.
This worked for me.
sudo adduser <username> www-data
sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rwX /var/www
Then logout or reboot.
If SELinux
complains, try the following
sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www(/.*)?'
sudo restorecon -Rv '/var/www(/.*)?'
In case of lubuntu 14.04 use
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
P.S-no need to restart the system.
From the doc for path.resolve
:
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
But path.join
keeps trailing slashes
So
__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'
Write this code in your on backpressed override method
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
timespec_get
from C11
Returns up to nanoseconds, rounded to the resolution of the implementation.
Looks like an ANSI ripoff from POSIX' clock_gettime
.
Example: a printf
is done every 100ms on Ubuntu 15.10:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static long get_nanos(void) {
struct timespec ts;
timespec_get(&ts, TIME_UTC);
return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}
int main(void) {
long nanos;
long last_nanos;
long start;
nanos = get_nanos();
last_nanos = nanos;
start = nanos;
while (1) {
nanos = get_nanos();
if (nanos - last_nanos > 100000000L) {
printf("current nanos: %ld\n", nanos - start);
last_nanos = nanos;
}
}
return EXIT_SUCCESS;
}
The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says":
If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock. (321)
321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.
C++11 also got std::chrono::high_resolution_clock
: C++ Cross-Platform High-Resolution Timer
glibc 2.21 implementation
Can be found under sysdeps/posix/timespec_get.c
as:
int
timespec_get (struct timespec *ts, int base)
{
switch (base)
{
case TIME_UTC:
if (__clock_gettime (CLOCK_REALTIME, ts) < 0)
return 0;
break;
default:
return 0;
}
return base;
}
so clearly:
only TIME_UTC
is currently supported
it forwards to __clock_gettime (CLOCK_REALTIME, ts)
, which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html
Linux x86-64 has a clock_gettime
system call.
Note that this is not a fail-proof micro-benchmarking method because:
man clock_gettime
says that this measure may have discontinuities if you change some system time setting while your program runs. This should be a rare event of course, and you might be able to ignore it.
this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.
For those reasons getrusage()
might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.
More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?
I don't know why you should think it is dirty... because of the exception? if you want a oneliner, here it is:
thing_index = thing_list.index(elem) if thing_list.count(elem) else -1
but i would advise against using it; I think Ross Rogers solution is the best, use an object to encapsulate your desiderd behaviour, don't try pushing the language to its limits at the cost of readability.
Note however:
If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.
A fix and elaboration of @Fredrik Mörk answer.
strings.resx
Resource file to your project (or a different filename)Access Modifier
to Public
(in the opened strings.resx
file tab)Hello
, value Hello
)Visual Studio auto-generates a respective strings
class, which is actually placed in strings.Designer.cs
. The class is in the same namespace that you would expect a newly created .cs
file to be placed in.
This code always prints Hello
, because this is the default resource and no language-specific resources are available:
Console.WriteLine(strings.Hello);
Now add a new language-specific resource:
strings.fr.resx
(for French)Hello
, value Salut
)The following code prints Salut
:
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(strings.Hello);
What resource is used depends on Thread.CurrentThread.CurrentUICulture
. It is set depending on Windows UI language setting, or can be set manually like in this example. Learn more about this here.
You can add country-specific resources like strings.fr-FR.resx
or strings.fr-CA.resx
.
The string to be used is determined in this priority order:
strings.fr-CA.resx
strings.fr.resx
strings.resx
Note that language-specific resources generate satellite assemblies.
Also learn how CurrentCulture
differs from CurrentUICulture
here.
The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.
string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");
properly returns file:///C:/my%20example?.txt
The .before
argument in dplyr::add_row
can be used to specify the row.
dplyr::add_row(
cars,
speed = 0,
dist = 0,
.before = 3
)
#> speed dist
#> 1 4 2
#> 2 4 10
#> 3 0 0
#> 4 7 4
#> 5 7 22
#> 6 8 16
#> ...
This took me way too long to figure out. I can't believe nobody has mentioned center tags.
Ex:
<center><img src = "yourimage.png"/></center>
and if you want to resize the image to a percentage:
<center><img src = "yourimage.png" width = "75%"/></center>
GG America
I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass
annotation (optimize later).
Example of optimization using the @BeforeClass
setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass
and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.
Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
Perhaps you just want to stop executing a long script at some point. ie. like you want to hard code an exit() in C or Python.
print("this is the last message")
stop()
print("you should not see this")
This:
print "\n"
is printing out two \n
characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a ,
like you use in print a,
. Simply use
print
instead.
You need to implement your own MessageBodyReader
and MessageBodyWriter
for your class Lorg.shoppingsite.model.entity.jpa.User
.
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyReader<T extends Object> {
public boolean isReadable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public T readFrom(Class<T> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
package javax.ws.rs.ext;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
public interface MessageBodyWriter<T extends Object> {
public boolean isWriteable(Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public long getSize(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType);
public void writeTo(T t,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"
It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.
So I would say no.
However, there is no guarantee that some change in the future will not introduce a problem.
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem
for more info Redim
The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask.
However, you can use send_from_directory
to send files from a directory, which can be pretty convenient in some situations:
from flask import Flask, request, send_from_directory
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/js/<path:path>')
def send_js(path):
return send_from_directory('js', path)
if __name__ == "__main__":
app.run()
Do not use send_file
or send_static_file
with a user-supplied path.
send_static_file
example:
from flask import Flask, request
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/')
def root():
return app.send_static_file('index.html')
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
Scrollbars etc have an effect on the window size so you may want to tweak to desired size.
Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:
Example:
bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;
Just make a sample 'Hello World' Program and try to compile it using "g++ sam.cpp" in terminal, and it will ask you if you wish to download the g++ package. Press y to install.
select * from
(select
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1
You can use the Regex.Split method, something like this:
Regex regex = new Regex(@"\bis\b");
string[] substrings = regex.Split("This is a sentence");
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.
Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.
As of Ansible 2.0 there seems to be an option called strategy
on a playbook. When setting the strategy to free
, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.
It looks something like this (taken from the above link):
- hosts: all
strategy: free
tasks:
...
Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.
EDIT:
It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.
This includes specifying async
and poll
on a task. The following is taken from the 2nd link I mentioned:
- name: simulate long running op, allow to run for 45 sec, fire and forget
command: /bin/sleep 15
async: 45
poll: 0
I guess you can specify longer async
times if your task is lengthy. You can probably define your three concurrent task this way.
Swift3 : heightForHeaderInSection works with 0, you just have to make sure header is set to clipsToBounds.
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
if you don't set clipsToBounds hidden header will be visible when scrolling.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.clipsToBounds = true
}
try
enum E {
E1, E2, E3
}
public static void main(String[] args) throws Exception {
List<E> list = Arrays.asList(E.values());
System.out.println(list);
}
Sparky's answer is one standard way to solve this problem, but as I also wrote in my comment, you run the risk of overflows. This can be solved by using a wider type, but what if you want to divide long long
s?
Nathan Ernst's answer provides one solution, but it involves a function call, a variable declaration and a conditional, which makes it no shorter than the OPs code and probably even slower, because it is harder to optimize.
My solution is this:
q = (x % y) ? x / y + 1 : x / y;
It will be slightly faster than the OPs code, because the modulo and the division is performed using the same instruction on the processor, because the compiler can see that they are equivalent. At least gcc 4.4.1 performs this optimization with -O2 flag on x86.
In theory the compiler might inline the function call in Nathan Ernst's code and emit the same thing, but gcc didn't do that when I tested it. This might be because it would tie the compiled code to a single version of the standard library.
As a final note, none of this matters on a modern machine, except if you are in an extremely tight loop and all your data is in registers or the L1-cache. Otherwise all of these solutions will be equally fast, except for possibly Nathan Ernst's, which might be significantly slower if the function has to be fetched from main memory.
If the thing you want to compare is performance of file copying, then for the channel test you should do this instead:
final FileInputStream inputStream = new FileInputStream(src);
final FileOutputStream outputStream = new FileOutputStream(dest);
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();
This won't be slower than buffering yourself from one channel to the other, and will potentially be massively faster. According to the Javadocs:
Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
I got this problem after moving a project and deleting it's packages folder. Nuget was showning that MSTest.TestAdapter and MSTest.TestFramework v 1.3.2 was installed. The fix seemed to be to open VS as administrator and build After that I was able to re-open and build without having admin priviledge.
Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a
(an es6 version, and a .js version which can be included in a script tag)
You can use it as follows:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
// you can also now upload this blob using an XHR.
});
};
</script>
It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.
(it also ignores gif images - in case they're animated)
overflow-x: scroll;
overflow-y: hidden;
EDIT:
It works for me:
<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
<div style='width:400px;height:250px'></div>
</div>
The default .NET ServicePointManager.SecurityProtocol
uses SSLv3 and TLS. If you are accessing an Apache server, there is a config variable called SSLProtocol
which defaults to TLSv1.2. You can either set the ServicePointManager.SecurityProtocol
to use the appropriate protocol supported by your web server or change your Apache config to allow all protocols like this SSLProtocol
all
.
I know this is coming a bit late, but a colleague of mine figured something out:
figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1' '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off
We came across many situation where we need to check error and error logs to figure out issue we are facing we can check by possibly following method:
1.) On blank screen Some time we got nothing but blank screen instead of our site or message written The website encountered an unexpected error. Please try again later , so we can Print Errors to the Screen by adding
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
in index.php
at top.;
2.) We should enable optional core module for Database Logging at /admin/build/modules, and then we can check logs your_domain_name/admin/reports/dblog
3.) We can use drush command also to check logs drush watchdog-show it will show recent ten message
or if we want to continue showing logs with more information we can user
drush watchdog-show --tail --full.
4.) Also we can enable core Syslog module this module logs events of operating system of any web server.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
Post installation instructions are not clear:
==> Source [/.../google-cloud-sdk/completion.bash.inc] in your profile to enable shell command completion for gcloud.
==> Source [/.../google-cloud-sdk/path.bash.inc] in your profile to add the Google Cloud SDK command line tools to your $PATH.
I had to actually add the following lines of code in my .bash_profile
for gcloud
to work:
source '/.../google-cloud-sdk/completion.bash.inc'
source '/.../google-cloud-sdk/path.bash.inc'
Below is my script for converting all files recursively. You can specify folders or files to exclude.
$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"
Function Dos2Unix {
[CmdletBinding()]
Param([Parameter(ValueFromPipeline)] $fileName)
Write-Host -Nonewline "."
$fileContents = Get-Content -raw $fileName
$containsCrLf = $fileContents | %{$_ -match "\r\n"}
If($containsCrLf -contains $true)
{
Write-Host "`r`nCleaing file: $fileName"
set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
}
}
Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }
use es6 deconstruction array with the spread operator
var last = [...yourArray].pop();
note that yourArray doesn't change.
I had such dependancy in build.gradle -
compile 'com.android.support:recyclerview-v7:+'
But it causes unstable builds. Ensure it works ok for you, and look in your android sdk manager for current version of support lib available, and replace this dependency with
def final RECYCLER_VIEW_VER = '23.1.1'
compile "com.android.support:recyclerview-v7:${RECYCLER_VIEW_VER}"
function useOnceCall(cb, condition = true) {
const isCalledRef = React.useRef(false);
React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
cb();
}
}, [cb, condition]);
}
and use it.
useOnceCall(()=>{
console.log('called');
})
or
useOnceCall(()=>{
console.log('isLoading');
},isLoading);
I know this is a very old question but just in case it helps someone, I found when using the onmousemove event to detect the cancel, that it was necessary to test for two or more such events in a short space of time. This was because single onmousemove events are generated by the browser (Chrome 65) each time the cursor is moved out of the select file dialog window and each time it is moved out of the main window and back in. A simple counter of mouse movement events coupled with a short duration timeout to reset the counter back to zero worked a treat.
Use count(*)
declare
cnt integer;
begin
SELECT count(*) INTO cnt
FROM people
WHERE person_id = my_person_id;
IF cnt > 0 THEN
-- Do something
END IF;
Edit (for the downvoter who didn't read the statement and others who might be doing something similar)
The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)
Because of that where
clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.
eventcreate2 allows you to create custom logs, where eventcreate does not.
Why do you need it to be of type GenericWebApplicationContext
?
I think you can probably work with any ApplicationContext type.
Usually you would use an init method (in addition to your setter method):
@PostConstruct
public void init(){
AutowireCapableBeanFactory bf = this.applicationContext
.getAutowireCapableBeanFactory();
// wire stuff here
}
And you would wire beans by using either
AutowireCapableBeanFactory.autowire(Class, int mode, boolean dependencyInject)
or
AutowireCapableBeanFactory.initializeBean(Object existingbean, String beanName)
As others have said <b> and <i> are explicit (i.e. "make this text bold"), whereas <strong> and <em> are semantic (i.e. "this text should be emphasised").
In the context of a modern web-browser, it's difficult to see the difference (they both appear to produce the same result, right?), but think about screen readers for the visually impaired. If a screen-reader came across an <i> tag, it wouldn't know what to do. But if it comes across a <em> tag, it knows that whatever is within should be emphasised to the listener. And therein you get the practical difference.
This is simple and works:
let item = {
firstName: 'Jonnie',
lastName: 'Walker',
fullName: function fullName() {
return 'Jonnie Walker';
}
Object.assign(Object.create(item), item);
Explain:
Object.create()
Creates new Object. If you pass params to function it will creates you object with prototype of other object. So if you have any functions on prototype of object they will be passed to prototype of other object.
Object.assign()
Merges two objects and creates fully new object and they have no reference anymore. So this example works good for me.
Try:
if($("option[value='parcel']").is(":checked"))
$('#row_dim').show();
Or even:
$(function() {
$('#type').change(function(){
$('#row_dim')[ ($("option[value='parcel']").is(":checked"))? "show" : "hide" ]();
});
});
JSFiddle: http://jsfiddle.net/3w5kD/
I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.
To get the executable path use GetModuleFileName:
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
Here's a C++ function that gets the directory without the file name:
#include <windows.h>
#include <string>
#include <iostream>
wstring ExePath() {
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
return std::wstring(buffer).substr(0, pos);
}
int main() {
std::cout << "my directory is " << ExePath() << "\n";
}
Plain HTML does not support this. You'll need to use some JavaScript code.
Also, note that large parts of the world are using a popup blocker nowadays. You may want to reconsider your design!