If you have a hidden field like this
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>
Now you can use your value like this
$(this).parent().find('input[type=hidden]').val()
Correct way (if you are not trying to reset the value of the hidden_field input) is:
f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form
Where :method
is the method that when called on the object results in the value you want
So following the example above:
= simple_form_for @movie do |f|
= f.hidden :title, "some value"
= f.button :submit
The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:
= simple_form_for @movie do |f|
= f.hidden :title, :value => params[:movie][:title]
= f.button :submit
Again only use my answer is you do not want to reset the value submitted by the user.
I hope this makes sense.
function addHidden(theForm, key, value) {
// Create a hidden input element, and append it to the form:
var input = document.createElement('input');
input.type = 'hidden';
input.name = key; //name-as-seen-at-the-server
input.value = value;
theForm.appendChild(input);
}
// Form reference:
var theForm = document.forms['detParameterForm'];
// Add data:
addHidden(theForm, 'key-one', 'value');
Hello World!
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
For me it works:
document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);
Maybe your JS is not executed and you need to add a function() {} around it all.
It's simple as:
$('#action').val("1");
#action
is hidden input field id.
To pass the value you must included the hidden value value="hiddenValue"
in the <input>
statement like so:
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:
This code goes on the page where you want to hide the value.
<form action="anotherPage.jsp" method="GET">
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">
</form>
Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name)
method of the implicit request
object, as so:
<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>
The output of the above script will be:
The Hidden Value is hiddenValue
https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js
This is what node-boilerplate does.
You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main()
function could, for example, look like this:
int main()
{
Name_pairs np;
cout << "Enter names and ages. Use 0 to cancel.\n";
while(np.test())
{
np.read_names();
np.read_ages();
}
np.print();
keep_window_open();
}
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
According to the javadoc a Scanner
does not seem to be intended for reading single characters. You attach a Scanner
to an InputStream
(or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.
Since Java 9.0 JDWP supports only local connections by default. http://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435
For remote debugging one should run program with *:
in address:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
Another option, if you need to sign the executable on a Linux box is to use signcode from the Mono project tools. It is supported on Ubuntu.
ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.
In your case, in may be better to apply the filter inside of your controller using the $filter
service:
function MainCtrl( $scope, filterFilter ) {
// ...
$scope.filteredData = myNormalData;
$scope.$watch( 'myInputModel', function ( val ) {
$scope.filteredData = filterFilter( myNormalData, val );
});
// ...
}
And then you use the filteredData
property in your view instead. Here is a working Plunker: http://plnkr.co/edit/7c1l24rPkuKPOS5o2qtx?p=preview
ummm, I don't know why all this programming, I think the original problem is solved easily by specifying this default route ...
routes.MapRoute("Default", "{*id}",
new { controller = "Home"
, action = "Index"
, id = UrlParameter.Optional
}
);
try:
ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'
BinaryFormatter
may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.
If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer
or XmlSerializer
.
This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any
<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
$fvisit = mysql_fetch_array($result3);
$showDivFlag=true;
}else {
}
?>
later in html
<div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>
On Mac: Fn+Left Ctrl+F12
On Linux: Left Ctrl+F12
If you want to rotate just the screen and not the emulator: Ctrl+F10 (I tried it on Linux)
From the doc (bootsrap 4):
https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content
.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around
Wikibooks has a fairly good summary of jump instructions. Basically, there's actually two stages:
cmp_instruction op1, op2
Which sets various flags based on the result, and
jmp_conditional_instruction address
which will execute the jump based on the results of those flags.
Compare (cmp
) will basically compute the subtraction op1-op2
, however, this is not stored; instead only flag results are set. So if you did cmp eax, ebx
that's the same as saying eax-ebx
- then deciding based on whether that is positive, negative or zero which flags to set.
More detailed reference here.
You can use Github Contents API to get an archive link and tar
to retrieve a specified folder.
curl https://codeload.github.com/[owner]/[repo]/tar.gz/master | \ tar -xz --strip=2 [repo]-master/[folder_path]
For example,
if you want to download examples/with-apollo/ folder from zeit/next.js, you can type this:
curl https://codeload.github.com/zeit/next.js/tar.gz/master | \
tar -xz --strip=2 next.js-master/examples/with-apollo
When adding a nullable column, WITH VALUES
will ensure that the specific DEFAULT value is applied to existing rows:
ALTER TABLE table
ADD column BIT -- Demonstration with NULL-able column added
CONSTRAINT Constraint_name DEFAULT 0 WITH VALUES
git clone --filter
from git 2.19 now works on GitHub (tested 2021-01-14, git 2.30.0)
This option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.
E.g., to clone only objects required for d1
of this minimal test repository: https://github.com/cirosantilli/test-git-partial-clone I can do:
git clone \
--depth 1 \
--filter=blob:none \
--sparse \
https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git sparse-checkout init --cone
git sparse-checkout set d1
Here's a less minimal and more realistic version at https://github.com/cirosantilli/test-git-partial-clone-big-small
git clone \
--depth 1 \
--filter=blob:none \
--sparse \
https://github.com/cirosantilli/test-git-partial-clone-big-small \
;
cd test-git-partial-clone
git sparse-checkout init --cone
git sparse-checkout set small
That repository contains:
All contents are pseudo-random and therefore incompressible.
Clone times on my 36.4 Mbps internet:
The sparse-checkout
part is also needed unfortunately. You can also only download certain files with the much more understandable:
git clone \
--depth 1 \
--filter=blob:none \
--no-checkout \
https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git checkout master -- di
but that method for some reason downloads files one by one very slowly, making it unusable unless you have very few files in the directory.
Analysis of the objects in the minimal repository
The clone command obtains only:
master
branchd1
, d2
, master
Then, the git sparse-checkout set
command fetches only the missing blobs (files) from the server:
d1/a
d1/b
Even better, later on GitHub will likely start supporting:
--filter=blob:none \
--filter=tree:0 \
where --filter=tree:0
from Git 2.20 will prevent the unnecessary clone
fetch of all tree objects, and allow it to be deferred to checkout
. But on my 2020-09-18 test that fails with:
fatal: invalid filter-spec 'combine:blob:none+tree:0'
presumably because the --filter=combine:
composite filter (added in Git 2.24, implied by multiple --filter
) is not yet implemented.
I observed which objects were fetched with:
git verify-pack -v .git/objects/pack/*.pack
as mentioned at: How to list ALL git objects in the database? It does not give me a super clear indication of what each object is exactly, but it does say the type of each object (commit
, tree
, blob
), and since there are so few objects in that minimal repo, I can unambiguously deduce what each object is.
git rev-list --objects --all
did produce clearer output with paths for tree/blobs, but it unfortunately fetches some objects when I run it, which makes it hard to determine what was fetched when, let me know if anyone has a better command.
TODO find GitHub announcement that saying when they started supporting it. https://github.blog/2020-01-17-bring-your-monorepo-down-to-size-with-sparse-checkout/ from 2020-01-17 already mentions --filter blob:none
.
git sparse-checkout
I think this command is meant to manage a settings file that says "I only care about these subtrees" so that future commands will only affect those subtrees. But it is a bit hard to be sure because the current documentation is a bit... sparse ;-)
It does not, by itself, prevent the fetching of blobs.
If this understanding is correct, then this would be a good complement to git clone --filter
described above, as it would prevent unintentional fetching of more objects if you intend to do git operations in the partial cloned repo.
When I tried on Git 2.25.1:
git clone \
--depth 1 \
--filter=blob:none \
--no-checkout \
https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git sparse-checkout init
it didn't work because the init
actually fetched all objects.
However, in Git 2.28 it didn't fetch the objects as desired. But then if I do:
git sparse-checkout set d1
d1
is not fetched and checked out, even though this explicitly says it should: https://github.blog/2020-01-17-bring-your-monorepo-down-to-size-with-sparse-checkout/#sparse-checkout-and-partial-clones With disclaimer:
Keep an eye out for the partial clone feature to become generally available[1].
[1]: GitHub is still evaluating this feature internally while it’s enabled on a select few repositories (including the example used in this post). As the feature stabilizes and matures, we’ll keep you updated with its progress.
So yeah, it's just too hard to be certain at the moment, thanks in part to the joys of GitHub being closed source. But let's keep an eye on it.
Command breakdown
The server should be configured with:
git config --local uploadpack.allowfilter 1
git config --local uploadpack.allowanysha1inwant 1
Command breakdown:
--filter=blob:none
skips all blobs, but still fetches all tree objects
--filter=tree:0
skips the unneeded trees: https://www.spinics.net/lists/git/msg342006.html
--depth 1
already implies --single-branch
, see also: How do I clone a single branch in Git?
file://$(path)
is required to overcome git clone
protocol shenanigans: How to shallow clone a local git repository with a relative path?
--filter=combine:FILTER1+FILTER2
is the syntax to use multiple filters at once, trying to pass --filter
for some reason fails with: "multiple filter-specs cannot be combined". This was added in Git 2.24 at e987df5fe62b8b29be4cdcdeb3704681ada2b29e "list-objects-filter: implement composite filters"
Edit: on Git 2.28, I experimentally see that --filter=FILTER1 --filter FILTER2
also has the same effect, since GitHub does not implement combine:
yet as of 2020-09-18 and complains fatal: invalid filter-spec 'combine:blob:none+tree:0'
. TODO introduced in which version?
The format of --filter
is documented on man git-rev-list
.
Docs on Git tree:
Test it out locally
The following script reproducibly generates the https://github.com/cirosantilli/test-git-partial-clone repository locally, does a local clone, and observes what was cloned:
#!/usr/bin/env bash
set -eu
list-objects() (
git rev-list --all --objects
echo "master commit SHA: $(git log -1 --format="%H")"
echo "mybranch commit SHA: $(git log -1 --format="%H")"
git ls-tree master
git ls-tree mybranch | grep mybranch
git ls-tree master~ | grep root
)
# Reproducibility.
export GIT_COMMITTER_NAME='a'
export GIT_COMMITTER_EMAIL='a'
export GIT_AUTHOR_NAME='a'
export GIT_AUTHOR_EMAIL='a'
export GIT_COMMITTER_DATE='2000-01-01T00:00:00+0000'
export GIT_AUTHOR_DATE='2000-01-01T00:00:00+0000'
rm -rf server_repo local_repo
mkdir server_repo
cd server_repo
# Create repo.
git init --quiet
git config --local uploadpack.allowfilter 1
git config --local uploadpack.allowanysha1inwant 1
# First commit.
# Directories present in all branches.
mkdir d1 d2
printf 'd1/a' > ./d1/a
printf 'd1/b' > ./d1/b
printf 'd2/a' > ./d2/a
printf 'd2/b' > ./d2/b
# Present only in root.
mkdir 'root'
printf 'root' > ./root/root
git add .
git commit -m 'root' --quiet
# Second commit only on master.
git rm --quiet -r ./root
mkdir 'master'
printf 'master' > ./master/master
git add .
git commit -m 'master commit' --quiet
# Second commit only on mybranch.
git checkout -b mybranch --quiet master~
git rm --quiet -r ./root
mkdir 'mybranch'
printf 'mybranch' > ./mybranch/mybranch
git add .
git commit -m 'mybranch commit' --quiet
echo "# List and identify all objects"
list-objects
echo
# Restore master.
git checkout --quiet master
cd ..
# Clone. Don't checkout for now, only .git/ dir.
git clone --depth 1 --quiet --no-checkout --filter=blob:none "file://$(pwd)/server_repo" local_repo
cd local_repo
# List missing objects from master.
echo "# Missing objects after --no-checkout"
git rev-list --all --quiet --objects --missing=print
echo
echo "# Git checkout fails without internet"
mv ../server_repo ../server_repo.off
! git checkout master
echo
echo "# Git checkout fetches the missing directory from internet"
mv ../server_repo.off ../server_repo
git checkout master -- d1/
echo
echo "# Missing objects after checking out d1"
git rev-list --all --quiet --objects --missing=print
Output in Git v2.19.0:
# List and identify all objects
c6fcdfaf2b1462f809aecdad83a186eeec00f9c1
fc5e97944480982cfc180a6d6634699921ee63ec
7251a83be9a03161acde7b71a8fda9be19f47128
62d67bce3c672fe2b9065f372726a11e57bade7e
b64bf435a3e54c5208a1b70b7bcb0fc627463a75 d1
308150e8fddde043f3dbbb8573abb6af1df96e63 d1/a
f70a17f51b7b30fec48a32e4f19ac15e261fd1a4 d1/b
84de03c312dc741d0f2a66df7b2f168d823e122a d2
0975df9b39e23c15f63db194df7f45c76528bccb d2/a
41484c13520fcbb6e7243a26fdb1fc9405c08520 d2/b
7d5230379e4652f1b1da7ed1e78e0b8253e03ba3 master
8b25206ff90e9432f6f1a8600f87a7bd695a24af master/master
ef29f15c9a7c5417944cc09711b6a9ee51b01d89
19f7a4ca4a038aff89d803f017f76d2b66063043 mybranch
1b671b190e293aa091239b8b5e8c149411d00523 mybranch/mybranch
c3760bb1a0ece87cdbaf9a563c77a45e30a4e30e
a0234da53ec608b54813b4271fbf00ba5318b99f root
93ca1422a8da0a9effc465eccbcb17e23015542d root/root
master commit SHA: fc5e97944480982cfc180a6d6634699921ee63ec
mybranch commit SHA: fc5e97944480982cfc180a6d6634699921ee63ec
040000 tree b64bf435a3e54c5208a1b70b7bcb0fc627463a75 d1
040000 tree 84de03c312dc741d0f2a66df7b2f168d823e122a d2
040000 tree 7d5230379e4652f1b1da7ed1e78e0b8253e03ba3 master
040000 tree 19f7a4ca4a038aff89d803f017f76d2b66063043 mybranch
040000 tree a0234da53ec608b54813b4271fbf00ba5318b99f root
# Missing objects after --no-checkout
?f70a17f51b7b30fec48a32e4f19ac15e261fd1a4
?8b25206ff90e9432f6f1a8600f87a7bd695a24af
?41484c13520fcbb6e7243a26fdb1fc9405c08520
?0975df9b39e23c15f63db194df7f45c76528bccb
?308150e8fddde043f3dbbb8573abb6af1df96e63
# Git checkout fails without internet
fatal: '/home/ciro/bak/git/test-git-web-interface/other-test-repos/partial-clone.tmp/server_repo' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
# Git checkout fetches the missing directory from internet
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1/1), 45 bytes | 45.00 KiB/s, done.
remote: Enumerating objects: 1, done.
remote: Counting objects: 100% (1/1), done.
remote: Total 1 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1/1), 45 bytes | 45.00 KiB/s, done.
# Missing objects after checking out d1
?8b25206ff90e9432f6f1a8600f87a7bd695a24af
?41484c13520fcbb6e7243a26fdb1fc9405c08520
?0975df9b39e23c15f63db194df7f45c76528bccb
Conclusions: all blobs from outside of d1/
are missing. E.g. 0975df9b39e23c15f63db194df7f45c76528bccb
, which is d2/b
is not there after checking out d1/a
.
Note that root/root
and mybranch/mybranch
are also missing, but --depth 1
hides that from the list of missing files. If you remove --depth 1
, then they show on the list of missing files.
I have a dream
This feature could revolutionize Git.
Imagine having all the code base of your enterprise in a single repo without ugly third-party tools like repo
.
Imagine storing huge blobs directly in the repo without any ugly third party extensions.
Imagine if GitHub would allow per file / directory metadata like stars and permissions, so you can store all your personal stuff under a single repo.
Imagine if submodules were treated exactly like regular directories: just request a tree SHA, and a DNS-like mechanism resolves your request, first looking on your local ~/.git
, then first to closer servers (your enterprise's mirror / cache) and ending up on GitHub.
ViewBag
is of type dynamic
but, is internally an System.Dynamic.ExpandoObject()
It is declared like this:
dynamic ViewBag = new System.Dynamic.ExpandoObject();
which is why you can do :
ViewBag.Foo = "Bar";
A Sample Expander Object Code:
public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
public Dictionary<string, object> objectDictionary;
public ExpanderObject()
{
objectDictionary = new Dictionary<string, object>();
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
object val;
if (objectDictionary.TryGetValue(binder.Name, out val))
{
result = val;
return true;
}
result = null;
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
try
{
objectDictionary[binder.Name] = value;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
string.IsNullOrEmpty(str) - if you'd like to check string value has been provided
string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).
My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.
To continue using the iframe YouTube, you should only have to change ?autoplay=1
to ?autoplay=0
.
Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)
Edit: the YouTube JavaScript Player API is no longer supported.
<div id="howToVideo"></div>
<script type="application/javascript">
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = false;
ga.src = 'http://www.youtube.com/player_api';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('howToVideo', {
height: '390',
width: '640',
videoId: 'qUJYqhKZrwA',
playerVars: {
controls: 0,
disablekb: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
console.log('onPlayerReady', evt);
}
function onPlayerStateChange(evt) {
console.log('onPlayerStateChange', evt);
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
console.log('stopVideo');
player.stopVideo();
}
</script>
Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/
Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo()
.
For installing
gem install gemname -v versionnumber
For uninstall
gem uninstall gemname -v versionnumber
For just quickly viewing the cookies on any particular page, I keep a favorites-bar "Cookies" shortcut with the URL set to:
javascript:window.alert(document.cookie.split(';').join(';\r\n'));
The Advanced Editor did not resolve my issue, instead I was forced to edit dtsx-file through notepad (or your favorite text/xml editor) and manually replace values in attributes to
length="0"
dataType="nText"
(I'm using unicode)
Always make a backup of the dtsx-file before you edit in text/xml mode.
Running SQL Server 2008 R2
All these patterns, MVC, MVVM, MVP, and Presentation Model, can be applied to Android apps, but without a third-party framework, it is not easy to get well-organized structure and clean code.
MVVM is originated from PresentationModel. When we apply MVC, MVVM, and Presentation Model to an Android app, what we really want is to have a clear structured project and more importantly easier for unit tests.
At the moment, without an third-party framework, you usually have lots of code (like addXXListener(), findViewById(), etc.), which does not add any business value. What's more, you have to run Android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical.
For these reasons, some years ago we started an open source project, RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test, and maintain. RoboBinding removes the need of unnecessary code like addXXListener or so, and shifts UI logic to the Presentation Model, which is a POJO and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality.
If you have LWP installed, it provides a binary simply named "GET".
$ GET http://example.com <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE>Example Web Page</TITLE> </HEAD> <body> <p>You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser.</p> <p>These domain names are reserved for use in documentation and are not available for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </BODY> </HTML>
wget -O-
, curl
, and lynx -source
behave similarly.
This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:
df.groupby(['group']).agg(['min','max','count','nunique'])
Hope you find it useful
I had the same:
Error opening registry key 'Software\JavaSoft\Java Runtime Environment
Clearing Windows\SysWOW64 doesn't help for Win7
In my case it installing JDK8 offline helped (from link)
I'd suggest to modify the primary constructor and add a default value to each parameter:
data class Activity(
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
)
You can also make values nullable by adding ?
and then you can assing null
:
data class Activity(
var updated_on: String? = null,
var tags: List<String>? = null,
var description: String? = null,
var user_id: List<Int>? = null,
var status_id: Int? = null,
var title: String? = null,
var created_at: String? = null,
var data: HashMap<*, *>? = null,
var id: Int? = null,
var counts: LinkedTreeMap<*, *>? = null
)
In general, it is a good practice to avoid nullable objects - write the code in the way that we don't need to use them. Non-nullable objects are one of the advantages of Kotlin compared to Java. Therefore, the first option above is preferable.
Both options will give you the desired result:
val activity = Activity()
activity.title = "New Computer"
sendToServer(activity)
Just use this extension to move any UIView when keyboard is presented.
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification){
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endFrame.origin.y - beginningFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
}, completion: nil)
}
}
Then in your viewdidload bind your view to the keyboard
UiView.bindToKeyboard()
You can use multiprocessing.Pool
:
from multiprocessing import Pool
class Engine(object):
def __init__(self, parameters):
self.parameters = parameters
def __call__(self, filename):
sci = fits.open(filename + '.fits')
manipulated = manipulate_image(sci, self.parameters)
return manipulated
try:
pool = Pool(8) # on 8 processors
engine = Engine(my_parameters)
data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
pool.close()
pool.join()
set -x
Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
[source]
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
expr
has been evaluated.echo
has been evaluated.To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works
If you are splitting from Linux, you can still reassemble in Windows.
copy /b file1 + file2 + file3 + file4 filetogether
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case "DbConnectionString")
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
For TortoiseGit 1.8.1.2 or later, there is a GUI to switch on/off credential helper.
It supports git-credential-wincred
and git-credential-winstore
.
TortoiseGit 1.8.16 add support for git-credential-manager
(Git Credential Manager, the successor of git-credential-winstore
)
For the first time you sync you are asked for user and password, you enter them and they will be saved to Windows credential store. It won't ask for user or password the next time you sync.
To use: Right click → TortoiseGit → Settings → Git → Credential. Select Credential helper: wincred - this repository only / wincred - current Windows user
You need to compile and link all your source files together:
g++ main.c function_file.c
Make sure your root index.php
file has the correct permission, its permission must be 0755
or 0644
I have been working on to write a custom module in Drupal 7 and got the same error:
Notice: Trying to get property of non-object
My code is something like this:
function example_node_access($node, $op, $account) {
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes to it.','error');
return NODE_ACCESS_DENY;
}
}
Solution:
I just added a condition if (is_object($sqlResult))
, and everything went fine.
Here is my final code:
function mediaten_node_access($node, $op, $account) {
if (is_object($node)){
if ($node->type == 'page' && $op == 'update') {
drupal_set_message('This poll has been published, you may not make changes.','error');
return NODE_ACCESS_DENY;
}
}
}
To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:
val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
case Process("b", _) => println("first: 'a', some rest")
case Process(_, rest) => println("some first, rest: " + rest)
// etc.
}
GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"
Rebase to before said commit and stop for amendment:
git rebase <commit-hash>^ -i
pick
with e
(edit) on the line with that commit (the first one):wq
in VIM)GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"
Source: https://codewithhugo.com/change-the-date-of-a-git-commit/
Example:
SELECT TRIM(' Sample ');
Result: 'Sample'
UPDATE TableName SET ColumnName = TRIM(ColumnName)
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:
sampleDict = {
"key1": {"key10": "value10", "key11": "value11"},
"key2": {"key20": "value20", "key21": "value21"}
}
So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values()
list, you may use something like this:
for key, value in sampleDict.items():
print value.keys()[0]
If you want to just access first key of the first item in sampleDict.values()
, this may be useful:
print sampleDict.values()[0].keys()[0]
If you use the example you gave in the question, I mean:
sampleDict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'}
}
The output for the first code is:
American
Indian
And the output for the second code is:
American
EDIT 1:
Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys
and values
from list
to dict_values
. Type dict_values
is not accepting indexing, but it is iterable. So you need to change above codes as below:
First One:
for key, value in sampleDict.items():
print(list(value.keys())[0])
Second One:
print(list(list(sampleDict.values())[0].keys())[0])
It is very simple do not import anything. This is my code. This will define a function that multiplies all the items in a list and returns their product.
def myfunc(lst):
multi=1
for product in lst:
multi*=product
return product
<script type="text/JavaScript">
setTimeout("location.href = 'http://www.your_site.com';",1500);
</script>
I found an answer that I like much better here
Looks like this:
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
Enabling would involve setting the href attribute
$(document).ready(function(){
$("a").click(function () {
$(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html");
});
});
This gives you the appearance that the anchor element becomes normal text, and vice versa.
pg_hba.conf
entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf
in order to get proper help.
Change this line:
host all all <my-ip-address>/32 md5
To reflect your local network settings. So, if your IP is 192.168.16.78
(class C) with a mask of 255.255.255.0
, then put this:
host all all 192.168.16.0/24 md5
Make sure your WINDOWS MACHINE is in that network 192.168.16.0
and try again.
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
Javascript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""
), null
, undefined
, false
and the numbers 0
and NaN
Please note that if you are specifically checking for numbers it is a common mistake to miss 0
with this method, and num !== 0
is preferred (or num !== -1
or ~num
(hacky code that also checks against -1
)) for functions that return -1
, e.g. indexOf
)
This may be late, but sharing it for the new users visiting this question. To drop multiple columns actual syntax is
alter table tablename drop column col1, drop column col2 , drop column col3 ....
So for every column you need to specify "drop column" in Mysql 5.0.45.
Now, You can use below code (by google)
<div class="g-recaptcha" data-sitekey="<yours>" data-size="compact"></div>
Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line
counter += 1
implicitly makes counter
local to increment()
. Trying to execute this line, though, will try to read the value of the local variable counter
before it is assigned, resulting in an UnboundLocalError
.[2]
If counter
is a global variable, the global
keyword will help. If increment()
is a local function and counter
a local variable, you can use nonlocal
in Python 3.x.
I suppose you have figured it out by now. The answer is hidden in your first mail itself.
The make
command by default looks for makefile
, Makefile
, and GNUMakefile
as the input file and you are having Makefile.txt
in your folder. Just remove the file extension (.txt
) and it should work.
It is not possible at this point (unless the author of the image explicitly included the Dockerfile).
However, it is definitely something useful! There are two things that will help to obtain this feature.
Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :
class TestAD
{
static DirContext ldapContext;
public static void main (String[] args) throws NamingException
{
try
{
System.out.println("Début du test Active Directory");
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//ldapEnv.put(Context.PROVIDER_URL, "ldap://societe.fr:389");
ldapEnv.put(Context.PROVIDER_URL, "ldap://dom.fr:389");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
//ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
ldapContext = new InitialDirContext(ldapEnv);
// Create the search controls
SearchControls searchCtls = new SearchControls();
//Specify the attributes to return
String returnedAtts[]={"sn","givenName", "samAccountName"};
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//specify the LDAP search filter
String searchFilter = "(&(objectClass=user))";
//Specify the Base for the search
String searchBase = "dc=dom,dc=fr";
//initialize counter to total the results
int totalResults = 0;
// Search for objects using the filter
NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);
//Loop through the search results
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult)answer.next();
totalResults++;
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
System.out.println(">>>>>>" + attrs.get("samAccountName"));
}
System.out.println("Total results: " + totalResults);
ldapContext.close();
}
catch (Exception e)
{
System.out.println(" Search error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
}
There is no difference between the %i
and %d
format specifiers for printf
. We can see this by going to the draft C99 standard section 7.19.6.1
The fprintf function which also covers printf
with respect to format specifiers and it says in paragraph 8:
The conversion specifiers and their meanings are:
and includes the following bullet:
d,i The int argument is converted to signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
On the other hand for scanf
there is a difference, %d
assume base 10 while %i
auto detects the base. We can see this by going to section 7.19.6.2
The fscanf function which covers scanf
with respect to format specifier, in paragraph 12 it says:
The conversion specifiers and their meanings are:
and includes the following:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
Try;
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];
From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.
EDIT
Maybe also worth trying to echo the json string from php://input.
echo file_get_contents('php://input');
The ?:
Operator returns one of two values depending on the value of a Boolean expression.
Condition-Expression ? Expression1 : Expression2
Find here more on ?:
operator, also know as a Ternary Operator:
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
Here is an algorithm finding and printing all paths from s to t using modification of DFS. Also dynamic programming can be used to find the count of all possible paths. The pseudo code will look like this:
AllPaths(G(V,E),s,t)
C[1...n] //array of integers for storing path count from 's' to i
TopologicallySort(G(V,E)) //here suppose 's' is at i0 and 't' is at i1 index
for i<-0 to n
if i<i0
C[i]<-0 //there is no path from vertex ordered on the left from 's' after the topological sort
if i==i0
C[i]<-1
for j<-0 to Adj(i)
C[i]<- C[i]+C[j]
return C[i1]
If your file has only one main function that you want to call/expose, then you can also just start the file with:
Param($Param1)
You can then call it e.g. as follows:
.\MyFunctions.ps1 -Param1 'value1'
This makes it much more convenient if you want to easily call just that function without having to import the function.
Just like any other collection. With the addition of the List<T>.ForEach
method.
foreach (var item in myMoney)
Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);
for (int i = 0; i < myMoney.Count; i++)
Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);
myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
$('#_SelectID').change(function () {
var SelectedText = $('option:selected',this).text();
var SelectedValue = $('option:selected',this).val();
});
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
git log
+ git branch
will find it for you:
% git log --all -- somefile
commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date: Tue Dec 16 14:16:22 2008 -0800
added somefile
% git branch -a --contains 55d2069
otherbranch
Supports globbing, too:
% git log --all -- '**/my_file.png'
The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find
).
I reverted back a few commits by running 'git revert commit id' such as:
git revert b2cb7c248d416409f8eb42b561cbff91b0601712
Then i was prompted to commit the revert (just as you would when running 'git commit'). My default terminal program is Vim so i ran:
:wq
Finally i pushed the change to the repository with:
git push
It is the simplest one I could come up with, so wanted to share here,
#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<”Enter the Temperature in Celsius”<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<”Temperature in Fahrenheit is “<<fah;
//get character
getch();
}
Source: Celsius to Fahrenheit
tr:hover
doesn't work in old browsers.
You can use jQuery for this:
.tr-hover
{
background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
$(this).addClass('tr-hover');
},function()
{
$(this).removeClass('tr-hover');
});
This is my approach. Iterate over characters in the string until a match is found. On a larger array of needles this will outperform the accepted answer because it doesn't need to check every needle to determine that a match has been found.
function strpos_array($haystack, $needles = [], $offset = 0) {
for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
if (in_array($haystack[$i],$needles)) {
return $i;
}
}
return false;
}
I benchmarked this against the accepted answer and with an array of more than 7 $needles
this was dramatically faster.
In MacOS Catalina 10.15.5 the .npmrc
file path can be found at
/Users/<user-name>/.npmrc
Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.
You are ready to go.
Note:
As mentioned by @oligofren, the command npm config ls -l
will npm configurations. You will get the .npmrc file from config parameter userconfig
There is both window.onbeforeunload
and window.onunload
, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener
:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
Usually, onbeforeunload
is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload
isn't supported by Opera, as far as I know, but you could always set both.
$query = $this->db
->get_where('orders',array('order_date <='=>$first_date,'order_date >='=>$second_date))
->result_array();
You can try this
click Help>Install New Software on the menu bar
I've been studying this problem quite a bit lately. Based on that my conclusion is that nowadays this is the best approach:
from collections.abc import Iterable # drop `.abc` with Python 2.7 or lower
def iterable(obj):
return isinstance(obj, Iterable)
The above has been recommended already earlier, but the general consensus has been that using iter()
would be better:
def iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
return True
We've used iter()
in our code as well for this purpose, but I've lately started to get more and more annoyed by objects which only have __getitem__
being considered iterable. There are valid reasons to have __getitem__
in a non-iterable object and with them the above code doesn't work well. As a real life example we can use Faker. The above code reports it being iterable but actually trying to iterate it causes an AttributeError
(tested with Faker 4.0.2):
>>> from faker import Faker
>>> fake = Faker()
>>> iter(fake) # No exception, must be iterable
<iterator object at 0x7f1c71db58d0>
>>> list(fake) # Ooops
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/.../site-packages/faker/proxy.py", line 59, in __getitem__
return self._factory_map[locale.replace('-', '_')]
AttributeError: 'int' object has no attribute 'replace'
If we'd use insinstance()
, we wouldn't accidentally consider Faker instances (or any other objects having only __getitem__
) to be iterable:
>>> from collections.abc import Iterable
>>> from faker import Faker
>>> isinstance(Faker(), Iterable)
False
Earlier answers commented that using iter()
is safer as the old way to implement iteration in Python was based on __getitem__
and the isinstance()
approach wouldn't detect that. This may have been true with old Python versions, but based on my pretty exhaustive testing isinstance()
works great nowadays. The only case where isinstance()
didn't work but iter()
did was with UserDict
when using Python 2. If that's relevant, it's possible to use isinstance(item, (Iterable, UserDict))
to get that covered.
I know I'm a bit late, but was able to fix this issue by following the docs directly.
Add the meta-data tag to AndroidManifest.xml
(so the system knows)
<activity
android:name=".Sub"
android:label="Sub-Activity"
android:parentActivityName=".MainChooser"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainChooser" />
</activity>
Next, enable the back (up) button in your MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_child);
// my_child_toolbar is defined in the layout file
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
And, you will be all set up!
Source: Android Developer Documentation
#function to find mode
def mode(data):
modecnt=0
#for count of number appearing
for i in range(len(data)):
icount=data.count(data[i])
#for storing count of each number in list will be stored
if icount>modecnt:
#the loop activates if current count if greater than the previous count
mode=data[i]
#here the mode of number is stored
modecnt=icount
#count of the appearance of number is stored
return mode
print mode(data1)
If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:
val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)
Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:
Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow
It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:
Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn
This may also be of use to you:
With Sheet1.UsedRange
MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With
but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange
property.
Solution I have json object which has data
[{"name":"Ata","email":"[email protected]"}]
You can use following approach to iterate through ng-repeat and use table format instead of list.
<div class="container" ng-controller="fetchdataCtrl">
<ul ng-repeat="item in numbers">
<li>
{{item.name}}: {{item.email}}
</li>
</ul>
</div>
Your method signature is:
- (void) myTest:(NSString *)
withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).
If you call the function in this manner:
[self performSelector:@selector(myTest:) withObject:myString];
It will work.
But, as the other posters have suggested, you may want to rename the method:
- (void)myTestWithAString:(NSString*)aString;
And call:
[self performSelector:@selector(myTestWithAString:) withObject:myString];
You have two ways to fix this. The preferred way is to use:
string answer;
(instead of char
). The other possible way to fix it is:
if (answer == 'y') ...
(note single quotes instead of double, representing a char
constant).
All you'd need in your case is:
return expression;
The reason why is that the expression itself evaluates to a boolean value of true
or false
, so it's redundant to have an if
block (or even a ?:
operator).
You can add a jar in Eclipse by right-clicking on the Project ? Build Path ? Configure Build Path. Under Libraries tab, click Add Jars or Add External JARs and give the Jar. A quick demo here.
The above solution is obviously a "Quick" one. However, if you are working on a project where you need to commit files to the source control repository, I would recommend adding Jar files to a dedicated library folder within your source control repository and referencing few or all of them as mentioned above.
git commit -am "msg"
is not same as git add file
and git commit -m "msg"
If you have some files which were never added to git tracking you still need to do git add file
The “git commit -a” command is a shortcut to a two-step process. After you modify a file that is already known by the repo, you still have to tell the repo, “Hey! I want to add this to the staged files and eventually commit it to you.” That is done by issuing the “git add” command. “git commit -a” is staging the file and committing it in one step.
Source: "git commit -a" and "git add"
To check whether your inside Virtualenv:
import os
if os.getenv('VIRTUAL_ENV'):
print('Using Virtualenv')
else:
print('Not using Virtualenv')
You can also get more data on your environment:
import sys
import os
print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')
You are allowed to use IDs that start with a digit in your HTML5 documents:
The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
But querySelector
method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
Use a value like b22
for the ID attribute and your code will work.
Since you want to select an element by ID you can also use .getElementById
method:
document.getElementById('22')
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
For mocking of void methods try out below:
//Kotlin Syntax
Mockito.`when`(voidMethodCall())
.then {
Unit //Do Nothing
}
The ORA-01722 error is pretty straightforward. According to Tom Kyte:
We've attempted to either explicity or implicity convert a character string to a number and it is failing.
However, where the problem is is often not apparent at first. This page helped me to troubleshoot, find, and fix my problem. Hint: look for places where you are explicitly or implicitly converting a string to a number. (I had NVL(number_field, 'string')
in my code.)
I had some problems with andy's code, but it gave me some great ideas. First problem was that we should pop off any jqXHR objects that successfully complete. I also had to modify the abortAll function. Here is my final working code:
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
}
});
$(document).ajaxComplete(function() {
$.xhrPool.pop();
});
I didn't like the ajaxComplete() way of doing things. No matter how I tried to configure .ajaxSetup it did not work.
For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name
. Add this as the first line of your module:
global __DBNAME__
You can use list comprehension:
content = open("path/to/file.txt").readlines()
lookup = 'the dog barked'
lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]
print(lines)
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
I know this is an old topic but thought I would feed back in case it helps others. None of the answers to the question seem to work in IE8. I did however find this code that works in IE8. (Havent tested anything below IE8 yet). This can be easily modified for jQuery if required.
function capsCheck(e,obj){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('#'+obj.id).style.visibility = 'visible';
}
else document.getElementById('#'+obj.id).style.visibility = 'hidden';
}
And the function is called through the onkeypress event like this:
<input type="password" name="txtPassword" onkeypress="capsCheck(event,this);" />
<div id="capsWarningDiv" style="visibility:hidden">Caps Lock is on.</div>
Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.
WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();
or
using(WCFServiceClient client = new WCFServiceClient ())
{
//More codes here
}
In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:
The same applies if you simply switch the branch too.
Check out gVim. You can launch that in its own window.
gVim makes it really easy to manage multiple open buffers graphically.
You can also do the usual :e
to open a new file, CTRL+^ to toggle between buffers, etc...
Another cool feature lets you open a popup window that lists all the buffers you've worked on.
This allows you to switch between open buffers with a single click.
To do this, click on the Buffers menu at the top and click the dotted line with the scissors.
Otherwise you can just open a new tab from your terminal session and launch vi from there.
You can usually open a new tab from terminal with CTRL+T or CTRL+ALT+T
Once vi is launched, it's easy to open new files and switch between them.
\r
= CR (Carriage Return) → Used as a new line character in Mac OS before X\n
= LF (Line Feed) → Used as a new line character in Unix/Mac OS X\r\n
= CR + LF → Used as a new line character in Windowssometimes you need to select some fields by FirstOrDefault()
or singleOrDefault()
you can use the below query:
List<ResultLine> result = Lines
.GroupBy(l => l.ProductCode)
.Select(cl => new Models.ResultLine
{
ProductName = cl.select(x=>x.Name).FirstOrDefault(),
Quantity = cl.Count().ToString(),
Price = cl.Sum(c => c.Price).ToString(),
}).ToList();
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound).
For example, an algorithm taking Omega(n log n)
takes at least n log n
time, but has no upper limit. An algorithm taking Theta(n log n)
is far preferential since it takes at least n log n
(Omega n log n) and no more than n log n
(Big O n log n).
I would like to give one additional answer, while the other ones will suffice in most cases.
I wanted to write a string over multiple lines, but its contents needed to be single-line.
sql=" \
SELECT c1, c2 \
from Table1, ${TABLE2} \
where ... \
"
I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.
In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute
<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>
Inside the controller:
vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
vm.zoneDropdown = $customService.getZone();
}
And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):
<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
<a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
</li>
</ul>
ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y
Use the above command. It will definitely work.
In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:
/h
copies hidden and system files also/i
if destination does not exist and copying more than one file, assume that destination must be a directory/c
continue copying even if error occurs/k
copies attributes/e
copies directories and subdirectories, including empty ones/r
overwrites read-only files/y
suppress prompting to confirm whether you want to overwrite a fileA previous answer is mostly correct, but it will also match the empty string. The following would solve this.
^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$
If you really want to force-download all dependencies, you can try to re-initialise the entire maven repository. Like in this article already described, you could use:
mvn -Dmaven.repo.local=$HOME/.my/other/repository clean install
Try with quotes:
data: {"status": status, "name": name}
It must work fine.
To complete André's answer, an ant solution could be like the one described in Emacs, JDEE, Ant, and the Eclipse Java Compiler, as in:
<javac
srcdir="${src}"
destdir="${build.dir}/classes">
<compilerarg
compiler="org.eclipse.jdt.core.JDTCompilerAdapter"
line="-warn:+unused -Xemacs"/>
<classpath refid="compile.classpath" />
</javac>
The compilerarg element also allows you to pass in additional command line args to the eclipse compiler.
You can find a full ant script example here which would be invoked in a command line with:
java -cp C:/eclipse-SDK-3.4-win32/eclipse/plugins/org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar org.eclipse.core.launcher.Main -data "C:\Documents and Settings\Administrator\workspace" -application org.eclipse.ant.core.antRunner -buildfile build.xml -verbose
BUT all that involves ant, which is not what Keith is after.
For a batch compilation, please refer to Compiling Java code, especially the section "Using the batch compiler"
The batch compiler class is located in the JDT Core plug-in. The name of the class is org.eclipse.jdt.compiler.batch.BatchCompiler. It is packaged into plugins/org.eclipse.jdt.core_3.4.0..jar. Since 3.2, it is also available as a separate download. The name of the file is ecj.jar.
Since 3.3, this jar also contains the support for jsr199 (Compiler API) and the support for jsr269 (Annotation processing). In order to use the annotations processing support, a 1.6 VM is required.
Running the batch compiler From the command line would give
java -jar org.eclipse.jdt.core_3.4.0<qualifier>.jar -classpath rt.jar A.java
or:
java -jar ecj.jar -classpath rt.jar A.java
All java compilation options are detailed in that section as well.
The difference with the Visual Studio command line compilation feature is that Eclipse does not seem to directly read its .project and .classpath in a command-line argument. You have to report all information contained in the .project and .classpath in various command-line options in order to achieve the very same compilation result.
So, then short answer is: "yes, Eclipse kind of does." ;)
the easy way use this in button :
var table = $('#example1').DataTable();
table.row($(`#yesmediasec-${id}`).closest('tr')).remove( ).draw();
example1 = id table . yesmediasec = id of the button in the row
use it and every thing will be ok
you can copy an individual text apart from an HTML element's text.
var copyToClipboard = function (text) {
var $txt = $('<textarea />');
$txt.val(text)
.css({ width: "1px", height: "1px" })
.appendTo('body');
$txt.select();
if (document.execCommand('copy')) {
$txt.remove();
}
};
There are two options:
First
You can also use like is()
$('#dropDownId').is(':disabled');
Second
Using == true
by checking if the attributes value is disabled
. attr()
$('#dropDownId').attr('disabled');
whatever you feel fits better , you can use :)
Cheers!
I use Supervisor for development. It just works. When ever you make changes to a .js file Supervisor automatically restarts your app with those changes loaded.
Here's a link to its Github page
Install :
sudo npm install supervisor -g
You can easily make it watch other extensions with -e. Another command I use often is -i to ignore certain folders.
You can use nohup and supervisor to make your node app run in the background even after you log out.
sudo nohup supervisor myapp.js &
I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?
A sqlite db is on my hard disk E:\ABCD\efg\mydb.db
. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db
does not work. This is what question asked.
I found the best way to do the work is
E:\ABCD\efg\mydbs
)sqlite3
and then .open mydb.db
This way you can do the join operation on different tables belonging to different databases as well.
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
Here is a way how to send message in WhatsApp in KOTLIN
private fun sendMessage(phone: String, message: String) {
val pm = requireActivity().packageManager
val i = Intent(Intent.ACTION_VIEW)
try {
val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
message,
"UTF-8"
)
i.setPackage("com.whatsapp")
i.data = Uri.parse(url)
if (i.resolveActivity(pm) != null) {
context?.startActivity(i)
}
} catch (e: PackageManager.NameNotFoundException) {
Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
}
Depending on the length of the wanted loop, maybe even a more "template-driven" solution:
<ul>
<li *ngFor="let index of [0,1,2,3,4,5]">
{{ index }}
</li>
</ul>
No, there isn't one - you have a couple of options:
Wrap the whole script in a big if/end block that is simply ensured to not be true (i.e. "if 1=2 begin" - this will only work however if the script doesn't include any GO statements (as those indicate a new batch)
Use the return statement at the top (again, limited by the batch separators)
Use a connection based approach, which will ensure non-execution for the entire script (entire connection to be more accurate) - use something like a 'SET PARSEONLY ON' or 'SET NOEXEC ON' at the top of the script. This will ensure all statements in the connection (or until said set statement is turned off) will not execute and will instead be parsed/compiled only.
Use a comment block to comment out the entire script (i.e. /* and */)
EDIT: Demonstration that the 'return' statement is batch specific - note that you will continue to see result-sets after the returns:
select 1
return
go
select 2
return
select 3
go
select 4
return
select 5
select 6
go
Practically speaking, the :undolist
is hard to use and Vim’s :earlier
and :later
time tracking of changes is only usable for course-grain fixes.
Given that, I resort to a plug-in that combines these features to provide a visual tree of browsable undos, called “Gundo.”
Obviously, this is something to use only when you need a fine-grained fix, or you are uncertain of the exact state of the document you wish to return to. See: Gundo. Graph your Vim undo tree in style
The error is in your string formatting.
The correct way to use traditional string formatting using the '%' operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):
"'%s' is longer than '%s'" % (name1, name2)
However, the '%' operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:
"'{0}' is longer than '{1}'".format(name1, name2)
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
With SublimeText 3 on Windows, the problem is fixed by just closing the Sublime windows used for interactive commit edition.
It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?
If not, you can use netcat
for testing:
nc -l -k -p 5000
Some implementations may require you to omit the -p
flag.
You can use type-converter. To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
@Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
Make sure you have AndroidManifest.xml in the project.
It happened to me that I imported a project that didn't have the manifest yet so Android Studio wouldn't recognize it as an Android project. Then I pulled the project in GIT and it downloaded the manifest but still not working. Then I restarted Android Studio and it said something like "Framework detected android".
So make sure your project is configured as an Android project.
You can use
hdfs fsck /
to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with
hdfs fsck / | egrep -v '^\.+$' | grep -v eplica
which ignores lines with nothing but dots and lines talking about replication.
Once you find a file that is corrupt
hdfs fsck /path/to/corrupt/file -locations -blocks -files
Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.
You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.
Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.
Once you determine what happened and you cannot recover any more blocks, just use the
hdfs fs -rm /path/to/file/with/permanently/missing/blocks
command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.
Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL
UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";
Hope this helps someone else.
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String>
(the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this
pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
Go to Efficient Editing with vim and learn what you need to get started. Not everything on that page is essential starting off, so cherry pick what you want.
From there, use vim for everything. "hjkl", "y", and "p" will get you a long way, even if it's not the most efficient way. When you come up against a task for which you don't know the magic key to do it efficiently (or at all), and you find yourself doing it more than a few times, go look it up. Little by little it will become second nature.
I found vim daunting many moons ago (back when it didn't have the "m" on the end), but it only took about a week of steady use to get efficient. I still find it the quickest editor in which to get stuff done.
Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]
# 1. 'Actual' and 'Predicted' data
df <- data.frame(
y_actual = c(1:5),
y_predicted = c(0.8, 2.4, 2, 3, 4.8))
# 2. R2 Score components
# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)
# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)
# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total
svn delete --keep-local the_file
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
You don't have to do this locally either. You can do it through a remote repository, for example:
svn export http://<repo>/process/test.txt /path/to/code/
Using the lodash library you can write shorter
_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();
As with everything in git there are multiple ways of doing it. The two commands you used are one way of doing it. Another thing you could have done is simply stash them with git stash -u
. The -u
makes sure that newly added files (untracked) are also included.
The handy thing about git stash -u
is that
git stash pop
(it's like deleting an email in gmail where you can just undo if you change your mind afterwards)As of your other question git reset --hard
won't remove the untracked files so you would still need the git clean -f
. But a git stash -u
might be the most convenient.
For a side-by-side visual representation, I use git difftool
with openDiff
set to the default viewer.
Example usage:
git difftool tags/<FIRST TAG> tags/<SECOND TAG>
If you are only interested in a specific file, you can use:
git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>
As a side-note, the tags/<TAG>
s can be replaced with <BRANCH>
es if you are interested in diff
ing branches.
If you have spaces in the filename, try these:
[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)
First one seems more reliable
If you want to define a 3D matrix containing all zeros, you write
A = zeros(8,4,20);
All ones uses ones
, all NaN's uses NaN
, all false uses false
instead of zeros
.
If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.
For example
B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array
If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:
sqlite3 database.sqlite
Replace database.sqlite
with your database file. Then, if the database is small enough, you can view the entire contents with:
sqlite> .dump
Or you can list the tables:
sqlite> .tables
Regular SQL works here as well:
sqlite> select * from some_table;
Replace some_table
as appropriate.
Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.
The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.
Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.
Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
Apparently things are changing.... getDerivedStateFromProps() is now the preferred function.
class Component extends React.Component {_x000D_
static getDerivedStateFromProps(props, current_state) {_x000D_
if (current_state.value !== props.value) {_x000D_
return {_x000D_
value: props.value,_x000D_
computed_prop: heavy_computation(props.value)_x000D_
}_x000D_
}_x000D_
return null_x000D_
}_x000D_
}
_x000D_
Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.
CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE
AS
IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
BEGIN
UPDATE a
SET Date_Column = GETDATE()
FROM Table_A a
JOIN inserted i ON a.ID = i.ID
END
When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.
You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.
IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
I tried following on mac.
/Library/Android/sdk/platform-tools
../adb status
. "./"
is to be prefixed with "adb".adb shell
. Use command ./adb shell
to enter an adb shell. Now we have access to device's folder using shell.ls -la
./sdcard
within our device.(You can choose any folder here.) Suppose my destination is /sdcard/3233-3453/DCIM/Videos
and source is ~/Documents/Videos/film.mp4
./adb exit
./adb push [source location] [destination location]
./adb push ~/Documents/Videos/film.mp4 /sdcard/3233-3453/DCIM/Videos
I used threads to make the Flash Screen in android.
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
public class HomeScreen extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_home);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(3 * 1000);
Intent i = new Intent(HomeScreen.this, MainActivity.class);
startActivity(i);
} catch (InterruptedException e) {
}
}
};
thread.start();
}
}
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
You need to add an action
into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']);
does is that it sends your information to the top of your script so you could use it.
I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.
To check for Collection be empty or null
public static boolean isEmpty(Collection obj) {
return obj == null || obj.isEmpty();
}
or use Apache Commons CollectionUtils.isEmpty()
To check if Map is empty or null
public static boolean isEmpty(Map<?, ?> value) {
return value == null || value.isEmpty();
}
or use Apache Commons MapUtils.isEmpty()
To check for String empty or null
public static boolean isEmpty(String string) {
return string == null || string.trim().isEmpty();
}
or use Apache Commons StringUtils.isBlank()
To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
or
form_for @user, :url => whatever_path
@Luke Peterson: There's a simpler way to get .box file.
Just go to https://atlas.hashicorp.com/boxes/search, search for the box you'd like to download. Notice the URL of the box, e.g:
https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
Then you can download this box using URL like this:
https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box
I tried and successfully download all the boxes I need. Hope that help.
Does it matter which I use?
Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.
Which is faster?
Neither.
Is it a better practice to use the shortest code whenever possible?
Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).
I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader
on a Sectionable item, then you call showAllHeaders
. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.
Unfortunately footers are not covered (yet).
The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.
In 2015 I would go with:
Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.
Or just wait for ECMA6, 7, ... :)
Well, IMHO..
With regards to #1, I have a strongly typed Master View which has a property to access whatever the Session object represents....in my instance the stongly typed Master View is generic which gives me some flexibility with regards to strongly typed View Pages
ViewMasterPage<AdminViewModel>
AdminViewModel
{
SomeImportantObjectThatWasInSession ImportantObject
}
AdminViewModel<TModel> : AdminViewModel where TModel : class
{
TModel Content
}
and then...
ViewPage<AdminViewModel<U>>
First add a variable to your SSIS package (Package Scope) - I used FileName, OleRootFilePath, OleProperties, OleProvider. The type for each variable is "string". Then I create a Configuration file (Select each variable - value) - populate the values in the configuration file - Eg: for OleProperties - Microsoft.ACE.OLEDB.12.0; for OleProperties - Excel 8.0;HDR=, OleRootFilePath - Your Excel file path, FileName - FileName
In the Connection manager - I then set the Properties-> Expressions-> Connection string expression dynamically eg:
"Provider=" + @[User::OleProvider] + "Data Source=" + @[User::OleRootFilePath] + @[User::FileName] + ";Extended Properties=\"" + @[User::OleProperties] + "NO \""+";"
This way once you set the variables values and change it in your configuration file - the connection string will change dynamically - this helps especially in moving from development to production environments.
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved.The $@
and $<
are special macros.
Where:
$@
is the file name of the target.
$<
is the name of the first dependency.
Add in AppDelegate Class at the end of code
func appDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
To use AppDelegate reference in your class?
Call AppDelegate Method
appDelegate().setRoot()
Put the input
in the label, and ditch the for
attribute
<label>
label1:
<input type="text" id="id1" name="whatever" />
</label>
But of course, what if you want to style the text? Just use a span
.
<label id="id1">
<span>label1:</span>
<input type="text" name="whatever" />
</label>
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window
<!DOCTYPE html>
<html>
<body>
<center><h2>Heading</h2></center>
<center><p>Paragraph</p></center>
<iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
</body>
</html>
If you don't already have a JSONArray object, call
JSONArray jsonArray = new JSONArray(jsonArrayString);
Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
where('archived IS NOT NULL', null, false)
You can create a stored procedure passing 2 dates
CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);
Create table #tmpDates
(displayDate date)
WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END
Select *
from #tmpDates
drop table #tmpDates
To disable a keyboard key after IE9, use : e.preventDefault();
To disable a regular keyboard key under IE7/8, use : e.returnValue = false;
or return false;
If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F
) you need to add those lines :
try {
e.keyCode = 0;
}catch (e) {}
Here is a full example for IE7/8 only :
document.attachEvent("onkeydown", function () {
var e = window.event;
//Ctrl+F or F3
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
//Prevent for Ctrl+...
try {
e.keyCode = 0;
}catch (e) {}
//prevent default (could also use e.returnValue = false;)
return false;
}
});
Reference : How to disable keyboard shortcuts in IE7 / IE8
It depends on how you want the text to display. If you want it all to be left-aligned then either format it as in the first snippet or iterate through the lines left-trimming all the space.
EDIT:
To Be Clear: If the order of your #include
s matters and it is not part of your design pattern (read: you don't know why), then you need to rethink your design. Most likely, this just means you need to add the #include
to the header file causing problems.
At this point, I have little interest in discussing/defending the merits of the example but will leave it up as it illustrates some nuances in the compilation process and why they result in errors.
END EDIT
You need to #include
the stdint.h
BEFORE you #include
any other library interfaces that need it.
Example:
My LCD library uses uint8_t types. I wrote my library with an interface (Display.h
) and an implementation (Display.c
)
In display.c, I have the following includes.
#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
And this works.
However, if I re-arrange them like so:
#include <string.h>
#include <avr/io.h>
#include <Display.h>
#include <GlobalTime.h>
#include <stdint.h>
I get the error you describe. This is because Display.h
needs things from stdint.h
but can't access it because that information is compiled AFTER Display.h is compiled.
So move stdint.h
above any library that need it and you shouldn't get the error anymore.
Probably because you're using unsafe code.
Are you doing something with pointers or unmanaged assemblies somewhere?
Choose the project in eclipse - > Select run as -> Choose Java application. This displays a popup forcing you to select something, try searching your class having the main method in the search box. Once you find it, select it and hit ok. This will launch the spring boot application.
I do not have the spring tool suite installed in eclipse yet and still, it works. I hope this helps.
update the server arguments from -Dhttps.protocols=SSLv3 to -Dhttps.protocols=TLSv1,SSLv3
Probably the easiest solution so far:
public static Bitmap cropCenter(Bitmap bmp) {
int dimension = Math.min(bmp.getWidth(), bmp.getHeight());
return ThumbnailUtils.extractThumbnail(bmp, dimension, dimension);
}
imports:
import android.media.ThumbnailUtils;
import java.lang.Math;
import android.graphics.Bitmap;
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source
Try this it may help you:
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
You may be looking for following code:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
, Green
, Blue
valuesImplementation
private static string HexConverter(Color c) {
return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}
public static string RgbConverter(Color c) {
return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}
I know, that's the "answer" nobody wants. But if something's worth doing, it's worth doing right, right?
This seeming like a good idea probably stems from a fairly wide misconception that shell commands such as curl
are anything other than programs themselves.
So what you're asking is "how do I run this other program, from within my program, just to make a measly little web request?". That's crazy, there's got to be a better way right?
Uxio's answer works, sure. But it hardly looks very Pythonic, does it? That's a lot of work just for one little request. Python's supposed to be about flying! Anyone writing that is probably wishing they just call
'd curl
!
it works, but is there a better way?
Things shouldn’t be this way. Not in Python.
Let's GET this page:
import requests
res = requests.get('https://stackoverflow.com/questions/26000336')
That's it, really! You then have the raw res.text
, or res.json()
output, the res.headers
, etc.
You can see the docs (linked above) for details of setting all the options, since I imagine OP has moved on by now, and you - the reader now - likely need different ones.
But, for example, it's as simple as:
url = 'http://example.tld'
payload = { 'key' : 'val' }
headers = {}
res = requests.post(url, data=payload, headers=headers)
You can even use a nice Python dict to supply the query string in a GET request with params={}
.
Simple and elegant. Keep calm, and fly on.
if you are allowed to do it globally then you can set the session time out in
TOMCAT_HOME/conf/web.xml as below
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>
Use
<a href="/fruits/index.html">Back to Fruits List</a>
or
<a href="../index.html">Back to Fruits List</a>
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
You already got the right answer, but if you dislike the UIColor
interface like me, you can do this:
#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];
UIColor+Helper.h:
#import <UIKit/UIKit.h>
@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end
UIColor+Helper.m:
#import "UIColor+Helper.h"
@implementation UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
green:((color >> 16) & 0xFF) / 255.0f
blue:((color >> 8) & 0xFF) / 255.0f
alpha:((color) & 0xFF) / 255.0f];
}
@end
If you are using Clojure, you have another option:
(defn map-entry
[k v]
(clojure.lang.MapEntry/create k v))
One other way would be to use 4 letter commands to validate if zookeeper service is healthy or not
echo stat | nc <zookeeper ip> 2181
echo mntr | nc <zookeeper ip> 2181
echo isro | nc <zookeeper ip> 2181
More details on the documentation link below https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html#sc_zkCommands
Well here is a simple function which will return the left justified string version of an integer:
character(len=20) function str(k)
! "Convert an integer to string."
integer, intent(in) :: k
write (str, *) k
str = adjustl(str)
end function str
And here is a test code:
program x
integer :: i
do i=1, 100
open(11, file='Output'//trim(str(i))//'.txt')
write (11, *) i
close (11)
end do
end program x