This question seems to be the most popular one for disabling textarea
wrap. However, as of April 2017 I find that IE 11 (11.0.9600) will not disable word wrap with any of the above solutions.
The only solution which does work for IE 11 is wrap="off"
. wrap="soft"
and/or the various CSS attributes like white-space: pre
alter where IE 11 chooses to wrap but it still wraps somewhere. Note that I have tested this with or without Compatibility View. IE 11 is pretty HTML 5 compatible, but not in this case.
Thus, to achieve lines which retain their whitespace and go off the right-hand side I am using:
<textarea style="white-space: pre; overflow: scroll;" wrap="off">
Fortuitously this does seem to work in Chrome & Firefox too. I am not defending the use of pre-HTML 5 wrap="off"
, just saying that it seems to be required for IE 11.
Alternatively you can do like this.
RUN addgroup demo && adduser -DH -G demo demo
First command creates group called demo. Second command creates demo user and adds him to previously created demo group.
Flags stands for:
-G Group
-D Don't assign password
-H Don't create home directory
By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..
Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.
I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final")
.
When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.
Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.
libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)
This is for play 2.2.x
. In previous versions there were some differences in the build files.
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").
git merge -s ort
This comes from this thread from Elijah Newren:
For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).
But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch
$GIT_WORK_TREE
or$GIT_INDEX_FILE
will allow for some fun new features.
That's the hope anyway.
In the ideal world, we should:
ask
unpack_trees()
to do "read-tree -m
" without "-u
";do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;
compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
And then finallycarry out the working tree update to make it match what the resulting in-core index says it should look like.
Result:
See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit a1f9595, 18 Nov 2020)
merge-ort
: barebones API of new merge strategy with empty implementationSigned-off-by: Elijah Newren
This is the beginning of a new merge strategy.
While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for
merge-recursive.c
.However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.
And:
See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit 66c62ea, 18 Nov 2020)
t6423, t6436
: note improved ort handling with dirty filesSigned-off-by: Elijah Newren
The "recursive" backend relies on
unpack_trees()
to check if unstaged changes would be overwritten by a merge, butunpack_trees()
does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.
t6423
: expect improved conflict markers labels in the ort backendSigned-off-by: Elijah Newren
Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the
:FILENAME
piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).However, there were cases where the
:FILENAME
annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.
t6404, t6423
: expect improved rename/delete handling in ort backendSigned-off-by: Elijah Newren
When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.
Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually '
git rm
'(man) the old version as well as 'git add
'(man) the new one).rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive
" or "ort
" merge strategies are in use.
With Git 2.30 (Q1 2021), Preparation for a new merge strategy.
See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit 66c62ea, 18 Nov 2020)
merge tests
: expect improved directory/file conflict handling in ortSigned-off-by: Elijah Newren
merge-recursive.c
is built on the idea of runningunpack_trees()
and then "doing minor touch-ups" to get the result.
Unfortunately,unpack_trees()
was run in an update-as-it-goes mode, leadingmerge-recursive.c
to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a '
git merge --abort
'(man) or 'git rebase --abort
'(man).It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changingmerge-recursive.c
to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).
With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:
See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster
).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit f9d29da, 06 Jan 2021)
merge-ort
: add implementation ofrecord_conflicted_index_entries()
Signed-off-by: Elijah Newren
After
checkout()
, the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.We do this by looping over the conflicted entries, marking the existing index entry for the path with
CE_REMOVE
, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing theCE_REMOVED-marked
cache entries and sorting the index.
With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.
See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit 2856089, 25 Jan 2021)
Example:
merge-ort
: add implementation of normal rename handlingSigned-off-by: Elijah Newren
Implement handling of normal renames.
This code replaces the following frommerge-recurisve.c
:
- the code relevant to
RENAME_NORMAL
inprocess_renames()
- the
RENAME_NORMAL
case ofprocess_entry()
Also, there is some shared code from
merge-recursive.c
for multiple different rename cases which we will no longer need for this case (or other rename cases):
handle_rename_normal()
setup_rename_conflict_info()
The consolidation of four separate codepaths into one is made possible by a change in design:
process_renames()
tweaks theconflict_info
entries withinopt->priv->paths
such thatprocess_entry()
can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).
That, together with letting worktree/index updating be handled orthogonally in the
merge_switch_to_result()
function, dramatically simplifies the code for various special rename cases.(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)
And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.
See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren
).
(Merged by Junio C Hamano -- gitster
-- in commit b65b9ff, 05 Feb 2021)
merge-ort
: add handling for different types of files at same pathSigned-off-by: Elijah Newren
Add some handling that explicitly considers collisions of the following types:
- file/submodule
- file/symlink
- submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.
Note that in the case of recursive handling (i.e.
call_depth > 0
), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.
This previous question mentions using qSleep()
which is in the QtTest
module. To avoid the overhead linking in the QtTest
module, looking at the source for that function you could just make your own copy and call it. It uses defines to call either Windows Sleep()
or Linux nanosleep()
.
#ifdef Q_OS_WIN
#include <windows.h> // for Sleep
#endif
void QTest::qSleep(int ms)
{
QTEST_ASSERT(ms > 0);
#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
The important thing is that you know what those terms mean to your colleagues. Different groups will have slightly varying definitions of what they mean when they say "full end-to-end" tests, for instance.
I came across Google's naming system for their tests recently, and I rather like it - they bypass the arguments by just using Small, Medium, and Large. For deciding which category a test fits into, they look at a few factors - how long does it take to run, does it access the network, database, filesystem, external systems and so on.
http://googletesting.blogspot.com/2010/12/test-sizes.html
I'd imagine the difference between Small, Medium, and Large for your current workplace might vary from Google's.
However, it's not just about scope, but about purpose. Mark's point about differing perspectives for tests, e.g. programmer vs customer/end user, is really important.
Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:
File Thread Safe VC Bulid
php_sqlsrv_53_nts_vc6.dll No VC6
php_sqlsrv_53_nts_vc9.dll No VC9
php_sqlsrv_53_ts_vc6.dll Yes VC6
php_sqlsrv_53_ts_vc9.dll Yes VC9
You can see the Thread Safety status in phpinfo().
Add the correct file to your ext directory and the following line to your php.ini:
extension=php_sqlsrv_53_*_vc*.dll
Use the filename of the file you used.
As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*
Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.
In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2
To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.
Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.
The simplest way to log to stdout:
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
This could be what you want
cat file | grep pattern | paste -sd' '
As to your edit, I'm not sure what it means, perhaps this?
cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g'
(this assumes that ~
does not occur in file
)
They are exactly the same. When you use it be consistent. Use one of them in your database
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
if in a DataRow the row["fieldname"] isDbNull replace it with 0 otherwise get the decimal value:
decimal result = rw["fieldname"] as decimal? ?? 0;
On Windows, you need to download it and install the .exe
You can encode the <
and >
to their HTML equivelant.
html = html.replace(/</g, "<").replace(/>/g, ">");
Like this :
Body -> form-data -> select file
You must write "file" instead of "name"
Also you can send JSON data from Body -> raw field. (Just paste JSON string)
In LINQ you could do something like:
foreach (var data in from DataRow row in dataTable.Rows
from DataColumn col in dataTable.Columns
where
row[col] != null
select row[col])
{
// do something with data
}
In Sql Server
You can do this using cross apply
Select
ColumnA,
ColumnB,
c.calccolumn1 As calccolumn1,
c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.
I can't quite remember the php CLI syntax, but you'd want something like:
exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");
I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.
Can you remove the headers element in @RequestMapping and try..
Like
@RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)
I guess spring does an 'contains check' rather than exact match for accept headers. But still, worth a try to remove the headers element and check.
To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.
<select class="form-control glyphicon">
<option value="">− − − Hello</option>
<option value="glyphicon-list-alt"> Text</option>
</select>
Here's a list of the icons with their unicode:
mkdir -p `dirname /destination/moved_file_name.txt`
mv /full/path/the/file.txt /destination/moved_file_name.txt
There are multiple ways of reshaping a PyTorch tensor. You can apply these methods on a tensor of any dimensionality.
Let's start with a 2-dimensional 2 x 3
tensor:
x = torch.Tensor(2, 3)
print(x.shape)
# torch.Size([2, 3])
To add some robustness to this problem, let's reshape the 2 x 3
tensor by adding a new dimension at the front and another dimension in the middle, producing a 1 x 2 x 1 x 3
tensor.
None
Use NumPy-style insertion of None
(aka np.newaxis
) to add dimensions anywhere you want. See here.
print(x.shape)
# torch.Size([2, 3])
y = x[None, :, None, :] # Add new dimensions at positions 0 and 2.
print(y.shape)
# torch.Size([1, 2, 1, 3])
Use torch.Tensor.unsqueeze(i)
(a.k.a. torch.unsqueeze(tensor, i)
or the in-place version unsqueeze_()
) to add a new dimension at the i'th dimension. The returned tensor shares the same data as the original tensor. In this example, we can use unqueeze()
twice to add the two new dimensions.
print(x.shape)
# torch.Size([2, 3])
# Use unsqueeze twice.
y = x.unsqueeze(0) # Add new dimension at position 0
print(y.shape)
# torch.Size([1, 2, 3])
y = y.unsqueeze(2) # Add new dimension at position 2
print(y.shape)
# torch.Size([1, 2, 1, 3])
In practice with PyTorch, adding an extra dimension for the batch may be important, so you may often see unsqueeze(0)
.
Use torch.Tensor.view(*shape)
to specify all the dimensions. The returned tensor shares the same data as the original tensor.
print(x.shape)
# torch.Size([2, 3])
y = x.view(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])
Use torch.Tensor.reshape(*shape)
(aka torch.reshape(tensor, shapetuple)
) to specify all the dimensions. If the original data is contiguous and has the same stride, the returned tensor will be a view of input (sharing the same data), otherwise it will be a copy. This function is similar to the NumPy reshape()
function in that it lets you define all the dimensions and can return either a view or a copy.
print(x.shape)
# torch.Size([2, 3])
y = x.reshape(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])
Furthermore, from the O'Reilly 2019 book Programming PyTorch for Deep Learning, the author writes:
Now you might wonder what the difference is between view()
and reshape()
. The answer is that view()
operates as a view on the original tensor, so if the underlying data is changed, the view will change too (and vice versa). However, view()
can throw errors if the required view is not contiguous; that is, it doesn’t share the same block of memory it would occupy if a new tensor of the required shape was created from scratch. If this happens, you have to call tensor.contiguous()
before you can use view()
. However, reshape()
does all that behind the scenes, so in general, I recommend using reshape()
rather than view()
.
Use the in-place function torch.Tensor.resize_(*sizes)
to modify the original tensor. The documentation states:
WARNING. This is a low-level method. The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged). For most purposes, you will instead want to use view()
, which checks for contiguity, or reshape()
, which copies data if needed. To change the size in-place with custom strides, see set_()
.
print(x.shape)
# torch.Size([2, 3])
x.resize_(1, 2, 1, 3)
print(x.shape)
# torch.Size([1, 2, 1, 3])
If you want to add just one dimension (e.g. to add a 0th dimension for the batch), then use unsqueeze(0)
. If you want to totally change the dimensionality, use reshape()
.
What's the difference between reshape and view in pytorch?
What is the difference between view() and unsqueeze()?
In PyTorch 0.4, is it recommended to use reshape
than view
when it is possible?
Select the column with duplicate values then go to Data Tab, Then Data Tools select remove duplicate select 1) "Continue with the current selection" 2) Click on Remove duplicate.... button 3) Click "Select All" button 4) Click OK
now you get the unique value list.
Not sure if this is faster, but at least it's shorter :)
int rows = new DataView(dtFoo, "IsActive = 'Y'", "IsActive",
DataViewRowState.CurrentRows).Table.Rows.Count;
I always avoid using float:left
but instead I use display: inline
.wrapper-class input[type="radio"] {_x000D_
width: 15px;_x000D_
}_x000D_
_x000D_
.wrapper-class label {_x000D_
display: inline;_x000D_
margin-left: 5px;_x000D_
}
_x000D_
<div class="wrapper-class">_x000D_
<input type="radio" id="radio1">_x000D_
<label for="radio1">Test Radio</label>_x000D_
</div>
_x000D_
If you are doing in code then first check for table in database by using query SELECT table_name FROM user_tables WHERE table_name = 'XYZ'
if record found then truncate table otherwise create Table
Work like Create or Replace.
Use prop()
for updating the hidden property, and change()
for handling the change event.
$('#check').change(function() {_x000D_
$("#delete").prop("hidden", !this.checked);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<input id="check" type="checkbox" name="del_attachment_id[]" value="<?php echo $attachment['link'];?>">_x000D_
</td>_x000D_
_x000D_
<td id="delete" hidden="true">_x000D_
the file will be deleted from the newsletter_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
All this arises because git does not provide an option in clone/pull/push/fetch commands to send the credentials through a pipe. Though it gives credential.helper, it stores on the file system or creates a daemon etc. Often, the credentials of GIT are system level ones and onus to keep them safe is on the application invoking the git commands. Very unsafe indeed.
Here is what I had to work around. 1. Git version (git --version) should be greater than or equal to 1.8.3.
GIT CLONE
For cloning, use "git clone URL" after changing the URL from the format, http://{myuser}@{my_repo_ip_address}/{myrepo_name.git} to http://{myuser}:{mypwd}@{my_repo_ip_address}/{myrepo_name.git}
Then purge the repository of the password as in the next section.
PURGING
Now, this would have gone and
If your application is using Java to issue these commands, use ProcessBuilder instead of Runtime. If you must use Runtime, use getRunTime().exec which takes String array as arguments with /bin/bash and -c as arguments rather then the one which takes a single String as argument.
GIT FETCH/PULL/PUSH
I could not really work with the above. So this might help someone.
$http.get(url)
.then(
function(response) {
console.log('get',response)
}
).catch(
function(response) {
console.log('return code: ' + response.status);
}
)
See also the $http response
parameter.
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters) _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
JavaScript:
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
//get the month_x000D_
var month = d.getMonth();_x000D_
//get the day_x000D_
//convert day to string_x000D_
var day = d.getDate().toString();_x000D_
//get the year_x000D_
var year = d.getFullYear();_x000D_
_x000D_
//pull the last two digits of the year_x000D_
year = year.toString().substr(-2);_x000D_
_x000D_
//increment month by 1 since it is 0 indexed_x000D_
//converts month to a string_x000D_
month = (month + 1).toString();_x000D_
_x000D_
//if month is 1-9 pad right with a 0 for two digits_x000D_
if (month.length === 1)_x000D_
{_x000D_
month = "0" + month;_x000D_
}_x000D_
_x000D_
//if day is between 1-9 pad right with a 0 for two digits_x000D_
if (day.length === 1)_x000D_
{_x000D_
day = "0" + day;_x000D_
}_x000D_
_x000D_
//return the string "MMddyy"_x000D_
return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
there's a better way
# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:
split(string str, string pat)
Split str around pat (pat is a regular expression)
In your case, the delimiter "|
" has a special meaning as a regular expression, so it should be referred to as "\\|
".
In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),
I tried running the following code
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
fig, ax = plt.scatter(z, y)
for i, txt in enumerate(n):
ax.annotate(txt, (z[i], y[i]))
But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)
I eventually solved the error using the following code
plt.scatter(z, y)
for i, txt in enumerate(n):
plt.annotate(txt, (z[i], y[i]))
I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.
You want to use the array_key_exists function.
actually I didnt understand what do you want to do. As I understand, you can write this code another way like this. Are you asking this or not? Can you explain more?
string s = string.Empty;
if(!string.IsNullOrEmpty(myObj))
{
s = myObj.ToString();
}
UPDATE: Well, initially I posted the solution to a more difficult problem, to get a complete split of any string with any delimiter (just changing delims). I read more the accepted solutions than what the OP wanted, sorry. I think this time I comply with the original requirements:
@echo off
IF [%1] EQU [] echo get n ["user_string"] & goto :eof
set token=%1
set /a "token+=1"
set string=
IF [%2] NEQ [] set string=%2
IF [%2] EQU [] set string="AAA BBB CCC DDD EEE FFF"
FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G
An other version with a better user interface:
@echo off
IF [%1] EQU [] echo USAGE: get ["user_string"] n & goto :eof
IF [%2] NEQ [] set string=%1 & set token=%2 & goto update_token
set string="AAA BBB CCC DDD EEE FFF"
set token=%1
:update_token
set /a "token+=1"
FOR /F "tokens=%TOKEN%" %%G IN (%string%) DO echo %%~G
Output examples:
E:\utils\bat>get
USAGE: get ["user_string"] n
E:\utils\bat>get 5
FFF
E:\utils\bat>get 6
E:\utils\bat>get "Hello World" 1
World
This is a batch file to split the directories of the path:
@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO (
for /f "tokens=*" %%g in ("%%G") do echo %%g
set string="%%H"
)
if %string% NEQ "" goto :loop
2nd version:
@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO set line="%%G" & echo %line:"=% & set string="%%H"
if %string% NEQ "" goto :loop
3rd version:
@echo off
set string="%PATH%"
:loop
FOR /F "tokens=1* delims=;" %%G IN (%string%) DO CALL :sub "%%G" "%%H"
if %string% NEQ "" goto :loop
goto :eof
:sub
set line=%1
echo %line:"=%
set string=%2
Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:
<root>
<level value="ALL" />
<appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
<level value="ALL" />
<appender-ref ref="File1Appender2" />
</logger>
This is how I have done it in the past. Then something like this for the other log:
private static readonly ILog otherLog = LogManager.GetLogger("SomeName");
And you can get your normal logger as follows:
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Read the loggers and appenders section of the documentation to understand how this works.
just to add some clarity, you need to stage changes with git add
, then amend last commit:
git add /path/to/modified/files
git commit --amend --no-edit
This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.
...came here from a google search
I found the answer elsewhere here --> https://stackoverflow.com/a/15621223/1093174
which was to raise the connection idle timeout of my AWS elastic load balancer!
(I had setup a Django site with nginx/apache reverse proxy, and a really really really log backend job/view was timing out)
I know I'm late but my preferred way is:
:programend
pause>nul
GOTO programend
In this way the user cannot exit using enter.
Try this one:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);
You can add any format you want. That works for me!
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
iloc
df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]
In Eclipse you can set a VM argument to:
-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}
Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.
The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.
Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.
Try
#include <inttypes.h>
...
printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);
The z
represents an integer of length same as size_t
, and the PRIu32
macro, defined in the C99 header inttypes.h
, represents an unsigned 32-bit integer.
Base ond defualt config of 5.7.5 ONLY_FULL_GROUP_BY You should use all the not aggregate column in your group by
select libelle,credit_initial,disponible_v,sum(montant) as montant
FROM fiche,annee,type
where type.id_type=annee.id_type
and annee.id_annee=fiche.id_annee
and annee = year(current_timestamp)
GROUP BY libelle,credit_initial,disponible_v order by libelle asc
If you're looking to match non-blank values or empty cells and having difficulty with wildcard character, I found the solution below from here.
Dim n as Integer
n = Worksheets("Sheet1").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
As noted in comments, some of this becomes irrelevant in Java 8, where final
can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.
It's basically due to the way Java manages closures.
When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)
As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.
Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.
If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)
Quick helper method that might address this situation:
<T> T onlyItem(Collection<T> items) {
if (items.size() != 1)
throw new IllegalArgumentException("Collection must have single item; instead it has " + items.size());
return items.iterator().next();
}
Simple: http://jsfiddle.net/Xxk3F/3/
$('.phone').text(function(i, text) {
return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});
Or: http://jsfiddle.net/Xxk3F/1/
$('.phone').text(function(i, text) {
return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});
Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.
There are many options, for example:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))
here's a good way to do it
function isEmpty(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else if (typeof obj === 'object') {
for (var i in obj) {
return false;
}
return true;
} else {
return !obj;
}
}
You can subclass JPanel - here is an extract from my ImagePanel, which puts an image in any one of 5 locations, top/left, top/right, middle/middle, bottom/left or bottom/right:
protected void paintComponent(Graphics gc) {
super.paintComponent(gc);
Dimension cs=getSize(); // component size
gc=gc.create();
gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));
if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2) +mmHrzShift),(((cs.height-mmSize.height)/2) +mmVrtShift),null); }
if(tlImage!=null) { gc.drawImage(tlImage,(insets.left +tlHrzShift),(insets.top +tlVrtShift),null); }
if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top +trVrtShift),null); }
if(blImage!=null) { gc.drawImage(blImage,(insets.left +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }
if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }
}
If you are in early development cycle and don't care about your current database data you can just remove it and then migrate. But first you need to clean migrations dir and remove its rows from table (django_migrations)
rm your_app/migrations/*
rm db.sqlite3
python manage.py makemigrations
python manage.py migrate
You are really talking about serialization, which can take many forms. Since you want small and binary, protocol buffers may be a viable option - giving version tolerance and portability as well. Unlike BinaryFormatter
, the protocol buffers wire format doesn't include all the type metadata; just very terse markers to identify data.
In .NET there are a few implementations; in particular
I'd humbly argue that protobuf-net (which I wrote) allows more .NET-idiomatic usage with typical C# classes ("regular" protocol-buffers tends to demand code-generation); for example:
[ProtoContract]
public class Person {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name {get;set;}
}
....
Person person = new Person { Id = 123, Name = "abc" };
Serializer.Serialize(destStream, person);
...
Person anotherPerson = Serializer.Deserialize<Person>(sourceStream);
I don't work with contiguous ranges all the time. My solution for non-contiguous ranges is as follows (includes some code from other answers here):
Sub test_inters()
Dim rng1 As Range
Dim rng2 As Range
Dim inters As Range
Set rng2 = Worksheets("Gen2").Range("K7")
Set rng1 = ExcludeCell(Worksheets("Gen2").Range("K6:K8"), rng2)
If (rng2.Parent.name = rng1.Parent.name) Then
Dim ints As Range
MsgBox rng1.Address & vbCrLf _
& rng2.Address & vbCrLf _
For Each cell In rng1
MsgBox cell.Address
Set ints = Application.Intersect(cell, rng2)
If (Not (ints Is Nothing)) Then
MsgBox "Yes intersection"
Else
MsgBox "No intersection"
End If
Next cell
End If
End Sub
Your div
variable is a string, not a DOM element object:
var div = '<div>top div</div>';
Strings don't have an appendChild
method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:
var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));
div.appendChild(element);
You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).
For everything else you can use dictionary, or a utility class like this one:
>>> class Bunch:
... def __init__(self, **kwds):
... self.__dict__.update(kwds)
...
>>> mystruct = Bunch(field1=value1, field2=value2)
I think the "definitive" discussion is here, in the published version of the Python Cookbook.
A little optimization of the class before. In this version the files are not totally loaded into memory.
Security advice: a check for the boundary is missing, if the file contains the bounday it will crash.
namespace WindowsFormsApplication1
{
public static class FormUpload
{
private static string NewDataBoundary()
{
Random rnd = new Random();
string formDataBoundary = "";
while (formDataBoundary.Length < 15)
{
formDataBoundary = formDataBoundary + rnd.Next();
}
formDataBoundary = formDataBoundary.Substring(0, 15);
formDataBoundary = "-----------------------------" + formDataBoundary;
return formDataBoundary;
}
public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)
{
string boundary = NewDataBoundary();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
// Set up the request properties
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.UserAgent = "PhasDocAgent 1.0";
request.CookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
request.CookieContainer.Add(cookie);
}
#region WRITING STREAM
using (Stream formDataStream = request.GetRequestStream())
{
foreach (var param in postParameters)
{
if (param.Value.StartsWith("file://"))
{
string filepath = param.Value.Substring(7);
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
Path.GetFileName(filepath) ?? param.Key,
MimeTypes.GetMime(filepath));
formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
// Write the file data directly to the Stream, rather than serializing it to a string.
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(filepath, FileMode.Open);
for (int i = 0; i < fs.Length; )
{
int k = fs.Read(buffer, 0, buffer.Length);
if (k > 0)
{
formDataStream.Write(buffer, 0, k);
}
i = i + k;
}
fs.Close();
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
boundary,
param.Key,
param.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
}
}
// Add the end of the request
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
formDataStream.Write(footer, 0, footer.Length);
request.ContentLength = formDataStream.Length;
formDataStream.Close();
}
#endregion
return request.GetResponse() as HttpWebResponse;
}
}
}
Fought the same problem for about an hour. I finally realized that I was referencing some image files in an xml file that I did not yet have in my R.drawable folder. As soon as I copied the files into the folder, the problem went away. You need to make sure you have all the necessary files present.
You need to do two things. First add the changes with
git add .
git stash
git checkout <some branch>
It should solve your issue as it solved to me.
In your apps.js just add
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
Now you can use ejs view engine while keeping your view files as .html
source: http://www.makebetterthings.com/node-js/how-to-use-html-with-express-node-js/
You need to install this two packages:
`npm install ejs --save`
`npm install path --save`
And then import needed packages:
`var path = require('path');`
This way you can save your views as .html instead of .ejs.
Pretty helpful while working with IDEs that support html but dont recognize ejs.
make sure ,use this 404 route wrote on the bottom of the code.
syntax will be like
{
path: 'page-not-found',
component: PagenotfoundComponent
},
{
path: '**',
redirectTo: '/page-not-found'
},
Thank you
List<Customer> list = ...;
Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");
john will be null if no customer exists with a first name of "John".
In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)
This is a bit of a hack, but adding these to the script made it start correctly:
add:
DBDIR=/database/mongodb
change:
DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}
to:
DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.
Here's a simplified version, using XmlReader and MoveToContent().
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx
using (XmlReader xmlReader = XmlReader.Create(p_fileName))
{
if (xmlReader.MoveToContent() == XmlNodeType.Element)
rootNodeName = xmlReader.Name;
}
For the syntax, it looks like this (leave out the column list to implicitly mean "all")
INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'
For avoiding primary key errors if you already have data in the archive table
INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
AND a.id is null # does not yet exist in archive
private fun compareCategory(
categories: List<String>?,
category: String
) = categories?.any { it.equals(category, true) } ?: false
If you look at the inheritance tree (in version 2.6), HTMLParser
inherits from SGMLParser
which inherits from ParserBase
which doesn't inherits from object
. I.e. HTMLParser is an old-style class.
About your checking with isinstance
, I did a quick test in ipython:
In [1]: class A: ...: pass ...: In [2]: isinstance(A, object) Out[2]: True
Even if a class is old-style class, it's still an instance of object
.
Normally you can use None
, but you can also use objc.NULL
, e.g.
import objc
val = objc.NULL
Especially useful when working with C code in Python.
Also see: Python objc.NULL Examples
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.
You can do this directly from an open notebook:
!pip install jupyterthemes
!jt -t chesterish
Instead of isset()
you can use something shorter getting errors muted, it is @$_POST['field']
. Then, if the field is not set, you'll get no error printed on a page.
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
To be sure I need to see how you're rendering the form. The initial value is only used in a unbound form, if it's bound and a value for that field is not included nothing will be selected.
I'd suggest that the -i
means it does match "ABC", but the difference is in the output. -i
doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o
says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.
The output of echo "ABC" | grep -i abc
is ABC
, the -o
shows output matching "abc" so nothing shows:
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
It is called an array initializer and can be explained in the Java specification 10.6.
This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.
Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.
if you have a list a and then following statements
list<int>::iterator it; // declare an iterator
list<int>::const_iterator cit; // declare an const iterator
it=a.begin();
cit=a.begin();
you can change the contents of the element in the list using “it” but not “cit”, that is you can use “cit” for reading the contents not for updating the elements.
*it=*it+1;//returns no error
*cit=*cit+1;//this will return error
Indeed using {{ URL:previous() }}
do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.
In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.
When I use URL:previous()
, Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:
<a href="javascript:history.back()" class="btn btn-default">Voltar</a>
I'm tested this on Laravel 5.3, just for clarification.
One thing that I've not seen mentioned is that killing threads is generally a Bad Idea. There are techniques for making threaded methods cleanly abortable, but that's different to just killing a thread after a timeout.
The risk with what you're suggesting is that you probably don't know what state the thread will be in when you kill it - so you risk introducing instability. A better solution is to make sure your threaded code either doesn't hang itself, or will respond nicely to an abort request.
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index
is the array index of your car, or -1 if it doesn't exist.
try this:
streetaddress.substring(0, streetaddress.indexOf(','));
In your stylesheet add
{
padding:0px;
margin:0px;
border: 0px
}
This is also a viable option.
You need to create an alias for the mother.kind
. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
Here is a simple example to bring an overlay effect with a loading icon over another div.
<style>
#overlay {
position: absolute;
width: 100%;
height: 100%;
background: black url('icons/loading.gif') center center no-repeat; /* Make sure the path and a fine named 'loading.gif' is there */
background-size: 50px;
z-index: 1;
opacity: .6;
}
.wraper{
position: relative;
width:400px; /* Just for testing, remove width and height if you have content inside this div */
height:500px; /* Remove this if you have content inside */
}
</style>
<h2>The overlay tester</h2>
<div class="wraper">
<div id="overlay"></div>
<h3>Apply the overlay over this div</h3>
</div>
Try it here: http://jsbin.com/fotozolucu/edit?html,css,output
Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.
$key = array_search("Mark As Spam", $array);
unset($array[$key]);
For 2D arrays...
$remove = array("Mark As Spam", "Completed");
foreach($arrays as $array){
foreach($array as $key => $value){
if(in_array($value, $remove)) unset($array[$key]);
}
}
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
Some people may not like it, but this is what I do:
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
if (progressBar.Value < progressBar.Maximum)
progressBar.Increment(5);
else
progressBar.Value = progressBar.Minimum;
}
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.
I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;}
but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:
CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
This will give you the culture your UI is (texts on windows, message boxes, etc).
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);
The parameter TRUE preserve the changes.
For more details refer to MSDN.
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
Although Dennis and gengkev solutions of using Blob/FileReader work, I wouldn't suggest taking that approach. It is an async approach to a simple problem, and it is much slower than a direct solution. I've made a post in html5rocks with a simpler and (much faster) solution: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
And the solution is:
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
EDIT:
The Encoding API helps solving the string conversion problem. Check out the response from Jeff Posnik on Html5Rocks.com to the above original article.
Excerpt:
The Encoding API makes it simple to translate between raw bytes and native JavaScript strings, regardless of which of the many standard encodings you need to work with.
<pre id="results"></pre>
<script>
if ('TextDecoder' in window) {
// The local files to be fetched, mapped to the encoding that they're using.
var filesToEncoding = {
'utf8.bin': 'utf-8',
'utf16le.bin': 'utf-16le',
'macintosh.bin': 'macintosh'
};
Object.keys(filesToEncoding).forEach(function(file) {
fetchAndDecode(file, filesToEncoding[file]);
});
} else {
document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
}
// Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
function fetchAndDecode(file, encoding) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file);
// Using 'arraybuffer' as the responseType ensures that the raw data is returned,
// rather than letting XMLHttpRequest decode the data first.
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (this.status == 200) {
// The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
var dataView = new DataView(this.response);
// The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
var decoder = new TextDecoder(encoding);
var decodedString = decoder.decode(dataView);
// Add the decoded file's text to the <pre> element on the page.
document.querySelector('#results').textContent += decodedString + '\n';
} else {
console.error('Error while requesting', file, this);
}
};
xhr.send();
}
</script>
This is probably not the solution for everyone, but it was for me.
If you are using NVM, you might not have enabled the right version of node for the code you are running. After you reboot, your default version of node changes back to the system default.
Was running into this when working with react-native which had been working fine. Just use nvm to use the right version of node to solve this problem.
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
Put your assets in the public folder
public/css
public/images
public/fonts
public/js
And them called it using Laravel
{{ HTML::script('js/scrollTo.js'); }}
{{ HTML::style('css/css.css'); }}
The array has a Length
property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1
.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
You can use dictRysan library. I think that will solve your task.
import dictRysan as ry
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
changed_d=ry.nested_2L_value_sort(d,"key3",True)
print(changed_d)
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
I threw this together so that you could do some querying on the results
Declare @dbName varchar(150)
set @dbName = '[YOURDATABASENAME]'
--Total machine connections
--SELECT COUNT(dbid) as TotalConnections FROM sys.sysprocesses WHERE dbid > 0
--Available connections
DECLARE @SPWHO1 TABLE (DBName VARCHAR(1000) NULL, NoOfAvailableConnections VARCHAR(1000) NULL, LoginName VARCHAR(1000) NULL)
INSERT INTO @SPWHO1
SELECT db_name(dbid), count(dbid), loginame FROM sys.sysprocesses WHERE dbid > 0 GROUP BY dbid, loginame
SELECT * FROM @SPWHO1 WHERE DBName = @dbName
--Running connections
DECLARE @SPWHO2 TABLE (SPID VARCHAR(1000), [Status] VARCHAR(1000) NULL, [Login] VARCHAR(1000) NULL, HostName VARCHAR(1000) NULL, BlkBy VARCHAR(1000) NULL, DBName VARCHAR(1000) NULL, Command VARCHAR(1000) NULL, CPUTime VARCHAR(1000) NULL, DiskIO VARCHAR(1000) NULL, LastBatch VARCHAR(1000) NULL, ProgramName VARCHAR(1000) NULL, SPID2 VARCHAR(1000) NULL, Request VARCHAR(1000) NULL)
INSERT INTO @SPWHO2
EXEC sp_who2 'Active'
SELECT * FROM @SPWHO2 WHERE DBName = @dbName
MOV can do same thing as LEA [label], but MOV instruction contain the effective address inside the instruction itself as an immediate constant (calculated in advance by the assembler). LEA uses PC-relative to calculate the effective address during the execution of the instruction.
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
Yet another gotcha: readonly values can be changed by "devious" code via reflection.
var fi = this.GetType()
.BaseType
.GetField("_someField",
BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(this, 1);
Can I change a private readonly inherited field in C# using reflection?
After following the steps suggested by previous posters, do the following steps:
You should be good to go now.
Provided that the remote repository is origin, and that you're interested in master:
git fetch origin
git reset --hard origin/master
This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.
All your local commits not common to the remote will be gone.
As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written
LOG.error(exc);
instead of the typical
LOG.error("Some informative message", e);
through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.
Perhaps this is what you're experiencing?
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.
Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.
<input type="hidden" name="TrackingID"
<input type="text" name="FirstName" id="firstnametext" />
<input type="checkbox" name="IsLegal" value="Do you accept terms and conditions?" />
Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string
is nullable)) otherwise the AJAX or POST back will fail.
[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}
You can also post back a model without using any razor helpers. I have come across that this is needed some times.
public Class HomeModel
{
public int HouseNumber { get; set; }
public string StreetAddress { get; set; }
}
The HTML markup will simply be ...
<input type="text" name="variableName.HouseNumber" id="whateverid" >
and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.
[HttpPost]
public ActionResult PostBack(HomeModel variableName){
postBack.HouseNumber; //The value user entered
postBack.StreetAddress; //the default value of NULL.
}
When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.
TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !
Using List<>
is bit more complex in its mark-up.
<input type="text" name="variableNameHere[0].HouseNumber" id="id" value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber" value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">
Index on List<> MUST always be zero based and sequential. 0,1,2,3.
[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
int counter = MyHomes.Count()
foreach(var home in MyHomes)
{ ... }
}
Using IEnumerable<>
for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.
<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id" value="3">
<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3" value="4">
<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23" value="5">
And the code just needs to use IEnumerable and call ToList()
[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
int counter = variableNameHere.ToList().Count()
foreach(var home in variableNameHere)
{ ... }
}
It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.
So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views
If you have button'ed your button this seems to work:
<button id="button">First caption</button>
$('#button').button();//make it nice
var text="new caption";
$('#button').children().first().html(text);
There is also a new option now in http://vimr.org/, which looks quite promising.
Use the addslashes function:
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
Inheritance is more a static thing (one class extends another) while polymorphism is a dynamic/ runtime thing (an object behaves according to its dynamic/ runtime type not to its static/ declaration type).
E.g.
// This assignment is possible because B extends A
A a = new B();
// polymorphic call/ access
a.foo();
-> Though the static/ declaration type of a is A, the actual dynamic/ runtime type is B and thus a.foo() will execute foo as defined in B not in A.
Use arbitrary, extensible object, and then serialize it to JSON:
import json
class Object(object):
pass
response = Object()
response.debug = []
response.result = Object()
# Any manipulations with the object:
response.debug.append("Debug string here")
response.result.body = "404 Not Found"
response.result.code = 404
# Proper JSON output, with nice formatting:
print(json.dumps(response, indent=4, default=lambda x: x.__dict__))
I think the below rules are recommended for a default wordpress site:
For folders inside wp-content, set 0755 permissions:
chmod -R 0755 plugins
chmod -R 0755 uploads
chmod -R 0755 upgrade
Let apache user be the owner for the above directories of wp-content:
chown apache uploads
chown apache upgrade
chown apache plugins
Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title()
, the corresponding argument for an axes is ax.set_title()
. Therefore you need to call
sns.boxplot('Day', 'Count', data= gg).set_title('lalala')
A complete example would be:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")
plt.show()
Of course you could also use the returned axes instance to make it more readable:
ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')
We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.
More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.
The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!
In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:
=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")
For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.
If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.
The code is:
SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR,
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR,
LT.STD_PRJ_NBR,
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T,
LT.STD_CO_EXPL_SN,
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 0 AND 15
GROUP BY
LT.C_O_NBR,
RT.C_O_NBR,
...
And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:
SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 31 AND 45
...
... and so on.
In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple for
loop that looks like this:
int j = 9;
for(int i=0; i<10; i++)
j--;
In this example it is true (for every iteration) that i + j == 9
. A weaker invariant that is also true is that
i >= 0 && i <= 10
.
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
android studio 4.1.1
applicationVariants.all { variant ->
variant.outputs.all { output ->
def reversion = "118"
def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
def versionName = defaultConfig.versionName
outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
}
}
If your int_field is indexed, remove the index before running the update. Then create your index again...
5 hours seem like a lot for 120 million recs.
It's important to note that Lauritz's suggestion idea of using bisect does not actually find the closest value in MyList to MyNumber. Instead, bisect finds the next value in order after MyNumber in MyList. So in OP's case you'd actually get the position of 44 returned instead of the position of 4.
>>> myList = [1, 3, 4, 44, 88]
>>> myNumber = 5
>>> pos = (bisect_left(myList, myNumber))
>>> myList[pos]
...
44
To get the value that's closest to 5 you could try converting the list to an array and using argmin from numpy like so.
>>> import numpy as np
>>> myNumber = 5
>>> myList = [1, 3, 4, 44, 88]
>>> myArray = np.array(myList)
>>> pos = (np.abs(myArray-myNumber)).argmin()
>>> myArray[pos]
...
4
I don't know how fast this would be though, my guess would be "not very".
I came up with a similar example. Again, the rotation keyword is.. well, it's key.
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;
You want to use DATEADD, using a negative duration. e.g.
DATEADD(minute, -15, '2000-01-01 08:30:00')
You can try below code, worked for me:
import org.json.JSONObject;
import org.json.JSONTokener;
public static JSONObject parseJsonObject(String substring)
{
return new JSONObject(new JSONTokener(substring));
}
This is using subclass navigationController
removes the "Back".
I'm using this to remove it, permanently through the app.
//.h
@interface OPCustomNavigationController : UINavigationController
@end
//.m
@implementation OPCustomNavigationController
- (void)awakeFromNib
{
[self backButtonUIOverride:YES];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[self backButtonUIOverride:NO];
[super pushViewController:viewController animated:animated];
}
- (void)backButtonUIOverride:(BOOL)isRoot
{
if (!self.viewControllers.count)
return;
UIViewController *viewController;
if (isRoot)
{
viewController = self.viewControllers.firstObject;
}
else
{
int previousIndex = self.viewControllers.count - 1;
viewController = [self.viewControllers objectAtIndex:previousIndex];
}
viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
style:UIBarButtonItemStylePlain
target:nil
action:nil];
}
@end
You can also try this one
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapOrg, width, height, true);
Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
Then you can use the rotated image to set in your imageview through
imageView.setImageBitmap(rotatedBitmap);
Just include following in your code
<body background="C:\Users\Desktop\images.jpg">
if you want to specify the size and opacity you can use following
<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p>
Example for .csproj file
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="7.0.7-m61" />
</ItemGroup>
Just get package name and version number from NuGet and add to .csproj then save. You will be prompted to run restore that will import new packages.
For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation.
public static byte[] hexStringToByteArray(String input) {
int len = input.length();
if (len == 0) {
return new byte[] {};
}
byte[] data;
int startIdx;
if (len % 2 != 0) {
data = new byte[(len / 2) + 1];
data[0] = (byte) Character.digit(input.charAt(0), 16);
startIdx = 1;
} else {
data = new byte[len / 2];
startIdx = 0;
}
for (int i = startIdx; i < len; i += 2) {
data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
+ Character.digit(input.charAt(i+1), 16));
}
return data;
}
You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/
Adding return false;
worked for me:
jQuery version:
$(document).on('click', '#video-id', function (e) {
var video = $(this).get(0);
if (video.paused === false) {
video.pause();
} else {
video.play();
}
return false;
});
Vanilla JavaScript version:
var v = document.getElementById('videoid');
v.addEventListener(
'play',
function() {
v.play();
},
false);
v.onclick = function() {
if (v.paused) {
v.play();
} else {
v.pause();
}
return false;
};
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
setGame
has been discontinued. You must use client.user.setActivity
.
Don't forget, if you are setting a streaming status, you MUST specify a Twitch URL
An example is here:
client.user.setActivity("with depression", {
type: "STREAMING",
url: "https://www.twitch.tv/example-url"
});
Use the function IF :
=IF ( logical_test, value_if_true, value_if_false )
I logged in using my username instead of email and it started working.
The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:
#!/path/to/project/venv/bin/python
Make the script executable:
chmod u+x script.py
Run the script:
./script.py
Voila!
faster way (without pyspark.sql.functions
)
df.filter((df.d<5)&((df.col1 != df.col3) |
(df.col2 != df.col4) &
(df.col1 ==df.col3)))\
.show()
Use COALESCE
, which returns the first not-null value e.g.
SELECT COALESCE(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) as Succeeded
Will set Succeeded as 0 if it is returned as NULL
.
To cast, the actual object must be of a Type equal to or derived from the Type you are attempting to cast to...
or, to state it in the opposite way, the Type you are trying to cast it to must be the same as, or a base class of, the actual type of the object.
if your actual object is of type Baseclass, then you can't cast it to a derived class Type...
You must define states not equal to null..
@if (ViewBag.States!= null)
{
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
value="@de.Key">@de.Value
}
}
These are positional arguments of the script.
Executing
./script.sh Hello World
Will make
$0 = ./script.sh
$1 = Hello
$2 = World
Note
If you execute ./script.sh
, $0
will give output ./script.sh
but if you execute it with bash script.sh
it will give output script.sh
.
In windows, I was able to get it working using the following steps:
1) Download build-tools-21.1.1 from the following link: http://dl-ssl.google.com/android/repository/build-tools_r21.1.1-windows.zip
2) In windows, the android sdk will be will be located in: C:\Users\ \AppData\Android\sdk (AppData folder will be hidden by default, you can make it visible in "Folder Options")
3) In this path - C:\Users\ \AppData\Android\sdk\build-tools, you'll already find a folder "21.1.2". In the same path, create a new folder and name it "21.1.1"
4) Unzip the package that you downloaded in step 1. Copy the contents of the folder "android-5.0" and paste it in the folder "21.1.1" that you created in step 3).
5) Run Android Studio
You can use Distinct extension method from LINQ
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
Not exactly in-place, but some idea to do it:
a = ['a', 'b']
def inplace(a):
c = []
while len(a) > 0:
e = a.pop(0)
if e == 'b':
c.append(e)
a.extend(c)
You can extend the function to call you filter in the condition.
You can get SVN command-line tools with TortoiseSVN 1.7 or later or get a 6.5mb standalone package from VisualSVN.
Starting with TortoiseSVN 1.7, its installer provides you with an option to install the command-line tools.
It also makes sense to check the Apache Subversion "Binary Packages" page. xD
Use the Timer
class.
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
The Elapsed
event will be raised every X amount of milliseconds, specified by the Interval
property on the Timer object. It will call the Event Handler
method you specify. In the example above, it is OnTimedEvent
.
Just add the height you want with CSS, example:
.card{
height: 350px;
}
You will have to add your own CSS.
If you check the documentation, this is for Masonry style - the point of that is they are not all the same height.
Why not use order by asc limit 1
and the reverse, order by desc limit 1
?
The standard way of multiplying an m-by-n matrix by an n-by-p matrix has complexity O(mnp). If all of those are "n" to you, it's O(n^3), not O(n^2). EDIT: it will not be O(n^2) in the general case. But there are faster algorithms for particular types of matrices -- if you know more you may be able to do better.
Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:
def map_values(row, values_dict):
return values_dict[row]
values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})
df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))
What's it look like:
df
Out[2]:
INDICATOR VALUE NEW_VALUE
0 A 10 1
1 B 9 2
2 C 8 3
3 D 7 4
This approach can be very powerful when you have many ifelse
-type statements to make (i.e. many unique values to replace).
And of course you could always do this:
df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)
But that approach is more than three times as slow as the apply
approach from above, on my machine.
And you could also do this, using dict.get
:
df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]
Use a global namespace like global.MYAPI = {}
:
global.MYAPI._ = require('underscore')
All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.
Check this out with IsNullOrEmpty and IsNullOrwhiteSpace
string sTestes = "I like sweat peaches";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000000; i++)
{
for (int z = 0; z < 500; z++)
{
var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
}
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.ReadLine();
You'll see that IsNullOrWhiteSpace is much slower :/
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
String DataString=DateFormat.getDateInstance(DateFormat.SHORT).format(Calendar.getInstance().getTime());
To get the short date formatted String in the localised format of the unit.
I can't understand why so many answers are hardcoded date and time formats when the OS/Java supplies correct localisation of Dates and time? Isn't it better always use the formats of the unit than of the programmer?
It also supplies the reading of dates in localised formats:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
Date date=null;
try {
date = format.parse(DateString);
}
catch(ParseException e) {
}
Then it is up to the user setting the format to show the dates and time and not you? Regardless languages etc there are different formats in different countries with the same language.
If you want to alter the original objects, then a simple Array#forEach
will do:
rockets.forEach(function(rocket) {
rocket.launches += 10;
});
If you want to keep the original objects unaltered, then use Array#map
and copy the objects using Object#assign
:
var newRockets = rockets.forEach(function(rocket) {
var newRocket = Object.assign({}, rocket);
newRocket.launches += 10;
return newRocket;
});
Just get the file extention then assign the file a new name with uniqid and pass the new name to the move_upload_file method. For example:
if(isset($_POST['submit'])){
$total = count($_FILES['files']['tmp_name']);
for($i=0;$i<$total;$i++){
$fileName = $_FILES['files']['name'][$i];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = uniqid();
$fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
if($ext === 'pdf' || 'jpeg' || 'JPG'){
move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
$fileUpload = $newFileName.'.'.$ext[$i].',<br>';
}else{
echo 'Pdfs and jpegs only please';
}
}
}
First, put the app into the background (press the device's home button)
Then....in a terminal....
adb shell am kill com.your.package
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
I tried to add the following options in the /etc/docker/daemon.json. (I used CentOS7)
"add-registry": ["192.168.100.100:5001"],
"block-registry": ["docker.io"],
after that, restarted docker daemon. And it's working without docker.io. I hope this someone will be helpful.
Start Python and type import pip
pip.__version__
which works for all python packages.
I think that the best solution would be to use Regular expressions. It's cleanest and probably the most effective. Regular Expressions are supported in all commonly used DB engines.
In MySql there is RLIKE
operator so your query would be something like:
SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus|2100'
I'm not very strong in regexp so I hope the expression is ok.
Edit
The RegExp should rather be:
SELECT * FROM buckets WHERE bucketname RLIKE '(?=.*Stylus)(?=.*2100)'
More on MySql regexp support:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
The $http
legacy promise methods success
and error
have been deprecated. Use the standard then
method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http
Now the right way to use is:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:
from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
<td width="580" valign="top">.......</td>\
<td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')
<resource>
<style name="button">
<item name="android:textSize">15dp</item>
</style>
<resource>
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):
java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>
Original answer follows.
Try this:
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp
Two points here:
runjdwp
option.The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
Just use this:
svn copy http://svn.example.com/project/trunk
http://svn.example.com/project/branches/release-1
-m "branch for release 1.0"
(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.
See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2
Following resolved problem in my local machine:
A. First, ensure that you are using the correct log on details to connect to Bitbucket Server (ie. a username/password/SSH key that belongs to you)
B. Then, ensure that the name/email address is correctly set in your local Git configuration: Set your local Git configuration for the account that you are trying to push under (the check asserts that you are the person who committed the files)
* Note that this is case sensitive, both for name and email address
* It is also space sensitive - some company accounts have extra spaces/characters in their name eg. "Contractor/ space space(LDN)
". You must include the same number of spaces in your configuration as on Bitbucket Server. Check this in Notepad if stuck.
C. If you were using the wrong account, simply switch your account credentials (username/password/SSH key) and try pushing again.
D. Else, if your local configuration incorrect you will need to amend it
For MAC
open -a TextEdit.app ~/.gitconfig
NOTE: You will have to fix up the old commits that you were trying to push.
Amend your last commit:
> git commit --amend --reset-author
<save and quit the commit file text editor that opens, if Vim then
:wq to save and quit>
Try re-pushing your commits:
> git push
Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)
In some cases your directive runs twice when you simply not correct close you directive like this:
<my-directive>Some content<my-directive>
This will run your directive twice. Also there is another often case when your directive runs twice:
make sure you are not including your directive in your index.html
TWICE!
reverse()
| Django documentation
Let's suppose that in your urls.py
you have defined this:
url(r'^foo$', some_view, name='url_name'),
In a template you can then refer to this url as:
<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>
<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>
This will be rendered as:
<a href="/foo/">link which calls some_view</a>
Now say you want to do something similar in your views.py
- e.g. you are handling some other url (not /foo/
) in some other view (not some_view
) and you want to redirect the user to /foo/
(often the case on successful form submission).
You could just do:
return HttpResponseRedirect('/foo/')
But what if you want to change the url in future? You'd have to update your urls.py
and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.
Instead, you can say:
from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))
This looks through all urls defined in your project for the url defined with the name url_name
and returns the actual url /foo/
.
This means that you refer to the url only by its name
attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py
.
Use reject
:
>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
You can query the table msdb.dbo.sysjobactivity to determine if the job is currently running.
To make it a bit more user-friendly:
After you've unpacked it, go into the directory, and run bin/pycharm.sh
.
Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...
Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)
To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)
(Unless you are trying to debug an application, you usually do not need to see the output of it.)
cat \`find . -name "*.php"\` | wc -l
I propose this query:
SELECT DISTINCT s.*
FROM INFORMATION_SCHEMA.STATISTICS s
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t
ON t.TABLE_SCHEMA = s.TABLE_SCHEMA
AND t.TABLE_NAME = s.TABLE_NAME
AND s.INDEX_NAME = t.CONSTRAINT_NAME
WHERE 0 = 0
AND t.CONSTRAINT_NAME IS NULL
AND s.TABLE_SCHEMA = 'YOUR_SCHEMA_SAMPLE';
You found all Index only index.
Regard.