The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
While it's true that id(object)
gets the object's address in the default CPython implementation, this is generally useless... you can't do anything with the address from pure Python code.
The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.
From the book Fluent Python:
A basic requirement for a Python object is to provide usable string representations of itself, one used for debugging and logging, another for presentation to end users. That is why the
special methods__repr__
and__str__
exist in the data model.
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
You need to #include <stdlib.h>
. Otherwise it's defined as int malloc()
which is incompatible with the built-in type void *malloc(size_t)
.
My recommendation is Virtuous Ten Studio. The tool is free but they suggest a donation. It combines all the necessary steps (unpacking APK, baksmaliing, decompiling, etc.) into one easy-to-use UI-based import process. Within five minutes you should have Java source code, less than it takes to figure out the command line options of one of the above mentioned tools.
Decompiling smali to Java is an inexact process, especially if the smali artifacts went through an obfuscator. You can find several decompilers on the web but only some of them are still maintained. Some will give you better decompiled code than others. Read "better" as in "more understandable" than others. Don't expect that the reverse-engineered Java code will compile out of the box. Virtuous Ten Studio comes with multiple free Java decompilers built-in so you can easily try out different decompilers (the "Generate Java source" step) to see which one gives you the best results, saving you the time to find those decompilers yourself and figure out how to use them. Amongst them is CFR, which is one of the few free and still maintained decompilers.
As output you receive, amongst other things, a folder structure that contains all the decompiled Java source code. You can then import this into IntelliJ IDEA or Eclipse for further editing, analysis (e.g. Go to definition, Find usages), etc.
You can create a materialized/indexed views on the table. Based on your requirement you can do full or partial update of the views. Please see this to create mview and log. How to create materialized views in SQL Server?
No there is no explicit property for mouse leave in CSS.
You could use :hover on all the other elements except the item in question to achieve this effect. But Im not sure how practical that would be.
I think you have to look at a JS / jQuery solution.
df.drop('columnname', axis =1, inplace = True)
or else you can go with
del df['colname']
To delete multiple columns based on column numbers
df.drop(df.iloc[:,1:3], axis = 1, inplace = True)
To delete multiple columns based on columns names
df.drop(['col1','col2',..'coln'], axis = 1, inplace = True)
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
One pitfall with alloca
is that longjmp
rewinds it.
That is to say, if you save a context with setjmp
, then alloca
some memory, then longjmp
to the context, you may lose the alloca
memory. The stack pointer is back where it was and so the memory is no longer reserved; if you call a function or do another alloca
, you will clobber the original alloca
.
To clarify, what I'm specifically referring to here is a situation whereby longjmp
does not return out of the function where the alloca
took place! Rather, a function saves context with setjmp
; then allocates memory with alloca
and finally a longjmp takes place to that context. That function's alloca
memory is not all freed; just all the memory that it allocated since the setjmp
. Of course, I'm speaking about an observed behavior; no such requirement is documented of any alloca
that I know.
The focus in the documentation is usually on the concept that alloca
memory is associated with a function activation, not with any block; that multiple invocations of alloca
just grab more stack memory which is all released when the function terminates. Not so; the memory is actually associated with the procedure context. When the context is restored with longjmp
, so is the prior alloca
state. It's a consequence of the stack pointer register itself being used for allocation, and also (necessarily) saved and restored in the jmp_buf
.
Incidentally, this, if it works that way, provides a plausible mechanism for deliberately freeing memory that was allocated with alloca
.
I have run into this as the root cause of a bug.
DECLARE @IncrementValue int
SET @IncrementValue = 0
UPDATE Samples SET qty = @IncrementValue,@IncrementValue=@IncrementValue+1
As the PHP.net manual suggests, take a read of this discussion.
One major difference is that echo
can take multiple parameters to output. E.g.:
echo 'foo', 'bar'; // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error
If you're looking to evaluate the outcome of an output statement (as below) use print
. If not, use echo
.
$res = print('test');
var_dump($res); //bool(true)
An unofficial 64-bit Windows build is available from Apache Lounge.
Although not as straightforward as isinstance(x, list)
one could use as well:
this_is_a_list=[1,2,3]
if type(this_is_a_list) == type([]):
print("This is a list!")
and I kind of like the simple cleverness of that
I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
$(document).ready
happens when all the elements are present in the DOM, but not necessarily all content.
$(document).ready(function() {
alert("document is ready");
});
window.onload
or $(window).load()
happens after all the content resources (images, etc) have been loaded.
$(window).load(function() {
alert("window is loaded");
});
Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.
Alex's answer is great. but It is importanting to note that that calls the default fancybox style. If you have your own custom rules, you should just call .trigger click on that specific anchor
$(document).ready(function() {
$("#hidden_link").fancybox({
'padding': 0,
'cyclic': true,
'width': 625,
'height': 350,
'padding': 0,
'margin': 0,
'speedIn': 300,
'speedOut': 300,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'easingIn': 'swing',
'easingOut': 'swing',
'titleShow' : false
});
$("#hidden_link").trigger('click');
});
Another option that is pretty short:
<script type="text/javascript">
$.ajax({
url: "/js/partials",
success: function(data){
$(data).find('a:contains(.js)').each(function(){
// will loop through
var partial= $(this).attr("href");
$.getScript( "/js/partials/" + partial, function( data, textStatus, jqxhr ) {});
});
}
});
</script>
Interestingly enough, very often len(unique())
is a few times (3x-15x) faster than nunique()
.
A Stack
allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align
, Positioned
, or Container
to position the children of a stack.
Align
Widgets are moved by setting the alignment with Alignment
, which has static properties like topCenter
, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0)
, which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.
Stack(
children: [
Align(
alignment: Alignment.topCenter,
child: Container(
height: 80,
width: 80, color: Colors.blueAccent
),
),
Align(
alignment: Alignment.center,
child: Container(
height: 80,
width: 80, color: Colors.deepPurple
),
),
Container(
alignment: Alignment.bottomCenter,
// alignment: Alignment(1.0, -1.0),
child: Container(
height: 80,
width: 80, color: Colors.amber
),
)
]
)
In the default settings, VS Code uses the following fonts (14 pt) in descending order:
How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.
Just adding to all the information given above
NoSql Advantages:
1) NoSQL is good if you want to be production ready fast due to its support for schema-less and object oriented architecture.
2) NoSql db's are eventually consistent which in simple language means they will not provide any lock on the data(documents) as in case of RDBMS and what does it mean is latest snapshot of data is always available and thus increase the latency of your application.
3) It uses MVCC (Multi view concurrency control) strategy for maintaining and creating snapshot of data(documents).
4) If you want to have indexed data you can create view which will automatically index the data by the view definition you provide.
NoSql Disadvantages:
1) Its definitely not suitable for big heavy transactional applications as it is eventually consistent and does not support ACID properties.
2) Also it creates multiple snapshots (revisions) of your data (documents) as it uses MVCC methodology for concurrency control, as a result of which space get consumed faster than before which makes compaction and hence reindexing more frequent and it will slow down your application response as the data and transaction in your application grows. To counter that you can horizontally scale the nodes but then again it will be higher cost as compare sql database.
Remember set sendfile off;
or cache headers doesn't work.
I use this snipped:
location / {
index index.php index.html index.htm;
try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular
#.s. kill cache. use in dev
sendfile off;
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_no_cache 1;
proxy_cache_bypass 1;
}
There is a pretty good list at linuxappfinder.com.
My personal preference for LaTeX on Linux has been the KDE-based editor Kile.
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
You have two options:
Either use:
sb.setLength(0); // It will just discard the previous data, which will be garbage collected later.
Or use:
sb.delete(0, sb.length()); // A bit slower as it is used to delete sub sequence.
Avoid declaring StringBuffer
or StringBuilder
objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.
Check your elasticsearch.yml, "transport.host" property must be "0.0.0.0" not "127.0.0.1" or "localhost"
More precise Kotlin code using handler :
Handler(Looper.getMainLooper()).post {
// your codes here run on main Thread
}
Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
By declaring it global
inside the function that accesses it:
g_c = 0
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print(g_c)
The Python documentation says this, about the global
statement:
The global statement is a declaration which holds for the entire current code block.
There is a way to call the init()
method once and forbid it's usage, you can turn the function into private initializer and ivoke it after class declaration like this:
class Example {
private static function init() {
// do whatever needed for class initialization
}
}
(static function () {
static::init();
})->bindTo(null, Example::class)();
Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)
Since this is a Python 3 project, you only need to delete __pycache__
directories -- all .pyc
/.pyo
files are inside them.
find . -type d -name __pycache__ -exec rm -r {} \+
or its simpler form,
find . -type d -name __pycache__ -delete
which didn't work for me for some reason (files were deleted but directories weren't), so I'm including both for the sake of completeness.
Alternatively, if you're doing this in a directory that's under revision control, you can tell the RCS to ignore __pycache__
folders recursively. Then, at the required moment, just clean up all the ignored files. This will likely be more convenient because there'll probably be more to clean up than just __pycache__
.
How to change multiple "dogsss" to "dollsss":
$('#id1 p').each(function() {
var text = $(this).text();
// Use global flag i.e. g in the regex to replace all occurrences
$(this).text(text.replace(/dog/g, 'doll'));
});
You could do this:
library(dplyr)
cols <- paste0("a", 1:10)
tab <- matrix(1:1000, nrow = 100) %>% as.tibble() %>% set_names(cols)
tab
# A tibble: 100 x 10
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
<int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 1 101 201 301 401 501 601 701 801 901
2 2 102 202 302 402 502 602 702 802 902
3 3 103 203 303 403 503 603 703 803 903
4 4 104 204 304 404 504 604 704 804 904
5 5 105 205 305 405 505 605 705 805 905
6 6 106 206 306 406 506 606 706 806 906
7 7 107 207 307 407 507 607 707 807 907
8 8 108 208 308 408 508 608 708 808 908
9 9 109 209 309 409 509 609 709 809 909
10 10 110 210 310 410 510 610 710 810 910
# ... with 90 more rows
Above I just made a dataframe with 10 columns and 100 rows, ok?
Now you can sample it with sample_n
:
sample_n(tab, size = 800, replace = T)
# A tibble: 800 x 10
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
<int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 53 153 253 353 453 553 653 753 853 953
2 14 114 214 314 414 514 614 714 814 914
3 10 110 210 310 410 510 610 710 810 910
4 70 170 270 370 470 570 670 770 870 970
5 36 136 236 336 436 536 636 736 836 936
6 77 177 277 377 477 577 677 777 877 977
7 13 113 213 313 413 513 613 713 813 913
8 58 158 258 358 458 558 658 758 858 958
9 29 129 229 329 429 529 629 729 829 929
10 3 103 203 303 403 503 603 703 803 903
# ... with 790 more rows
maybe this article can help you link here
Write-through: Write is done synchronously both to the cache and to the backing store.
Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.
Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.
Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.
Two issues:
You're passing the jQuery wrapper of the element into parseInt
, which isn't what you want, as parseInt
will call toString
on it and get back "[object Object]"
. You need to use val
or text
or something (depending on what the element is) to get the string you want.
You're not telling parseInt
what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt
guesses which radix to use.
Fix if the element is a form field:
// vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
Fix if the element is something else and you want to use the text within it:
// vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
// ^^^^-- tell parseInt to use decimal (base 10)
I can't say for sure if this is the case, but what appeared to be a problem for me was having .gitignore files in some of the subdirectories. Again, I can't guarantee this, but everything worked after these were deleted.
These are the versions of C# known about at the time of this writing:
Dispose
on IEnumerator
s which implemented IDisposable
. A few other small features.var
), query expressionsdynamic
), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parametersawait
in catch
and finally
, extension Add
methods in collection initializers.out
parameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.unmanaged
generic type constraints. ref
reassignment. Unsafe improvements: stackalloc
initialization, unpinned indexed fixed
buffers, custom fixed
statements. Improved overloading resolution. Expression variables in initializers and queries. ==
and !=
defined for tuples. Auto-properties' backing fields can now be targeted by attributes.new
expressions, target typed ??
and ?
), covariant returns. Minor features: relax ordering of ref
and partial
modifiers, parameter null checking, lambda discard parameters, native int
s, attributes on local functions, function pointers, static lambdas, extension GetEnumerator
, module initializers, extending partial.What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?
There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version
property still reports 4.0.xxx.
As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.
If you want to loop over what you "find", you should use this:
find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
printf '%s\n' "$file"
done
Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command
try Windows Server 2003 Resource Kit Tools
it contains a tail.exe
which can be run on Windows system.
https://www.microsoft.com/en-us/download/details.aspx?id=17657
Don't forget to import Foundation
or UIKit
.
import Foundation
let trimmedString = " aaa "".trimmingCharacters(in: .whitespaces)
print(trimmedString)
Result:
"aaa"
Otherwise you'll get:
error: value of type 'String' has no member 'trimmingCharacters'
return self.trimmingCharacters(in: .whitespaces)
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
There's a pretty good explanation of first level caching on the Streamline Logic blog.
Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.
Netscape ANSI encoded files use 0D 0D 0A for their line breaks.
This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config
file and having something like this
Host git_host
HostName git.host.de
User root
Port 4019
then you can have
url = git_host:/var/cache/git/project.git
and you can also ssh git_host
and scp git_host ...
and everything will work out.
I had the same error and I had not made any changes to the application config or the web.xml. Multiple tries to revert back some minor changes to code was not clearing the exceptions. Finally it worked after restarting STS.
Here is an answer coming right from the libc6
!
Taking a look at /usr/include/x86_64-linux-gnu/bits/byteswap.h
, I found the trick you were looking for.
A few critics of previous solutions:
auto
keyword, that's fine, but feel free to use the known/expected type instead.The trick is to use both the (expr,expr)
construct and a {}
scope:
#define MACRO(X,Y) \
( \
{ \
register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
)
Note the use of the register
keyword, it's only a hint to the compiler.
The X
and Y
macro parameters are (already) surrounded in parenthesis and casted to an expected type.
This solution works properly with pre- and post-increment as parameters are evaluated only once.
For the example purpose, even though not requested, I added the __x + __y;
statement, which is the way to make the whole bloc to be evaluated as that precise expression.
It's safer to use void();
if you want to make sure the macro won't evaluate to an expression, thus being illegal where an rvalue
is expected.
However, the solution is not ISO C++ compliant as will complain g++ -pedantic
:
warning: ISO C++ forbids braced-groups within expressions [-pedantic]
In order to give some rest to g++
, use (__extension__ OLD_WHOLE_MACRO_CONTENT_HERE)
so that the new definition reads:
#define MACRO(X,Y) \
(__extension__ ( \
{ \
register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
))
In order to improve my solution even a bit more, let's use the __typeof__
keyword, as seen in MIN and MAX in C:
#define MACRO(X,Y) \
(__extension__ ( \
{ \
__typeof__(X) __x = (X); \
__typeof__(Y) __y = (Y); \
std::cout << "1st arg is:" << __x << std::endl; \
std::cout << "2nd arg is:" << __y << std::endl; \
std::cout << "Sum is:" << (__x + __y) << std::endl; \
__x + __y; \
} \
))
Now the compiler will determine the appropriate type. This too is a gcc
extension.
Note the removal of the register
keyword, as it would the following warning when used with a class type:
warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]
Syntax is Shown below:
"your condition"? "step if true":"step if condition fails"
<div class="container-fluid">
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary ml-auto">Button</button>
</div>
</div>
.ml-auto
is Bootstraph 4's non-flexbox way of aligning things.
Since you don't want to add a class to cells containing an icon, how about this...
Wrap the contents of each non-icon td
in a span
:
<td><span>consectetur</span></td>
<td><span>adipiscing</span></td>
<td><span>elit</span></td>
And use this CSS:
td {
text-align: center;
}
td span {
text-align: left;
display: block;
}
I wouldn't normally post an answer in this situation, but this seems too long for a comment.
A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.
You must first import the functions:
import org.apache.spark.sql.functions._
Then you can use them like this:
val df = CSV.load(args(0))
val sumSteps = df.agg(sum("steps")).first.get(0)
You can also cast the result if needed:
val sumSteps: Long = df.agg(sum("steps").cast("long")).first.getLong(0)
Edit:
For multiple columns (e.g. "col1", "col2", ...), you could get all aggregations at once:
val sums = df.agg(sum("col1").as("sum_col1"), sum("col2").as("sum_col2"), ...).first
Edit2:
For dynamically applying the aggregations, the following options are available:
df.groupBy().sum()
val columnNames = List("col1", "col2")
df.groupBy().sum(columnNames: _*)
val cols = List("col1", "col2")
val sums = cols.map(colName => sum(colName).cast("double").as("sum_" + colName))
df.groupBy().agg(sums.head, sums.tail:_*).show()
format
The following is excerpt from the documentation:
Given
format % values
,%
conversion specifications informat
are replaced with zero or more elements ofvalues
. The effect is similar to the usingsprintf()
in the C language.If
format
requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by theformat
string, or a single mapping object (for example, a dictionary).
str.format
instead of %
A newer alternative to %
operator is to use str.format
. Here's an excerpt from the documentation:
str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces
{}
. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.This method is the new standard in Python 3.0, and should be preferred to
%
formatting.
Here are some usage examples:
>>> '%s for %s' % ("tit", "tat")
tit for tat
>>> '{} and {}'.format("chicken", "waffles")
chicken and waffles
>>> '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}
Bond, James Bond
>>> '{last}, {first} {last}'.format(first="James", last="Bond")
Bond, James Bond
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
More elegant option:
String phone = "+34666777888";
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
startActivity(intent);
It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
<div ng-bind-html="myText"></div>
No need to put into html {{}} interpolation tags like you did {{myText}}.
and don't forget to use ngSanitize in module like e.g.
var app = angular.module("myApp", ['ngSanitize']);
and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize
Public Function getWeb(ByRef sURL As String) As String
Dim myWebClient As New System.Net.WebClient()
Try
Dim myCredentialCache As New System.Net.CredentialCache()
Dim myURI As New Uri(sURL)
myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
myWebClient.Encoding = System.Text.Encoding.UTF8
myWebClient.Credentials = myCredentialCache
Return myWebClient.DownloadString(myURI)
Catch ex As Exception
Return "Exception " & ex.ToString()
End Try
End Function
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
This will fix the error:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):
for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
std::cout << *i << std::endl;
}
public static void main(String[] args) {
int[] toyNumber = new int[] {5};
NewClass temp = new NewClass();
temp.play(toyNumber);
System.out.println("Toy number in main " + toyNumber[0]);
}
void play(int[] toyNumber){
System.out.println("Toy number in play " + toyNumber[0]);
toyNumber[0]++;
System.out.println("Toy number in play after increement " + toyNumber[0]);
}
Thanks to Rob, Updated Swift 4.2 syntax
let controller:WalletView = self.storyboard!.instantiateViewController(withIdentifier: "MyView") as! WalletView
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
Here is an example where the things to add come from a dictionary
>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
... L[item['idx']] += item['amount']
...
>>> L
[0, 1, 1, 0]
Here is an example adding elements from another list
>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
You could also achieve the above with a list comprehension and zip
L[:] = [sum(i) for i in zip(L, things_to_add)]
Here is an example adding from a list of tuples
>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
Well, I figured out the problem.
Basically Go starting path for import is $HOME/go/src
So I just needed to add myapp
in front of the package names, that is, the import should be:
import (
"log"
"net/http"
"myapp/common"
"myapp/routers"
)
You can override ggplots default scales by modifying scale_x_continuous
and/or scale_y_continuous
. For example:
library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))
ggplot(dat, aes(x,y)) +
geom_point()
Gives you this:
And overriding the scales can give you something like this:
ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = round(seq(min(dat$x), max(dat$x), by = 0.5),1)) +
scale_y_continuous(breaks = round(seq(min(dat$y), max(dat$y), by = 0.5),1))
If you want to simply "zoom" in on a specific part of a plot, look at xlim()
and ylim()
respectively. Good insight can also be found here to understand the other arguments as well.
As the rank doesn't depend at all from the contacts
RANKED_RSLTS
QRY_ID | RES_ID | SCORE | RANK
-------------------------------------
A | 1 | 15 | 3
A | 2 | 32 | 1
A | 3 | 29 | 2
C | 7 | 61 | 1
C | 9 | 30 | 2
Thus :
SELECT
C.*
,R.SCORE
,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT *,
MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
FROM RSLTS) R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID
FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:
Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"
In R1C1 you would use:
Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"
It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.
The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :
Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"
If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:
private string getClientIp(HttpRequestMessage request = null)
{
if (request == null)
{
return null;
}
if (request.Properties.ContainsKey("MS_OwinContext"))
{
return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
}
return null;
}
To ignore some folder from eslint rules we could create the file .eslintignore
in root directory and add there the path to the folder we want omit (the same way as for .gitignore
).
Here is the example from the ESLint docs on Ignoring Files and Directories:
# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
Update 2020 - Bootstrap 4, Bootstrap 5 beta
There are 3 rules to follow when overriding Bootstrap CSS..
bootstrap.css
before your CSS rules (overrides)Yes, overrides should be put in a separate styles.css
(or custom.css
) file so that the bootstrap.css
remains unmodified. This makes it easier to upgrade the Bootstrap version without impacting the overrides. The reference to the styles.css
follows after the bootstrap.css
for the overrides to work.
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
Just add whatever changes are needed in the custom CSS. For example:
legend {
display: block;
width: inherit;
padding: 0;
margin-bottom: 0;
font-size: inherit;
line-height: inherit;
color: inherit;
white-space: initial;
}
Note: It's not a good practice to use
!important
in the override CSS, unless you're overriding one of the Bootstrap Utility classes. CSS specificity always works for one CSS class to override another. Just make sure you use a CSS selector that is that same as, or more specific than the bootstrap.css
For example, consider the Bootstrap 4 dark Navbar link color. Here's the bootstrap.css
...
.navbar-dark .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
}
So, to override the Navbar link color, you can use the same selector, or a more specific selector such as:
#mynavbar .navbar-nav .nav-link {
color: #ffcc00;
}
When the CSS selectors are the same, the last one takes precedence, which it why the styles.css
should follow the bootstrap.css
.
The following works for me:
class Fruits: pass
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
import pickle
filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()
file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()
print(object_file.color, object_file.value, sep=', ')
# yellow, 30
Check the installation directories (typically C:\Program Files (x86)
or C:\Program Files
) for the java folder. If it contains the JRE you have java installed.
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>
tag
<%= stylesheet_link_tag controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
Also, to specify the same class CSS on a different controller
Add this line in the body
of application.html.erb
<body class="<%= controller.controller_name %>-<%= controller.action_name %>">
So, now for example I would like to change the p
tag in 'home' controller and 'index' action.
Inside index.scss
file adds.
.nameOfController-nameOfAction <tag> { }
.home-index p {
color:red !important;
}
I realise that WayneM has stated he knows that money is specific to SQL Server. However, he is asking if there are any reasons to use money over decimal or vice versa and I think one obvious reason still ought to be stated and that is using decimal means it's one less thing to worry about if you ever have to change your DBMS - which can happen.
Make your systems as flexible as possible!
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
You can use -i''
(--in-place
) for sed
as already suggested. See: The -i
in-place argument, however note that -i
option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed
is a Stream EDitor, not a file editor.
Alternative way is to use built-in substitution in Vim Ex mode, like:
$ ex +%s/foo/bar/g -scwq file.txt
and for multiple-files:
$ ex +'bufdo!%s/foo/bar/g' -scxa *.*
To edit all files recursively you can use **/*.*
if shell supports that (enable by shopt -s globstar
).
Another way is to use gawk
and its new "inplace" extension such as:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1
Georg have already mentioned ES6 have Array.findIndex for this. And some other answers are workaround for ES5 using Array.some method.
One more elegant approach can be
var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);
At the same time I will like to emphasize, Array.some may be implemented with binary or other efficient searching technique. So, it might perform better over for loop in some browser.
In addition to the suggestions in this thread, I wanted to mention that if you need to return dot files as well (.gitignore, etc), with Dir.glob you would need to include a flag as so:
Dir.glob("/path/to/dir/*", File::FNM_DOTMATCH)
By default, Dir.entries includes dot files, as well as current a parent directories.
For anyone interested, I was curious how the answers here compared to each other in execution time, here was the results against deeply nested hierarchy. The first three results are non-recursive:
user system total real
Dir[*]: (34900 files stepped over 100 iterations)
0.110729 0.139060 0.249789 ( 0.249961)
Dir.glob(*): (34900 files stepped over 100 iterations)
0.112104 0.142498 0.254602 ( 0.254902)
Dir.entries(): (35600 files stepped over 100 iterations)
0.142441 0.149306 0.291747 ( 0.291998)
Dir[**/*]: (2211600 files stepped over 100 iterations)
9.399860 15.802976 25.202836 ( 25.250166)
Dir.glob(**/*): (2211600 files stepped over 100 iterations)
9.335318 15.657782 24.993100 ( 25.006243)
Dir.entries() recursive walk: (2705500 files stepped over 100 iterations)
14.653018 18.602017 33.255035 ( 33.268056)
Dir.glob(**/*, File::FNM_DOTMATCH): (2705500 files stepped over 100 iterations)
12.178823 19.577409 31.756232 ( 31.767093)
These were generated with the following benchmarking script:
require 'benchmark'
base_dir = "/path/to/dir/"
n = 100
Benchmark.bm do |x|
x.report("Dir[*]:") do
i = 0
n.times do
i = i + Dir["#{base_dir}*"].select {|f| !File.directory? f}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir.glob(*):") do
i = 0
n.times do
i = i + Dir.glob("#{base_dir}/*").select {|f| !File.directory? f}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir.entries():") do
i = 0
n.times do
i = i + Dir.entries(base_dir).select {|f| !File.directory? File.join(base_dir, f)}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir[**/*]:") do
i = 0
n.times do
i = i + Dir["#{base_dir}**/*"].select {|f| !File.directory? f}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir.glob(**/*):") do
i = 0
n.times do
i = i + Dir.glob("#{base_dir}**/*").select {|f| !File.directory? f}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir.entries() recursive walk:") do
i = 0
n.times do
def walk_dir(dir, result)
Dir.entries(dir).each do |file|
next if file == ".." || file == "."
path = File.join(dir, file)
if Dir.exist?(path)
walk_dir(path, result)
else
result << file
end
end
end
result = Array.new
walk_dir(base_dir, result)
i = i + result.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
x.report("Dir.glob(**/*, File::FNM_DOTMATCH):") do
i = 0
n.times do
i = i + Dir.glob("#{base_dir}**/*", File::FNM_DOTMATCH).select {|f| !File.directory? f}.length
end
puts " (#{i} files stepped over #{n} iterations)"
end
end
The differences in file counts are due to Dir.entries
including hidden files by default. Dir.entries
ended up taking a bit longer in this case due to needing to rebuild the absolute path of the file to determine if a file was a directory, but even without that it was still taking consistently longer than the other options in the recursive case. This was all using ruby 2.5.1 on OSX.
Tested with Angular2 RC2
I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps
textarea-component.ts
import {Component} from '@angular/core';
@Component({
selector: 'textarea-comp',
template: `
<textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
<p><button (click)="pushMe()">pushMeToLog</button></p>
`
})
export class TextAreaComponent {
str: string;
pushMe() {
console.log( "TextAreaComponent::str: " + this.str);
}
}
char * const a;
*a
is writable, but a
is not; in other words, you can modify the value pointed to by a
, but you cannot modify a
itself. a
is a constant pointer to char
.
const char * a;
a
is writable, but *a
is not; in other words, you can modify a
(pointing it to a new location), but you cannot modify the value pointed to by a
.
Note that this is identical to
char const * a;
In this case, a
is a pointer to a const char
.
On Linux, you can use ldconfig
, which maintains the ld.so configuration and cache, to print out the directories search by ld.so
with
ldconfig -v 2>/dev/null | grep -v ^$'\t'
ldconfig -v
prints out the directories search by the linker (without a leading tab) and the shared libraries found in those directories (with a leading tab); the grep
gets the directories. On my machine, this line prints out
/usr/lib64/atlas:
/usr/lib/llvm:
/usr/lib64/llvm:
/usr/lib64/mysql:
/usr/lib64/nvidia:
/usr/lib64/tracker-0.12:
/usr/lib/wine:
/usr/lib64/wine:
/usr/lib64/xulrunner-2:
/lib:
/lib64:
/usr/lib:
/usr/lib64:
/usr/lib64/nvidia/tls: (hwcap: 0x8000000000000000)
/lib/i686: (hwcap: 0x0008000000000000)
/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib/sse2: (hwcap: 0x0000000004000000)
/usr/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib64/sse2: (hwcap: 0x0000000004000000)
The first paths, without hwcap
in the line, are either built-in or read from /etc/ld.so.conf.
The linker can then search additional directories under the basic library search path, with names like sse2
corresponding to additional CPU capabilities.
These paths, with hwcap
in the line, can contain additional libraries tailored for these CPU capabilities.
One final note: using -p
instead of -v
above searches the ld.so
cache instead.
The logic is not flawed. The statement
if x is y then x==y is also True
should never be read to mean
if x==y then x is y
It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)
Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line
It can be that you need to add or update your privacy policy. You can easily create a privacy policy using this template
Use the package "recommenderlab". Download and install the package. This package has a command "Normalize" in built. It also allows you to choose one of the many methods for normalization namely 'center' or 'Z-score' Follow the following example:
## create a matrix with ratings
m <- matrix(sample(c(NA,0:5),50, replace=TRUE, prob=c(.5,rep(.5/6,6))),nrow=5, ncol=10, dimnames = list(users=paste('u', 1:5, sep=”), items=paste('i', 1:10, sep=”)))
## do normalization
r <- as(m, "realRatingMatrix")
#here, 'centre' is the default method
r_n1 <- normalize(r)
#here "Z-score" is the used method used
r_n2 <- normalize(r, method="Z-score")
r
r_n1
r_n2
## show normalized data
image(r, main="Raw Data")
image(r_n1, main="Centered")
image(r_n2, main="Z-Score Normalization")
Another dplyr
possibility could be:
df %>%
group_by(cat) %>%
mutate(num = 1:n())
cat val num
<fct> <dbl> <int>
1 aaa 0.0564 1
2 aaa 0.258 2
3 aaa 0.308 3
4 aaa 0.469 4
5 aaa 0.552 5
6 bbb 0.170 1
7 bbb 0.370 2
8 bbb 0.484 3
9 bbb 0.547 4
10 bbb 0.812 5
11 ccc 0.280 1
12 ccc 0.398 2
13 ccc 0.625 3
14 ccc 0.763 4
15 ccc 0.882 5
Create a function to move it:
function move_file($file, $to){
$path_parts = pathinfo($file);
$newplace = "$to/{$path_parts['basename']}";
if(rename($file, $newplace))
return $newplace;
return null;
}
The problem might be with service mysql-server and apache2 running while system start. You can do the following.
sudo /opt/lampp/lampp stop
To stop already running default services
sudo service apache2 stop
sudo service mysql stop
To remove the services completely, so that they won't create problem in next system-restart, If you are in ubuntu(debian)
sudo apt-get remove apache2
sudo apt-get remove mysql-server
If you are in redhat or other, You could use yum
or similar command to uninstall the services
Then start the lampp again
sudo /opt/lampp/lampp start
Also, don't install mysql-server in the system, because it might start in system start-up, occupy the port, and create problem for mysql of lampp.
I am using the following
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
</configuration>
</plugin>
....
This way you can define each value individually or pragmatically from Jenkins of some other system.
mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3
This will place a folder target\{group.id}\projectName-1.2.3.jar
A better way to save time might be
....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
</configuration>
</plugin>
....
Like the same except I use on variable.
mvn package -DbaseVersion=0.3.4
This will place a folder target\{group.id}\projectName-1.2.3.jar
you can also use outputDirectory
inside of configuration
to specify a location you may want the package to be located.
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.
I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:
When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:
context.save();
context.translate(newx, newy);
context.rotate(-Math.PI/2);
context.textAlign = "center";
context.fillText("Your Label Here", labelXposition, 0);
context.restore();
.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".
Working solution for MVC
public ActionResult Index()
{
string fileName = "test.pdf";
string fileName1 = "test.vsix";
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\test\test.pdf");
byte[] fileBytes1 = System.IO.File.ReadAllBytes(@"C:\test\test.vsix");
byte[] compressedBytes;
using (var outStream = new MemoryStream())
{
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(fileBytes))
{
fileToCompressStream.CopyTo(entryStream);
}
var fileInArchive1 = archive.CreateEntry(fileName1, CompressionLevel.Optimal);
using (var entryStream = fileInArchive1.Open())
using (var fileToCompressStream = new MemoryStream(fileBytes1))
{
fileToCompressStream.CopyTo(entryStream);
}
}
compressedBytes = outStream.ToArray();
}
return File(compressedBytes, "application/zip", fileNameZip);
}
In javascript you can implement the function just once and invoke the function without the parameters myFunc()
You then check to see if options is 'undefined'
function myFunc(options){
if(typeof options != 'undefined'){
//code
}
}
you can get the current project path use System.getProperty("user.dir")
in that method you write Key name to get your different-different paths, and if you don't know key, you can find all property use of System.getProperties()
this method is return all property with key. and you can find key name manually from it.
and write System.getProperty("KEY NAME")
and get your require path.
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
Additional-> To clear the Child Controls The below function would clear the nested(Child) controls also, wrap up in a class.
public static void ClearControl(Control control)
{
if (control is TextBox)
{
TextBox txtbox = (TextBox)control;
txtbox.Text = string.Empty;
}
else if (control is CheckBox)
{
CheckBox chkbox = (CheckBox)control;
chkbox.Checked = false;
}
else if (control is RadioButton)
{
RadioButton rdbtn = (RadioButton)control;
rdbtn.Checked = false;
}
else if (control is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)control;
dtp.Value = DateTime.Now;
}
else if (control is ComboBox)
{
ComboBox cmb = (ComboBox)control;
if (cmb.DataSource != null)
{
cmb.SelectedItem = string.Empty;
cmb.SelectedValue = 0;
}
}
ClearErrors(control);
// repeat for combobox, listbox, checkbox and any other controls you want to clear
if (control.HasChildren)
{
foreach (Control child in control.Controls)
{
ClearControl(child);
}
}
}
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
The solution posted by @Linga:
"Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"
is nice and short. However, it only computes the size of 'directory_path'
, without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File
option to avoid errors for empty sub-directories)
foreach ($d in gci -Directory -Force) {
'{0:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d"
}
If working with data, many times pandas
is the simple key
This particular code will put the raw
into one column, then normalize by column per row. (But we can put it into a row and do it by row per column, too! Just have to change the axis
values where 0 is for row and 1 is for column.)
import pandas as pd
raw = [0.07, 0.14, 0.07]
raw_df = pd.DataFrame(raw)
normed_df = raw_df.div(raw_df.sum(axis=0), axis=1)
normed_df
where normed_df
will display like:
0
0 0.25
1 0.50
2 0.25
and then can keep playing with the data, too!
You can use setColumnWidth()
if you want to expand your cell more.
Here is my working code
function emptyTextAreaCheck(textarea, submitButtonClass) {
if(!submitButtonClass)
submitButtonClass = ".transSubmit";
if($(textarea).val() == '') {
$(submitButtonClass).addClass('disabled_button');
$(submitButtonClass).removeClass('transSubmit');
}
$(textarea).live('focus keydown keyup', function(){
if($(this).val().length == 0) {
$(submitButtonClass).addClass('disabled_button');
$(submitButtonClass).removeClass('transSubmit');
} else {
$('.disabled_button').addClass('transSubmit').css({
'cursor':'pointer'
}).removeClass('disabled_button');
}
});
}
If you really need to do this, use reverse proxy.
For example, with nginx as reverse proxy
server {
listen api.mydomain.com:80;
server_name api.mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
I did a pure shell version for an embedded system taking advantage of:
/usr/bin/dd's SIGUSR1 signal handling feature.
Basically, if you send a 'kill SIGUSR1 $(pid_of_running_dd_process)', it'll output a summary of throughput speed and amount transferred.
backgrounding dd and then querying it regularly for updates, and generating hash ticks like old-school ftp clients used to.
Using /dev/stdout as the destination for non-stdout friendly programs like scp
The end result allows you to take any file transfer operation and get progress update that looks like old-school FTP 'hash' output where you'd just get a hash mark for every X bytes.
This is hardly production quality code, but you get the idea. I think it's cute.
For what it's worth, the actual byte-count might not be reflected correctly in the number of hashes - you may have one more or less depending on rounding issues. Don't use this as part of a test script, it's just eye-candy. And, yes, I'm aware this is terribly inefficient - it's a shell script and I make no apologies for it.
Examples with wget, scp and tftp provided at the end. It should work with anything that has emits data. Make sure to use /dev/stdout for programs that aren't stdout friendly.
#!/bin/sh
#
# Copyright (C) Nathan Ramella ([email protected]) 2010
# LGPLv2 license
# If you use this, send me an email to say thanks and let me know what your product
# is so I can tell all my friends I'm a big man on the internet!
progress_filter() {
local START=$(date +"%s")
local SIZE=1
local DURATION=1
local BLKSZ=51200
local TMPFILE=/tmp/tmpfile
local PROGRESS=/tmp/tftp.progress
local BYTES_LAST_CYCLE=0
local BYTES_THIS_CYCLE=0
rm -f ${PROGRESS}
dd bs=$BLKSZ of=${TMPFILE} 2>&1 \
| grep --line-buffered -E '[[:digit:]]* bytes' \
| awk '{ print $1 }' >> ${PROGRESS} &
# Loop while the 'dd' exists. It would be 'more better' if we
# actually looked for the specific child ID of the running
# process by identifying which child process it was. If someone
# else is running dd, it will mess things up.
# My PID handling is dumb, it assumes you only have one running dd on
# the system, this should be fixed to just get the PID of the child
# process from the shell.
while [ $(pidof dd) -gt 1 ]; do
# PROTIP: You can sleep partial seconds (at least on linux)
sleep .5
# Force dd to update us on it's progress (which gets
# redirected to $PROGRESS file.
#
# dumb pid handling again
pkill -USR1 dd
local BYTES_THIS_CYCLE=$(tail -1 $PROGRESS)
local XFER_BLKS=$(((BYTES_THIS_CYCLE-BYTES_LAST_CYCLE)/BLKSZ))
# Don't print anything unless we've got 1 block or more.
# This allows for stdin/stderr interactions to occur
# without printing a hash erroneously.
# Also makes it possible for you to background 'scp',
# but still use the /dev/stdout trick _even_ if scp
# (inevitably) asks for a password.
#
# Fancy!
if [ $XFER_BLKS -gt 0 ]; then
printf "#%0.s" $(seq 0 $XFER_BLKS)
BYTES_LAST_CYCLE=$BYTES_THIS_CYCLE
fi
done
local SIZE=$(stat -c"%s" $TMPFILE)
local NOW=$(date +"%s")
if [ $NOW -eq 0 ]; then
NOW=1
fi
local DURATION=$(($NOW-$START))
local BYTES_PER_SECOND=$(( SIZE / DURATION ))
local KBPS=$((SIZE/DURATION/1024))
local MD5=$(md5sum $TMPFILE | awk '{ print $1 }')
# This function prints out ugly stuff suitable for eval()
# rather than a pretty string. This makes it a bit more
# flexible if you have a custom format (or dare I say, locale?)
printf "\nDURATION=%d\nBYTES=%d\nKBPS=%f\nMD5=%s\n" \
$DURATION \
$SIZE \
$KBPS \
$MD5
}
Examples:
echo "wget"
wget -q -O /dev/stdout http://www.blah.com/somefile.zip | progress_filter
echo "tftp"
tftp -l /dev/stdout -g -r something/firmware.bin 192.168.1.1 | progress_filter
echo "scp"
scp [email protected]:~/myfile.tar /dev/stdout | progress_filter
Most of previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip()
.
This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
You can of course format the result of current_timestamp()
.
Please have a look at the various formatting functions in the official documentation.
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
For a API v3 solution, refer to:
http://blog.enbake.com/draw-circle-with-google-maps-api-v3
It creates circle around points and then show markers within and out of the range with different colors. They also calculate dynamic radius but in your case radius is fixed so may be less work.
Install Windows Mobile Device Center for your architecture. (It will install older versions of .NET if needed.) In USB to PC settings on device uncheck Enable advanced network and tap OK. This worked for me on 2 different Windows 10 PCs.
read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter
^use as many of these as you need, and you can make your own BASIC encryption
The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.
libtriangle.dylib:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1368 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
libtriangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1256 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
triangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 BUNDLE 16 1696 NOUNDEFS DYLDLINK TWOLEVEL
The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.
Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
List<int> first_list = new List<int>() {
1,
12,
12,
5
};
List<int> second_list = new List<int>() {
12,
5,
7,
9,
1
};
var result = first_list.Union(second_list);
I had the same issue in Windows
and it worked since my proxy configuration in settings.xml
file was changed
So locate and edit the file inside the \conf
folder, for example : C:\Program Files\apache-maven-3.2.5\conf
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>jorgesys</username>
<password>supercalifragilisticoespialidoso</password>
<host>proxyjorgesys</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
80
to 8080
/program files
you can make a copy, edit the file and replace the file located into /program files
folder.You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true
.
You can also add multiple hidden fields. Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
var request = [];_x000D_
var container = '';_x000D_
console.log(arguments);_x000D_
request = arguments[0].hidden;_x000D_
console.log(arguments[0].hasOwnProperty('form'));_x000D_
if(arguments[0].hasOwnProperty('form') == true)_x000D_
{_x000D_
if(arguments[0].form.status == 'true'){_x000D_
var parent = document.getElementById("container");_x000D_
container = document.createElement('form');_x000D_
parent.appendChild(container);_x000D_
Object.assign(container, {'id':arguments[0].form.formID});_x000D_
}_x000D_
}_x000D_
else{_x000D_
container = document.getElementById("container");_x000D_
}_x000D_
_x000D_
//var container = document.getElementById("container");_x000D_
Object.keys(request).forEach(function(elem)_x000D_
{_x000D_
if($('#'+elem).length <= 0){_x000D_
console.log("Hidden Field created");_x000D_
var input = document.createElement('input');_x000D_
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
container.appendChild(input);_x000D_
}else{_x000D_
console.log("Hidden Field Exists and value is below" );_x000D_
$('#'+elem).val(request[elem]);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
This related question's answer provided the solution for me... it was just a dumb mistake:
Remember to commit first!
https://stackoverflow.com/a/7572252
If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.
I think, it is a very convenient way to use regular expressions
to find a range for applying attributes. This is how I did it:
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];
NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}
NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}
[self.textView setAttributedText:goodText];
I was searching for a list of available attributes and didn't find them here and in a class reference's first page. So I decided to post here information on that.
Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.
NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
NSString *NSForegroundColorAttributeName;
NSString *NSUnderlineStyleAttributeName;
NSString *NSSuperscriptAttributeName;
NSString *NSBackgroundColorAttributeName;
NSString *NSAttachmentAttributeName;
NSString *NSLigatureAttributeName;
NSString *NSBaselineOffsetAttributeName;
NSString *NSKernAttributeName;
NSString *NSLinkAttributeName;
NSString *NSStrokeWidthAttributeName;
NSString *NSStrokeColorAttributeName;
NSString *NSUnderlineColorAttributeName;
NSString *NSStrikethroughStyleAttributeName;
NSString *NSStrikethroughColorAttributeName;
NSString *NSShadowAttributeName;
NSString *NSObliquenessAttributeName;
NSString *NSExpansionAttributeName;
NSString *NSCursorAttributeName;
NSString *NSToolTipAttributeName;
NSString *NSMarkedClauseSegmentAttributeName;
NSString *NSWritingDirectionAttributeName;
NSString *NSVerticalGlyphFormAttributeName;
NSString *NSTextAlternativesAttributeName;
NSAttributedString programming guide
A full class reference is here.
$(document).ready(function(){
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}];
$.each(jsonObj,function(i,v){
if (v.Id == 3) {
v.Username = "Thomas";
return false;
}
});
alert("New Username: " + jsonObj[2].Username);
});
The last and the best one. i.e LOGICAL AND
if (foo != null && foo.bar()) {
etc...
}
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
Prefer to read :Java logical operator short-circuiting
I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
for get week number in jalai calendar you can use this:
$weeknumber = date("W"); //number week in year
$dayweek = date("w"); //number day in week
if ($dayweek == "6")
{
$weeknumberint = (int)$weeknumber;
$date2int++;
$weeknumber = (string)$date2int;
}
echo $date2;
result:
15
week number change in saturday
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
android:alpha
does this in XML:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/blah"
android:alpha=".75"/>
This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.
What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"
Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:
git status
. It will give you a list of unmerged files.git commit
Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)
Git then considers the merge successful and allows you to move forward.
It is an HTML, CSS, and JavaScript open-source framework (initially created by Twitter) that you can use as a basis for creating web sites or web applications.
Update
The official bootstrap website is updated and includes a clear definition.
"Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web."
"Designed and built with all the love in the world by @mdo and @fat."
I achieved the same thing using a local web server and PHP. I used a script containing shell_exec
to launch an application locally.
Alternatively, you could do something like this:
<a href="file://C:/Windows/notepad.exe">Notepad</a>
Change your object.
var top_brands = [
{ key: 'Adidas', value: 100 },
{ key: 'Nike', value: 50 }
];
var $brand_options = $("#top-brands");
$.each(top_brands, function(brand) {
$brand_options.append(
$("<option />").val(brand.key).text(brand.key + " " + brand.value)
);
});
As a rule of thumb:
'Adidas'
, 'Nike'
, 100
and 50
are data.There are no semantics in {Nike: 50}
. What's "Nike"? What's 50?
{key: 'Nike', value: 50}
is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.
Better still would be {vendor: 'Nike', itemsSold: 50}
, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.
I had the same problem.
My project directory was like this:
--project
---Classes
----Application
-----.h and .c files
----OtherFolders
--main.cpp
And what I used to include the files in all those folders:
file(GLOB source_files
"*.h"
"*.cpp"
"Classes/*/*.cpp"
"Classes/*/*.h"
)
add_executable(Server ${source_files})
And it totally worked.
If you're getting your timestamps from System.currentTimeMillis()
, then your time variables should be longs.
Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.
You can select to an anonymous type, for example
var dataset2 =
(from recordset in entities.processlists
where recordset.ProcessName == processname
select new
{
serverName = recordset.ServerName,
processId = recordset.ProcessID,
username = recordset.Username
}).ToList();
Or you can create a new class that will represent your selection, for example
public class MyDataSet
{
public string ServerName { get; set; }
public string ProcessId { get; set; }
public string Username { get; set; }
}
then you can for example do the following
var dataset2 =
(from recordset in entities.processlists
where recordset.ProcessName == processname
select new MyDataSet
{
ServerName = recordset.ServerName,
ProcessId = recordset.ProcessID,
Username = recordset.Username
}).ToList();
The error seems clear: model objects do not support item assignment.
MyModel.objects.latest('id')['foo'] = 'bar'
will throw this same error.
It's a little confusing that your model instance is called projectForm
...
To reproduce your first block of code in a loop, you need to use setattr
for k,v in session_results.iteritems():
setattr(projectForm, k, v)
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
I recently made my Music Player support all audio files locally. I did this by figuring out a way to use the vlc python module and also the VLC dll files. You can check it out: https://github.com/elibroftw/music-caster/blob/master/audio_player.py
It sounds like this
in your code is not referring to your .btn
element. Try referencing it explicitly with a selector:
var votevalue = parseInt($(".btn").data('votevalue'), 10);
Also, don't forget the radix.
Those seem to be MySQL data types.
According to the documentation they take:
tinyint
= 1 bytesmallint
= 2 bytesmediumint
= 3 bytesint
= 4 bytesbigint
= 8 bytesAnd, naturally, accept increasingly larger ranges of numbers.
You've imported the certificate into the truststore of the JRE provided in the JDK, but you are running the java.exe of the JRE installed directly.
EDIT
For clarity, and to resolve the morass of misunderstanding in the commentary below, you need to import the certificate into the cacerts
file of the JRE you are intending to use, and that will rarely if ever be the one shipping inside the JDK, because clients won't normally have a JDK. Anything in the commentary below that suggests otherwise should be ignored as not expressing my intention here.
A far better solution would be to create your own truststore, starting with a copy of the cacerts
file, and specifically tell Java to use that one via the system property javax.net.ssl.trustStore.
You should make building this part of your build process, so as to keep up to date with changes I the cacerts
file caused by JDK upgrades.
Working solution to set CultureInfo for all threads and windows.
<Application ........
Startup="Application_Startup"
>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
}
SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.
You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.
AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.
UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.
Check encoding and language:
$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR
Get all languages:
$ locale -a
Change to pt_PT.utf8:
$ export LC_ALL=pt_PT.utf8
$ export LANG="$LC_ALL"
I generally install Apache + PHP + MySQL by-hand, not using any package like those you're talking about.
It's a bit more work, yes; but knowing how to install and configure your environment is great -- and useful.
The first time, you'll need maybe half a day or a day to configure those. But, at least, you'll know how to do so.
And the next times, things will be far more easy, and you'll need less time.
Else, you might want to take a look at Zend Server -- which is another package that bundles Apache + PHP + MySQL.
Or, as an alternative, don't use Windows.
If your production servers are running Linux, why not run Linux on your development machine?
And if you don't want to (or cannot) install Linux on your computer, use a Virtual Machine.
Hi you can try viewing this jsFiddle.
I used this code:
var day = $(this).datepicker('getDate').getDate();
var month = $(this).datepicker('getDate').getMonth();
var year = $(this).datepicker('getDate').getYear();
I hope this helps.
Building PhoneGap Android app for deployment to the Google Play Store
These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova
is placed, replace it with phonegap
or ionic
, for your particular scenario.
Once you are done with the development and are ready to deploy, follow these steps:
Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).
Head over to the /path/to/your/project/, which we would refer to as the Project Root.
While at the project root, remove the "Console" plugin from your set of plugins.
The command is: cordova plugin rm cordova-plugin-console
While still at the project root, use the cordova build command to create an APK for release distribution.
The command is: cordova build --release android
The above process creates a file called android-release-unsigned.apk
in the folder ProjectRoot/platforms/android/build/outputs/apk/
Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually
At the end of this step the APK which you get can be uploaded to the Play Store.
Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.
Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.
Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.
Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?
The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/
. If you head over to the folder you would find a bunch of other folders like docs
, platform-tools
, build-tools
, tools
, add-ons
...
Open the build-tools
folder. cd build-tools
. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.
On macOS or Linux you may have to use ./zipalign
rather than simply typing in zipalign
as the documentation mentions. On Windows, zipalign
is good enough.
The &
means that the function accepts the address (or reference) to a variable, instead of the value of the variable.
For example, note the difference between this:
void af(int& g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
And this (without the &
):
void af(int g)
{
g++;
cout<<g;
}
int main()
{
int g = 123;
cout << g;
af(g);
cout << g;
return 0;
}
That's because your constructor depends on other constructors. To your constructor work correctly its necessary to other constructor works correctly which is dependent. That's why its necessary to check dependent constructors first which called by either this() or super() in your constructor. If other constructors which called by either this() or super() have a problem so whats point execute other statements because all will fail if called constructor fails.
print [key for key in locals().keys()
if isinstance(locals()[key], type(sys)) and not key.startswith('__')]
Assuming you're fine with taking all of the changes in master, what you want is:
git checkout <my branch>
to switch the working tree to your branch; then:
git merge master
to merge all the changes in master with yours.
To create a clickable reference to a channel in a Slack conversation, just type #
followed by the channel name. For example: #general
.
To share the channel URL externally, you can grab its link by control-clicking (Mac) or right-clicking (Windows) on the channel name:
The link would look like this:
https://yourteam.slack.com/messages/C69S1L3SS
Note that this link doesn't change even if you change the name of the channel. So, it is better to use this link rather than the one based on channel's name.
https://yourteam.slack.com/channels/<channel_name>
Opening the above URL from a browser would launch the Slack client (if available) or open the slack channel on the browser itself.
https://yourteam.slack.com/channels/<username>
string & replace(string & subj, string old, string neu)
{
size_t uiui = subj.find(old);
if (uiui != string::npos)
{
subj.erase(uiui, old.size());
subj.insert(uiui, neu);
}
return subj;
}
I think this fits your requirement with few code!
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
I put this function in a util file in one of the apps in my project:
import logging
import re
from django.db import connection
logger = logging.getLogger(__name__)
def sql_logger():
logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))
logger.debug('INDIVIDUAL QUERIES:')
for i, query in enumerate(connection.queries):
sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
if not sql[0]: sql = sql[1:]
sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))
Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:
# ... other imports
from .utils import sql_logger
class IngredientListApiView(generics.ListAPIView):
# ... class variables and such
# Main function that gets called when view is accessed
def list(self, request, *args, **kwargs):
response = super(IngredientListApiView, self).list(request, *args, **kwargs)
# Call our function
sql_logger()
return response
It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.
Why don't you try using only this code:
dismiss();
If you want to dismiss the Dialog Fragment by its own. You can simply put this code inside the dialog fragment where you want to dismiss the Dialog.
For example:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
This will close the recent Dialog Fragment that is shown on the screen.
Hope it helps for you.
Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/
<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>
<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>
Then, instead of $('#selector').function();
, you'd do jQuery_1_3_2('#selector').function();
or jQuery_1_1_3('#selector').function();
.
EDIT: This only applies to some versions of make
- you should check your man page.
You can also pass the -B
flag to make
. As per the man page, this does:
-B, --always-make
Unconditionally make all targets.
So make -B test
would solve your problem if you were in a situation where you don't want to edit the Makefile
or change the name of your test folder.
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
Download this jar
It resolved my problem, this is 1.7.
Not to confuse you further, but you can also use pip within your conda environment, which validates the general vs. python specific managers comments above.
conda install -n testenv pip
source activate testenv
pip <pip command>
you can also add pip to default packages of any environment so it is present each time so you don't have to follow the above snippet.
:focus
pseudo-classAs pure CSS solution, you could achieve sort of the effect by using a tabindex
attribute for the image, and :focus
pseudo-class as follows:
<img class="crossRotate" src="http://placehold.it/100" tabindex="1" />
.crossRotate {
outline: 0;
/* other styles... */
}
.crossRotate:focus {
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
Note: Using this approach, the image gets rotated onclick (focused), to negate the rotation, you'll need to click somewhere out of the image (blured).
:checked
pseudo-classThis is one of my favorite methods. In this approach, there's a hidden checkbox input and a <label>
element which wraps the image.
Once you click on the image, the hidden input is checked because of using for
attribute for the label.
Hence by using the :checked
pseudo-class and adjacent sibling selector +
, we could get the image to be rotated:
<input type="checkbox" id="hacky-input">
<label for="hacky-input">
<img class="crossRotate" src="http://placehold.it/100">
</label>
#hacky-input {
display: none; /* Hide the input */
}
#hacky-input:checked + label img.crossRotate {
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
WORKING DEMO #2 (Applying the rotate
to the label gives a better experience).
If using JavaScript/jQuery is an option, you could toggle a .active
class by .toggleClass()
to trigger the rotation effect, as follows:
$('.crossRotate').on('click', function(){
$(this).toggleClass('active');
});
.crossRotate.active {
/* vendor-prefixes here... */
transform: rotate(45deg);
}
When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
A second option to "nevets1219" is to open your CSV file in Notepad++ and do a convertion to ANSI.
Choose in the top menu : Encoding -> Convert to Ansi
on tables with many rows are two queries probably faster...
SELECT @last_id := MAX(id) FROM table;
SELECT * FROM table WHERE id = @last_id;
Right click project solution
Properties -> Configuration Properties -> C/C++ -> Precompiled Headers
Click on "Precompiled Headers" change to "Not Using Precompiled Headers".
Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.
Then you can feel free to delete the pch./stdafx. files in your project
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
yeah I have same experience
The ADB is now located in the platform-tools directory.
korsosa said Check your [sdk directory]/platform-tools directory, if it exists. If not, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), and download&install the Tools > Android SDK Platform-tools.
If you have platform-tools, you have check adb.exe file. In my case, that file was broken, so download that platform-tools again
Consider using axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});
I had this issue using fetch and axios worked perfectly.
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
This is easy one:
foreach( $_POST['field'] as $num => $val ) {
print ' '.$num.' -> '.$val.' ';
}
Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.
An example:
"c:\program files\my app\app.exe"
If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:
escapedString = """c:\program files\my app\app.exe"""
How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.
It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.
If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):
"c:\program files\my app\app.exe" "c:\documents and settings\steve"
I would enter this:
escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""
I've helped my sysadmins with some VBScripts that have had even more quotes.
It's not pretty, but that's how it works.
MIME stands for Multi-purpose Internet Mail Extensions. MIME types form a standard way of classifying file types on the Internet. Internet programs such as Web servers and browsers all have a list of MIME types, so that they can transfer files of the same type in the same way, no matter what operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword.
Although there is a complete list of MIME types, it does not list the extensions associated with the files, nor a description of the file type. This means that if you want to find the MIME type for a certain kind of file, it can be difficult. Sometimes you have to look through the list and make a guess as to the MIME type of the file you are concerned with.
In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.
Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.
Possibly every remotely modern compiler implements #pragma pack
which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)
From C99 §6.7.2.1:
12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.
13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
You need this instead:
if(s.contains("+"))
contains()
method of String
class does not take regular expression as a parameter, it takes normal text.
EDIT:
String s = "ddjdjdj+kfkfkf";
if(s.contains("+"))
{
String parts[] = s.split("\\+");
System.out.print(parts[0]);
}
OUTPUT:
ddjdjdj
Here is my simple solution:
1 - Define your fragment
public class MyFragment extends Fragment {
private String parameter;
public MyFragment() {
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
2 - Create your new fragment and populate the parameter
myfragment = new MyFragment();
myfragment.setParameter("here the value of my parameter");
3 - Enjoy it!
Obviously you can change the type and the number of parameters. Quick and easy.
Detecting mobile devices
Related answer: https://stackoverflow.com/a/13805337/1306809
There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.
Did you try RedirectView where you can provide the contextRelative parameter?
Pass 65536
to mysql_connect
as 5th parameter.
Example:
$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */)
or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);
DELETE FROM table3 WHERE field6 = 6;
UPDATE table4 SET field7 = 7 WHERE field8 = 8;
INSERT INTO table5
SELECT t6.field11, t6.field12, t7.field13
FROM table6 t6
INNER JOIN table7 t7 ON t7.field9 = t6.field10;
-- etc
");
When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.
For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
INSERT INTO table1 (field1,field2) VALUES(1,2);
SELECT * FROM table2;
");
Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.
$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
SELECT * FROM table2;
INSERT INTO table1 (field1,field2) VALUES(1,2);
");
class Person
{
/// Gets/sets a value indicating whether auto
/// save of review layer is enabled or not
[System.ComponentModel.DefaultValue(true)]
public bool AutoSaveReviewLayer { get; set; }
}
Step-1 Need to find user details by using below query
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB EXPIRED
Step-2 Get users password by using below query.
SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';
ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
Step -3 Run Above alter query
SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.
Step-4 :Check users account status
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB OPEN
You can try something like the following:
h1{
margin-bottom:<x>px;
}
div{
margin-bottom:<y>px;
}
div:last-of-type{
margin-bottom:0;
}
or instead of the first h1
rule:
div:first-of-type{
margin-top:<x>px;
}
or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:
div + div{
margin-bottom:<y>px;
}
Respectively, h1 + div
would control the first div after your header, giving you additional styling options.
When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.
Properties files from where? Your main jar? Dependencies?
In the former case, putting resources under src/test/resources
as suggested is probably the most straight forward and simplest option.
In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude
in the unpackOptions
.
After copying from A to B open file A again to write mode and then write empty string in it
I think this is the best way:
this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
I had this problem on a project I run on Netbeans. I simply right clicked on the file and update to fix it (after SVN up).
Create a class TestUserDetailsImpl
on your test package:
@Service
@Primary
@Profile("test")
public class TestUserDetailsImpl implements UserDetailsService {
public static final String API_USER = "[email protected]";
private User getAdminUser() {
User user = new User();
user.setUsername(API_USER);
SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_API_USER");
user.setAuthorities(Collections.singletonList(role));
return user;
}
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
if (Objects.equals(username, ADMIN_USERNAME))
return getAdminUser();
throw new UsernameNotFoundException(username);
}
}
Rest endpoint:
@GetMapping("/invoice")
@Secured("ROLE_API_USER")
public Page<InvoiceDTO> getInvoices(){
...
}
Test endpoint:
@Test
@WithUserDetails("[email protected]")
public void testApi() throws Exception {
...
}
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.
$.event.special.widthChanged = {
remove: function() {
$(this).children('iframe.width-changed').remove();
},
add: function () {
var elm = $(this);
var iframe = elm.children('iframe.width-changed');
if (!iframe.length) {
iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
}
var oldWidth = elm.width();
function elmResized() {
var width = elm.width();
if (oldWidth != width) {
elm.trigger('widthChanged', [width, oldWidth]);
oldWidth = width;
}
}
var timer = 0;
var ielm = iframe[0];
(ielm.contentWindow || ielm).onresize = function() {
clearTimeout(timer);
timer = setTimeout(elmResized, 20);
};
}
}
It requires the following css :
iframe.width-changed {
width: 100%;
display: block;
border: 0;
height: 0;
margin: 0;
}
You can see it in action here widthChanged fiddle
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
A script that runs hourly to retrain my spam filters based two IMAP folder where span and ham are put.
#!/bin/sh
FNDIR="train-as-spam"
FPDIR="train-as-ham"
for dir in /home/*/.maildir
do
cd "${dir}"
USER=`stat -c %U .`
SRCDIR="${dir}/.${FNDIR}"
if [ ! -d ${SRCDIR} ]; then
echo no "${SRCDIR}" directory
else
cd "${SRCDIR}/cur"
ls -tr | while read file
do
if grep -q "^X-DSPAM" "${file}"; then
SOURCE="error"
else
SOURCE="corpus"
fi
dspam --user "${USER}" --class=spam --source="${SOURCE}" --deliver=innocent,spam --stdout < "${file}" > "../tmp/${file}"
mv "../tmp/${file}" "${dir}/new/${file%%:*}" && rm "${file}"
done
fi
SRCDIR="${dir}/.${FPDIR}"
if [ ! -d ${SRCDIR} ]; then
echo no "${SRCDIR}" directory
else
cd "${SRCDIR}/cur"
ls -tr | while read file
do
if grep -q "^X-DSPAM" "${file}"; then
SOURCE="error"
else
SOURCE="corpus"
fi
dspam --user "${USER}" --class=innocent --source="${SOURCE}" --deliver=innocent,spam --stdout < "${file}" > "../tmp/${file}"
mv "../tmp/${file}" "${dir}/new/${file%%:*}" && rm "${file}"
done
fi
done
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
If you are to use the
<!-- saved from url=(0014)about:internet -->
or
<!-- saved from url=(0016)http://localhost -->
make sure the HTML file is saved in windows/dos format with "\r\n" as line breaks after the statement. Otherwise I couldn't make it work.
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the futureWebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
white-space: normal;
word-wrap: break-word;
"Both" worked for me.