The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.
Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%
generator- angular- fullstack offers 8% that MEANJS.org doesn't
MeanJS.org. offers 9% that generator-angular-fullstack doesn't
Here is the one between MEAN.io and MEAN.js in a more readable format
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br> * Dedicated/searchable user group for questions, using github issues<br> * There's a book about it<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side<br> * Module directories hold directives<br><b>Code Modularization</b>:<br> * Approach to AngularJS modules, Only one module definition per file<br> * Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br> * Object-relational mapping<br> * Server-side validation, server-side example<br> * Client side validation, using Angular 1.3<br><b>View</b>:<br> * Approach to AngularJS views, Directives start with "data-"<br> * Approach to data readiness, Use ng-init<br><b>Control</b>:<br> * Approach to frontend routing or state changing, URLs start with '#!'<br> * Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br> * Languages, LESS<br> * Languages, SASS<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br> * Testing, using Mocha<br> * End-to-end tests<br> * End-to-end tests, using Protractor<br> * Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br> * Command line interface (CLI), using Yeoman<br><b>Build</b>:<br> * Build configurations file(s)<br> * Deployment automation, using Azure<br> * Deployment automation, using Digital Ocean, screencast of it<br> * Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br> * Input application profile<br> * Quick install?<br> * Options for making subcomponents<br> * config generator<br> * controller (client side) generator<br> * directive generator<br> * filter generator<br> * route (client side) generator<br> * service (client side) generator<br> * test - client side<br> * view or view partial generator<br> * controller (server side) generator<br> * model (server side) generator<br> * route (server side) generator<br> * test (server side) generator<br><b>Implemented Functionality</b>:<br> * Account Management, Forgotten Password with Resetting<br> * Chat<br> * CSV processing<br> * E-mail sending system<br> * E-mail sending system, using Nodemailer<br> * E-mail sending system, using its own e-mail implementation<br> * Menus system, state-based<br> * Paypal integration<br> * Responsive design<br> * Social connections management page<br><b>Performance</b>:<br> * Creates a favicon<br><b>Security</b>:<br> * Safe from IP Spoofing<br> * Authorization, Access Contol List (ACL)<br> * Authentication, Cookie<br> * Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br> * Sponsoring company<br><b>Help</b>:<br> * Docs with flatdoc<br><b>Code Modularization</b>:<br> * Share code between projects<br> * Module manager<br><b>View</b>:<br> * Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br> * Approach to frontend code loading, Use AMD with Require.js<br> * Approach to frontend code loading, using wiredep<br> * Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br> * Centralized event handling<br> * Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br> * API introspection report and testing interface, using Swagger<br> * Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br> * Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br> * Deployment automation<br> * Deployment automation, using Heroku<br><b>Code Generation</b>:<br> * Scaffolding undo (mean package -d <name>)<br> * FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br> * Admin page for users and roles<br> * Content Management System (Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br> * File Upload<br> * i18n, localization<br> * Menus system, submenus<br> * Search<br> * Search, actually works with backend API<br> * Search, using Elastic Search<br> * Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br> * Text (WYSIWYG) Editor<br> * Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br> * Instrumentation, server-side<br><b>Security</b>:<br> * Serverside authenticated route restriction<br> * Authentication, using Oauth, Link multiple Oauth strategies to one account<br> * Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br> * Version Control, using git<br><b>Platforms</b>:<br> * Client-side JS Framework, using AngularJS<br> * Frontend Server/ Framework, using Node.JS<br> * Frontend Server/ Framework, using Node.JS, using Express<br> * API Server/ Framework, using NodeJS<br> * API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br> * Dedicated/searchable user group for questions<br> * Dedicated/searchable user group for questions, using Google Groups<br> * Dedicated/searchable user group for questions, using Facebook<br> * Dedicated/searchable user group for questions, response time mostly under a day<br> * Example application<br> * Tutorial screencast in English<br> * Tutorial screencast in English, using Youtube<br> * Dedicated chatroom<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side, with type subfolders<br> * Module directories hold controllers<br> * Module directories hold services<br> * Module directories hold templates<br> * Module directories hold unit tests<br> * Separate route configuration files for each module<br><b>Code Modularization</b>:<br> * Modularized Functionality<br> * Approach to AngularJS modules, No global 'app' module variable<br> * Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br> * Setup of persistent storage<br> * Setup of persistent storage, using NoSQL db<br> * Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br> * No XHR calls in controllers<br> * Templates, using Angular directives<br> * Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br> * Approach to frontend routing or state changing, example of it<br> * Approach to frontend routing or state changing, State-based routing<br> * Approach to frontend routing or state changing, State-based routing, using ui-router<br> * Approach to frontend routing or state changing, HTML5 Mode<br> * Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br> * Serve status codes only as responses<br> * Accept nested, JSON parameters<br> * Add timer header to requests<br> * Support for signed and encrypted cookies<br> * Serve URLs based on the route definitions<br> * Can serve headers only<br> * Approach to XHR calls, using JSON<br> * Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br> * Languages, JavaScript (server side)<br> * Languages, Swig<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br> * Separate runtime configuration profiles<br><b>Testing</b>:<br> * Testing, using Jasmine<br> * Testing, using Karma<br> * Client-side unit tests<br> * Continuous integration (CI)<br> * Automated device testing, using Live Reload<br> * Server-side integration & unit tests<br> * Server-side integration & unit tests, using Mocha<br><b>Development and debugging</b>:<br> * Command line interface (CLI)<br><b>Build</b>:<br> * Build-time Dependency Management, using npm<br> * Build-time Dependency Management, using bower<br> * Build tool / Task runner, using Grunt<br> * Build tool / Task runner, using gulp<br> * Development build, script<br> * Development build, reload build script file upon change<br> * Development build, copy assets to build or dist or target folder<br> * Development build, html page processing<br> * Development build, html page processing, inject references by searching directories<br> * Development build, html page processing, inject references by searching directories, injects js references<br> * Development build, html page processing, inject references by searching directories, injects css references<br> * Development build, LESS/SASS/etc files are linted, compiled<br> * Development build, JavaScript style checking<br> * Development build, JavaScript style checking, using jshint or jslint<br> * Development build, run unit tests<br> * Production build, script<br> * Production build, concatenation (aggregation, globbing, bundling) (If you add debug:true to your config/env/development.js the will not be <br>uglified)<br> * Production build, minification<br> * Production build, safe pre-minification, using ng-annotate<br> * Production build, uglification<br> * Production build, make static pages for SEO<br><b>Code Generation</b>:<br> * FEATURE (a.k.a. module, entity) generator (README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br> * 404 Page<br> * 500 Page<br> * Account Management<br> * Account Management, register/login/logout<br> * Account Management, is password manager friendly<br> * Front-end CRUD<br> * Full-stack CRUD<br> * Full-stack CRUD, with Read<br> * Full-stack CRUD, with Create, Update and Delete<br> * Google Analytics<br> * Menus system<br> * Realtime data sync<br> * Realtime data sync, using socket.io<br> * Styles, using Bootstrap<br><b>Performance</b>:<br> * Javascript performance thing<br> * Javascript performance thing, using lodash<br> * One event-loop thread handles all requests<br> * Configurable response caching (Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br> * Clustered HTTP sessions<br><b>Security</b>:<br> * JavaScript obfuscation<br> * https<br> * Authentication, using Oauth<br> * Authentication, Basic (With Passport or others)<br> * Authentication, Digest (With Passport or others)<br> * Authentication, Token (With Passport or others)<br></td></tr></tbody></table>
_x000D_
I actually wouldn't recommend using a2enmod
for php 5 or 7. I would use update-alternatives
. You can do sudo update-alternatives --config php
to set which system wide version of PHP you want to use. This makes your command line and apache versions work the same. You can read more about update-alternatives
on the man page.
Joseph forgot to add the value in his example with withDefault
.
Here is the code I ended up using:
Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files
After applying the patch the issue went away and connection went fine.
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
It works for some websites, remove property webdriver from navigator
from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source":
"const newProto = navigator.__proto__;"
"delete newProto.webdriver;"
"navigator.__proto__ = newProto;"
})
Change the loading order of your scripts so that function1
was defined before using it in ready
callback.
Plus I always found it better to define ready
callback as an anonymous method then named one.
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
You can use length()
from EditText
.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
You will need to Build and Archive your project. You may need to check what code signing settings you have in the project and executable.
Use the Organiser to select your archive version and then you can Share that version of your project. You will need to select the correct code signing again. It will allow you to save the .ipa file where you want.
Drag and drop the .ipa file into iTunes and then sync with your iPhone.
For Upgradation php in Xampp you can follow this steps, Else you can skip these 4 steps and direct install MAMP (for windows as well) from site and here is the direct download link
Step 1: Make backups Before starting, make sure to backup any settings, custom modules and most importantly the htdocs directory, which contains your scripts and page resources. This directory is normally located atC:\xampp\htdocs\
Step 2: Preparation
Download PHP 5.3.0rc2. I use the VC6 build in order to minimise any potential compatibility issues. It is also recommended that you download the latest Windows version of XAMPP. While this is an upgrade guide that shouldwork with previous versions of XAMPP, it is recommended that a fresh copy of the core files is used. Stop any instances of the Apache service that might be running.
Step 3: The upgrade This guide will assume your XAMPP directory is C:\xampp\
Extract the XAMPP archive to a directory of your choosing, I would recommend using the default C:\xampp\ Extract the contents of the PHP archive to C:\xampp\php\, overwriting the contents of this directory with the new files. Open the file C:\xampp\apache\conf\extra\httpd-xampp.conf and ensure the following lines are present in this order:
LoadFile "/xampp/php/php5ts.dll"
LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
Replace C:\xampp\php\php.ini with C:\xampp\php\php.ini-dist
Uncomment the lines:
;extension=php_mbstring.dll
;extension=php_pdo_sqlite.dll
Replace the line
magic_quotes_gpc = On
with
magic_quotes_gpc = Off
Copy all files in the C:\xampp\php\ to C:\xampp\apache\bin\ (do not copy the subdirectories or their contents).
After following the above steps, restart your Apache service (this can be done using C:\xampp\xampp-control.exe or manually through the control panel/command prompt). Your PHPinfo should indicate that the upgrade has been successful. I will update this post if I discover any problems from using this method, or a cleaner (automated) means of performing the upgrade.
Attempting to give an overview of the various discussions and answers:
There is no single answer to the question which can replace all the ways isset
can be used. Some use cases are addressed by other functions, while others do not stand up to scrutiny, or have dubious value beyond code golf. Far from being "broken" or "inconsistent", other use cases demonstrate why isset
's reaction to null
is the logical behaviour.
Arrays can be treated like collections of variables, with unset
and isset
treating them as though they were. However, since they can be iterated, counted, etc, a missing value is not the same as one whose value is null
.
The answer in this case, is to use array_key_exists()
instead of isset()
.
Since this is takes the array to check as a function argument, PHP will still raise "notices" if the array itself doesn't exist. In some cases, it can validly be argued that each dimension should have been initialised first, so the notice is doing its job. For other cases, a "recursive" array_key_exists
function, which checked each dimension of the array in turn, would avoid this, but would basically be the same as @array_key_exists
. It is also somewhat tangential to the handling of null
values.
In the traditional theory of "Object-Oriented Programming", encapsulation and polymorphism are key properties of objects; in a class-based OOP implementation like PHP's, the encapsulated properties are declared as part of the class definition, and given access levels (public
, protected
, or private
).
However, PHP also allows you to dynamically add properties to an object, like you would keys to an array, and some people use class-less objects (technically, instances of the built in stdClass
, which has no methods or private functionality) in a similar way to associative arrays. This leads to situations where a function may want to know if a particular property has been added to the object given to it.
As with array keys, a solution for checking object properties is included in the language, called, reasonably enough, property_exists
.
register_globals
, and other pollution of the global namespaceThe register_globals
feature added variables to the global scope whose names were determined by aspects of the HTTP request (GET and POST parameters, and cookies). This can lead to buggy and insecure code, which is why it has been disabled by default since PHP 4.2, released Aug 2000 and removed completely in PHP 5.4, released Mar 2012. However, it's possible that some systems are still running with this feature enabled or emulated. It's also possible to "pollute" the global namespace in other ways, using the global
keyword, or $GLOBALS
array.
Firstly, register_globals
itself is unlikely to unexpectedly produce a null
variable, since the GET, POST, and cookie values will always be strings (with ''
still returning true
from isset
), and variables in the session should be entirely under the programmer's control.
Secondly, pollution of a variable with the value null
is only an issue if this over-writes some previous initialization. "Over-writing" an uninitialized variable with null
would only be problematic if code somewhere else was distinguishing between the two states, so on its own this possibility is an argument against making such a distinction.
get_defined_vars
and compact
A few rarely-used functions in PHP, such as get_defined_vars
and compact
, allow you to treat variable names as though they were keys in an array. For global variables, the super-global array $GLOBALS
allows similar access, and is more common. These methods of access will behave differently if a variable is not defined in the relevant scope.
Once you've decided to treat a set of variables as an array using one of these mechanisms, you can do all the same operations on it as on any normal array. Consequently, see 1.
Functionality that existed only to predict how these functions are about to behave (e.g. "will there be a key 'foo' in the array returned by get_defined_vars
?") is superfluous, since you can simply run the function and find out with no ill effects.
$$foo
)While not quite the same as functions which turn a set of variables into an associative array, most cases using "variable variables" ("assign to a variable named based on this other variable") can and should be changed to use an associative array instead.
A variable name, fundamentally, is the label given to a value by the programmer; if you're determining it at run-time, it's not really a label but a key in some key-value store. More practically, by not using an array, you are losing the ability to count, iterate, etc; it can also become impossible to have a variable "outside" the key-value store, since it might be over-written by $$foo
.
Once changed to use an associative array, the code will be amenable to solution 1. Indirect object property access (e.g. $foo->$property_name
) can be addressed with solution 2.
isset
is so much easier to type than array_key_exists
I'm not sure this is really relevant, but yes, PHP's function names can be pretty long-winded and inconsistent sometimes. Apparently, pre-historic versions of PHP used a function name's length as a hash key, so Rasmus deliberately made up function names like htmlspecialchars
so they would have an unusual number of characters...
Still, at least we're not writing Java, eh? ;)
The manual page on variable basics includes this statement:
Uninitialized variables have a default value of their type depending on the context in which they are used
I'm not sure whether there is some notion in the Zend Engine of "uninitialized but known type" or whether this is reading too much into the statement.
What is clear is that it makes no practical difference to their behaviour, since the behaviours described on that page for uninitialized variables are identical to the behaviour of a variable whose value is null
. To pick one example, both $a
and $b
in this code will end up as the integer 42
:
unset($a);
$a += 42;
$b = null;
$b += 42;
(The first will raise a notice about an undeclared variable, in an attempt to make you write better code, but it won't make any difference to how the code actually runs.)
(Keeping this one last, as it's much longer than the others. Maybe I'll edit it down later...)
Consider the following code:
$test_value = 'hello';
foreach ( $list_of_things as $thing ) {
if ( some_test($thing, $test_value) ) {
$result = some_function($thing);
}
}
if ( isset($result) ) {
echo 'The test passed at least once!';
}
If some_function
can return null
, there's a possibility that the echo
won't be reached even though some_test
returned true
. The programmer's intention was to detect when $result
had never been set, but PHP does not allow them to do so.
However, there are other problems with this approach, which become clear if you add an outer loop:
foreach ( $list_of_tests as $test_value ) {
// something's missing here...
foreach ( $list_of_things as $thing ) {
if ( some_test($thing, $test_value) ) {
$result = some_function($thing);
}
}
if ( isset($result) ) {
echo 'The test passed at least once!';
}
}
Because $result
is never initialized explicitly, it will take on a value when the very first test passes, making it impossible to tell whether subsequent tests passed or not. This is actually an extremely common bug when variables aren't initialised properly.
To fix this, we need to do something on the line where I've commented that something's missing. The most obvious solution is to set $result
to a "terminal value" that some_function
can never return; if this is null
, then the rest of the code will work fine. If there is no natural candidate for a terminal value because some_function
has an extremely unpredictable return type (which is probably a bad sign in itself), then an additional boolean value, e.g. $found
, could be used instead.
very_null
constantPHP could theoretically provide a special constant - as well as null
- for use as a terminal value here; presumably, it would be illegal to return this from a function, or it would be coerced to null
, and the same would probably apply to passing it in as a function argument. That would make this very specific case slightly simpler, but as soon as you decided to re-factor the code - for instance, to put the inner loop into a separate function - it would become useless. If the constant could be passed between functions, you could not guarantee that some_function
would not return it, so it would no longer be useful as a universal terminal value.
The argument for detecting uninitialised variables in this case boils down to the argument for that special constant: if you replace the comment with unset($result)
, and treat that differently from $result = null
, you are introducing a "value" for $result
that cannot be passed around, and can only be detected by specific built-in functions.
Another way of thinking about what the last if
is asking is "has anything made an assignment to $result
?" Rather than considering it to be a special value of $result
, you could maybe think of this as "metadata" about the variable, a bit like Perl's "variable tainting". So rather than isset
you might call it has_been_assigned_to
, and rather than unset
, reset_assignment_state
.
But if so, why stop at a boolean? What if you want to know how many times the test passed; you could simply extend your metadata to an integer and have get_assignment_count
and reset_assignment_count
...
Obviously, adding such a feature would have a trade-off in complexity and performance of the language, so it would need to be carefully weighed against its expected usefulness. As with a very_null
constant, it would be useful only in very narrow circumstances, and would be similarly resistant to re-factoring.
The hopefully-obvious question is why the PHP runtime engine should assume in advance that you want to keep track of such things, rather than leaving you to do it explicitly, using normal code.
I just have the same problem, just open the task manager, go to services tab and search MySQL_One service, rigth click and start, this works for very good.
There is a new option in Postgressql 9.5 called DISTINCT ON
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;
It eliminates duplicate rows an leaves only the first row as defined my the ORDER BY clause.
see the official documentation
onclick
propertySuppose you added your click event inline, like this :
<button id="myButton" onclick="alert('test')">Married</button>
Then, you can remove the event like this :
$("#myButton").prop('onclick', null); // Removes 'onclick' property if found
click
event listenersSuppose you added your click event by defining an event listener, like this :
$("button").on("click", function() { alert("clicked!"); });
... or like this:
$("button").click(function() { alert("clicked!"); });
Then, you can remove the event like this :
$("#myButton").off('click'); // Removes other events if found
If you're uncertain how your event has been added, you can combine both, like this :
$("#myButton").prop('onclick', null) // Removes 'onclick' property if found
.off('click'); // Removes other events if found
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
I noticed that none of these answers mention the .Offset Property. This also can be used to avoid using the Select
action when manipulating certain cells, particularly in reference to a selected cell (as the OP mentions with ActiveCell
).
Here are a couple examples.
I will also assume the "ActiveCell" is J4.
ActiveCell.Offset(2, 0).Value = 12
J6
to be a value of 12 ActiveCell.Offset(0,1).Copy ActiveCell.Offset(,2)
k4
to L4
.i4
ActiveCell.Offset(, -1).EntireColumn.ClearContents
These aren't to say they are "better" than the above options, but just listing alternatives.
FOR SPECIFIC NUM:
SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1
FOR ALL NUM:
SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM
Here are the all keycodes.
Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.
http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php
Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.
Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12
This happens if you're using cocoapods, use the .xcworkspace
file instead of the default .xcodeproj
file.
The event generated is bubbling up until it is handled.
This xaml portion below triggers ui_Tab_Changed
after ui_A_Changed
when the item selected in the ListView
changes, regardless of TabItem
change in the TabControl
.
<TabControl SelectionChanged="ui_Tab_Changed">
<TabItem>
<ListView SelectionChanged="ui_A_Changed" />
</TabItem>
<TabItem>
<ListView SelectionChanged="ui_B_Changed" />
</TabItem>
</TabControl>
We need to consume the event in ui_A_Changed
(and ui_B_Changed
, and so on):
private void ui_A_Changed(object sender, SelectionChangedEventArgs e) {
// do what you need to do
...
// then consume the event
e.Handled = true;
}
>> For Visual Studio Users using Package Manager Console <<
If you are using the Package Manager Console in Visual Studio and you want to execute:
npm install
and get:
ENOENT: no such file or directory, open 'C:\Users...\YourProject\package.json'
Verify that you are executing the command in the correct directory.
VS by default uses the solution folder when opening the Package Manager Console.
Execute dir
then you can see in which folder you currently are. Most probably in the solution folder, that's why you get this error.
Now you have to cd
to your project folder.
cd YourWebProject
Now npm install
should work now, if not, then you have another issue.
if($("input:radio[name=test]").is(":checked")){
//Code to append goes here
}
"I am actually going to change the colors of these images based on what color scheme the user has chosen for my site." - Jordan 10 hours ago
I suggest you to use PHP for this. There's really no better way to do this without icon fonts, and if you resist using them, you could try this:
<?php
header('Content-Type: image/svg+xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
$color = $_GET['color'];
?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
<g>
<path fill="<?php echo $color; ?>" d="M28.44..."/>
</g>
</svg>
And later you could use this file as filename.php?color=#ffffff
to get the svg file in the desired color.
There is an important detail:
set PATH="C:\linutils;C:\wingit\bin;%PATH%"
does not work, while
set PATH=C:\linutils;C:\wingit\bin;%PATH%
works. The difference is the quotes!
UPD also see the comment by venimus
On linux, if you can afford the run time cost (for debugging), you can use valgrind with the massif tool:
http://valgrind.org/docs/manual/ms-manual.html
It is heavy weight, but very useful.
Parsing is the process of analyzing text made of a sequence of tokens to determine its grammatical structure with respect to a given (more or less) formal grammar.
The parser then builds a data structure based on the tokens. This data structure can then be used by a compiler, interpreter or translator to create an executable program or library.
(source: wikimedia.org)
If I gave you an english sentence, and asked you to break down the sentence into its parts of speech (nouns, verbs, etc.), you would be parsing the sentence.
That's the simplest explanation of parsing I can think of.
That said, parsing is a non-trivial computational problem. You have to start with simple examples, and work your way up to the more complex.
There are 2 major ways to create/intialize an array in swift.
var myArray = [Double]()
This would create an array of Doubles.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
This would create an array of 5 doubles, all initialized with the value of 2.0.
You left off the /
(pattern delimiter) and $
(match end string).
preg_match("/^[a-zA-Z0-9]+$/", $value)
I tried to limit Get-ChildItem recursion depth using Resolve-Path
$PATH = "."
$folder = get-item $PATH
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}
But this works fine :
gci "$PATH\*\*\*\*"
There are many different things you can do when dealing with responsive tables.
I personally like this approach by Chris Coyier:
You can find many other alternatives here:
If you can leverage Bootstrap and get something quickly, you can simply use the class names ".hidden-phone" and ".hidden-tablet" to hide some rows but this approach might to be the best in many cases. More info (see "Responsive utility classes"):
If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.
If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
Keep in mind, there are actually no restrictions on filenames on Unix systems other than
Everything else is fair game.
$ touch " > even multiline > haha > ^[[31m red ^[[0m > evil" $ ls -la -rw-r--r-- 0 Nov 17 23:39 ?even multiline?haha??[31m red ?[0m?evil $ ls -lab -rw-r--r-- 0 Nov 17 23:39 \neven\ multiline\nhaha\n\033[31m\ red\ \033[0m\nevil $ perl -e 'for my $i ( glob(q{./*even*}) ){ print $i; } ' ./ even multiline haha red evil
Yes, i just stored ANSI Colour Codes in a file name and had them take effect.
For entertainment, put a BEL character in a directory name and watch the fun that ensues when you CD into it ;)
Factory Method relies on inheritance: Object creation is delegated to subclasses, which implement the factory method to create objects.
Abstract Factory relies on object composition: object creation is implemented in methods exposed in the factory interface.
High level diagram of Factory and Abstract factory pattern,
For more information about the Factory method, refer this article.
For more information about Abstract factory method, refer this article.
You can also achieve this completely without jQueryUI by using CSS styles. See the snippet below:
div#Tooltip_Text_container {_x000D_
max-width: 25em;_x000D_
height: auto;_x000D_
display: inline;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
cursor: default;_x000D_
font-weight: normal;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container a span.tooltips {_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
transition: visibility 0s linear 0.2s, opacity 0.2s linear;_x000D_
position: absolute;_x000D_
left: 10px;_x000D_
top: 18px;_x000D_
width: 30em;_x000D_
border: 1px solid #404040;_x000D_
padding: 0.2em 0.5em;_x000D_
cursor: default;_x000D_
line-height: 140%;_x000D_
font-size: 12px;_x000D_
font-family: 'Segoe UI';_x000D_
-moz-border-radius: 3px;_x000D_
-webkit-border-radius: 3px;_x000D_
border-radius: 3px;_x000D_
-moz-box-shadow: 7px 7px 5px -5px #666;_x000D_
-webkit-box-shadow: 7px 7px 5px -5px #666;_x000D_
box-shadow: 7px 7px 5px -5px #666;_x000D_
background: #E4E5F0 repeat-x;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container:hover a span.tooltips {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
transition-delay: 0.2s;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container img {_x000D_
left: -10px;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container:hover a span.tooltips {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
transition-delay: 0.2s;_x000D_
}
_x000D_
<div id="Tooltip_Text_container">_x000D_
<span><b>Tooltip headline</b></span>_x000D_
<a href="#">_x000D_
<span class="tooltips">_x000D_
<b>This is </b> a tooltip<br/>_x000D_
<b>This is </b> another tooltip<br/>_x000D_
</span>_x000D_
</a>_x000D_
<br/>Move the mousepointer to the tooltip headline above. _x000D_
</div>
_x000D_
The first span is for the displayed text, the second span for the hidden text, which is shown when you hover over it.
Here's what I did:
That's it. I have tested it with my Nokia and it's working for me.
I change the function to Match + make a change here with the slashes and its work: (http:// and https) both
function isValidUrl(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
Here's my contribution. Haml + CoffeeScript + SCSS
=f.collection_select :country_id, [us] + Country.all, :id, :name, {prompt: t('user.country')}, class: 'form-control'
$('select').on 'change', ->
if $(this).val()
$(this).css('color', 'black')
else
$(this).css('color', 'gray')
$('select').change()
select option {
color: black;
}
It's possible to use only CSS by changing the server code and only setting the class styles depending on the current value of the property, but this way seems easier and cleaner.
$('select').on('change', function() {_x000D_
if ($(this).val()) {_x000D_
return $(this).css('color', 'black');_x000D_
} else {_x000D_
return $(this).css('color', 'gray');_x000D_
}_x000D_
});_x000D_
_x000D_
$('select').change();
_x000D_
select option {_x000D_
color: black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select class="form-control" name="user[country_id]" id="user_country_id">_x000D_
<option value="">Country</option>_x000D_
<option value="231">United States</option>_x000D_
<option value="1">Andorra</option>_x000D_
<option value="2">Afghanistan</option>_x000D_
<option value="248">Zimbabwe</option></select>
_x000D_
You can add more CSS (select option:first-child
) to keep the placeholder gray when it opens, but I didn't care about that.
Convert dictionary into JSON (string)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
will get you:
{"name": "Don", "sur
Convert string into dictionary
back_to_mydict = json.loads(result)
I got this error because I pasted alias columns into a DECLARE statement.
DECLARE @userdata TABLE(
f.TABLE_CATALOG nvarchar(100),
f.TABLE_NAME nvarchar(100),
f.COLUMN_NAME nvarchar(100),
p.COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata
ERROR: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '.'.
DECLARE @userdata TABLE(
f_TABLE_CATALOG nvarchar(100),
f_TABLE_NAME nvarchar(100),
f_COLUMN_NAME nvarchar(100),
p_COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata
NO ERROR
public static class StringExtensions
{
public static bool Contains(this string s, params string[] predicates)
{
return predicates.All(s.Contains);
}
}
string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";
if (d.Contains(a, b))
{
Console.WriteLine("d contains a and b");
}
My problem is related to many of the other answers, but a little bit different reason for needing to make the change... I was trying to convert an Activity to a Fragment. So I moved the inflate code from onCreate to onCreateView, but I forgot to convert from setContentView to the inflate method, and the same IllegalStateException brought me to this page.
I changed this:
binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)
to this:
binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)
That solved the problem.
Copied from bobince answer, but made it support question marks in the query string, eg
http://www.google.com/search?q=test???+something&aq=f
Is it valid to have more than one question mark in a URL?
function removeUrlParameter(url, parameter) {
var urlParts = url.split('?');
if (urlParts.length >= 2) {
// Get first part, and remove from array
var urlBase = urlParts.shift();
// Join it back up
var queryString = urlParts.join('?');
var prefix = encodeURIComponent(parameter) + '=';
var parts = queryString.split(/[&;]/g);
// Reverse iteration as may be destructive
for (var i = parts.length; i-- > 0; ) {
// Idiom for string.startsWith
if (parts[i].lastIndexOf(prefix, 0) !== -1) {
parts.splice(i, 1);
}
}
url = urlBase + '?' + parts.join('&');
}
return url;
}
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
It's a separate statement.
It's also not possible to insert into a table and select from it and build an index in the same statement either.
The BOL entry contains the information you need:
CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.
You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.
A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.
That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).
I had the same problem trying to port a Go program to C#. This means that a lot of data has already been encrypted with the Go program. This data must now be decrypted with C#.
The final solution was PaddingMode.None
or rather PaddingMode.Zeros
.
The cryptographic methods in Go:
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"encoding/base64"
"io/ioutil"
"log"
"golang.org/x/crypto/pbkdf2"
)
func decryptFile(filename string, saltBytes []byte, masterPassword []byte) (artifact string) {
const (
keyLength int = 256
rfc2898Iterations int = 6
)
var (
encryptedBytesBase64 []byte // The encrypted bytes as base64 chars
encryptedBytes []byte // The encrypted bytes
)
// Load an encrypted file:
if bytes, bytesErr := ioutil.ReadFile(filename); bytesErr != nil {
log.Printf("[%s] There was an error while reading the encrypted file: %s\n", filename, bytesErr.Error())
return
} else {
encryptedBytesBase64 = bytes
}
// Decode base64:
decodedBytes := make([]byte, len(encryptedBytesBase64))
if countDecoded, decodedErr := base64.StdEncoding.Decode(decodedBytes, encryptedBytesBase64); decodedErr != nil {
log.Printf("[%s] An error occur while decoding base64 data: %s\n", filename, decodedErr.Error())
return
} else {
encryptedBytes = decodedBytes[:countDecoded]
}
// Derive key and vector out of the master password and the salt cf. RFC 2898:
keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
keyBytes := keyVectorData[:keyLength/8]
vectorBytes := keyVectorData[keyLength/8:]
// Create an AES cipher:
if aesBlockDecrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
return
} else {
// CBC mode always works in whole blocks.
if len(encryptedBytes)%aes.BlockSize != 0 {
log.Printf("[%s] The encrypted data's length is not a multiple of the block size.\n", filename)
return
}
// Reserve memory for decrypted data. By definition (cf. AES-CBC), it must be the same lenght as the encrypted data:
decryptedData := make([]byte, len(encryptedBytes))
// Create the decrypter:
aesDecrypter := cipher.NewCBCDecrypter(aesBlockDecrypter, vectorBytes)
// Decrypt the data:
aesDecrypter.CryptBlocks(decryptedData, encryptedBytes)
// Cast the decrypted data to string:
artifact = string(decryptedData)
}
return
}
... and ...
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"encoding/base64"
"github.com/twinj/uuid"
"golang.org/x/crypto/pbkdf2"
"io/ioutil"
"log"
"math"
"os"
)
func encryptFile(filename, artifact string, masterPassword []byte) (status bool) {
const (
keyLength int = 256
rfc2898Iterations int = 6
)
status = false
secretBytesDecrypted := []byte(artifact)
// Create new salt:
saltBytes := uuid.NewV4().Bytes()
// Derive key and vector out of the master password and the salt cf. RFC 2898:
keyVectorData := pbkdf2.Key(masterPassword, saltBytes, rfc2898Iterations, (keyLength/8)+aes.BlockSize, sha1.New)
keyBytes := keyVectorData[:keyLength/8]
vectorBytes := keyVectorData[keyLength/8:]
// Create an AES cipher:
if aesBlockEncrypter, aesErr := aes.NewCipher(keyBytes); aesErr != nil {
log.Printf("[%s] Was not possible to create new AES cipher: %s\n", filename, aesErr.Error())
return
} else {
// CBC mode always works in whole blocks.
if len(secretBytesDecrypted)%aes.BlockSize != 0 {
numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
copy(enhanced, secretBytesDecrypted)
secretBytesDecrypted = enhanced
}
// Reserve memory for encrypted data. By definition (cf. AES-CBC), it must be the same lenght as the plaintext data:
encryptedData := make([]byte, len(secretBytesDecrypted))
// Create the encrypter:
aesEncrypter := cipher.NewCBCEncrypter(aesBlockEncrypter, vectorBytes)
// Encrypt the data:
aesEncrypter.CryptBlocks(encryptedData, secretBytesDecrypted)
// Encode base64:
encodedBytes := make([]byte, base64.StdEncoding.EncodedLen(len(encryptedData)))
base64.StdEncoding.Encode(encodedBytes, encryptedData)
// Allocate memory for the final file's content:
fileContent := make([]byte, len(saltBytes))
copy(fileContent, saltBytes)
fileContent = append(fileContent, 10)
fileContent = append(fileContent, encodedBytes...)
// Write the data into a new file. This ensures, that at least the old version is healthy in case that the
// computer hangs while writing out the file. After a successfully write operation, the old file could be
// deleted and the new one could be renamed.
if writeErr := ioutil.WriteFile(filename+"-update.txt", fileContent, 0644); writeErr != nil {
log.Printf("[%s] Was not able to write out the updated file: %s\n", filename, writeErr.Error())
return
} else {
if renameErr := os.Rename(filename+"-update.txt", filename); renameErr != nil {
log.Printf("[%s] Was not able to rename the updated file: %s\n", fileContent, renameErr.Error())
} else {
status = true
return
}
}
return
}
}
Now, decryption in C#:
public static string FromFile(string filename, byte[] saltBytes, string masterPassword)
{
var iterations = 6;
var keyLength = 256;
var blockSize = 128;
var result = string.Empty;
var encryptedBytesBase64 = File.ReadAllBytes(filename);
// bytes -> string:
var encryptedBytesBase64String = System.Text.Encoding.UTF8.GetString(encryptedBytesBase64);
// Decode base64:
var encryptedBytes = Convert.FromBase64String(encryptedBytesBase64String);
var keyVectorObj = new Rfc2898DeriveBytes(masterPassword, saltBytes.Length, iterations);
keyVectorObj.Salt = saltBytes;
Span<byte> keyVectorData = keyVectorObj.GetBytes(keyLength / 8 + blockSize / 8);
var key = keyVectorData.Slice(0, keyLength / 8);
var iv = keyVectorData.Slice(keyLength / 8);
var aes = Aes.Create();
aes.Padding = PaddingMode.Zeros;
// or ... aes.Padding = PaddingMode.None;
var decryptor = aes.CreateDecryptor(key.ToArray(), iv.ToArray());
var decryptedString = string.Empty;
using (var memoryStream = new MemoryStream(encryptedBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var reader = new StreamReader(cryptoStream))
{
decryptedString = reader.ReadToEnd();
}
}
}
return result;
}
How can the issue with the padding be explained? Just before encryption the Go program checks the padding:
// CBC mode always works in whole blocks.
if len(secretBytesDecrypted)%aes.BlockSize != 0 {
numberNecessaryBlocks := int(math.Ceil(float64(len(secretBytesDecrypted)) / float64(aes.BlockSize)))
enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
copy(enhanced, secretBytesDecrypted)
secretBytesDecrypted = enhanced
}
The important part is this:
enhanced := make([]byte, numberNecessaryBlocks*aes.BlockSize)
copy(enhanced, secretBytesDecrypted)
A new array is created with an appropriate length, so that the length is a multiple of the block size. This new array is filled with zeros. The copy method then copies the existing data into it. It is ensured that the new array is larger than the existing data. Accordingly, there are zeros at the end of the array.
Thus, the C# code can use PaddingMode.Zeros
. The alternative PaddingMode.None
just ignores any padding, which also works. I hope this answer is helpful for anyone who has to port code from Go to C#, etc.
You can also use the good old micro clearfix for this.
#container::before, #container::after{
content: ' ';
display: table;
}
See updated fiddle: http://jsfiddle.net/XB9wX/97/
Activity
to a Fragment
Activity:
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("message");
...
...
...
}
But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
You can do something like this, than you you'll access the native mongodb functions inside mongoose:
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
connection.db.collection("YourCollectionName", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // it will print your collection data
})
});
});
The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).
main()
should be declared as either:
int main(void)
int main(int argc, char **argv)
Or equivalent. For example, int main(int argc, char *argv[])
is equivalent to the second one. In C90, the int
return type can be omitted as it is a default, but in C99 and newer, the int
return type may not be omitted.
If an implementation permits it, main()
can be declared in other ways (e.g., int main(int argc, char *argv[], char *envp[])
), but this makes the program implementation defined, and no longer strictly conforming.
The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0
and EXIT_SUCCESS
for a successful termination, and EXIT_FAILURE
for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, main()
must have an explicit return
statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from main()
. If you do, and main()
finished, there is an implicit return 0
.
Finally, there is nothing wrong from a standards point of view with calling main()
recursively from a C program.
Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:
Click on the wamp icon &rarr: mysql → mysql console
write following commands, one by one
use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit
The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.
If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True
Here is an example:
import pandas as pd
import numpy as np
my_series = pd.Series([1,2,2,3,3,3])
print(my_series.value_counts())
3 3
2 2
1 1
dtype: int64
Notice here that the item returned is a pandas.Series
In comparison, numpy.unique
returns a tuple with two items, the unique values and the counts.
vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]
You can then combine these into a dictionary:
results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}
And then into a pandas.Series
print(pd.Series(results))
1 1
2 2
3 3
dtype: int64
As described here, this is another approach that takes care of symlinks too:
/**
* Copy a file, or recursively copy a folder and its contents
* @author Aidan Lister <[email protected]>
* @version 1.0.1
* @link http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
* @param string $source Source path
* @param string $dest Destination path
* @param int $permissions New folder creation permissions
* @return bool Returns true on success, false on failure
*/
function xcopy($source, $dest, $permissions = 0755)
{
$sourceHash = hashDirectory($source);
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if($sourceHash != hashDirectory($source."/".$entry)){
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
}
// Clean up
$dir->close();
return true;
}
// In case of coping a directory inside itself, there is a need to hash check the directory otherwise and infinite loop of coping is generated
function hashDirectory($directory){
if (! is_dir($directory)){ return false; }
$files = array();
$dir = dir($directory);
while (false !== ($file = $dir->read())){
if ($file != '.' and $file != '..') {
if (is_dir($directory . '/' . $file)) { $files[] = hashDirectory($directory . '/' . $file); }
else { $files[] = md5_file($directory . '/' . $file); }
}
}
$dir->close();
return md5(implode('', $files));
}
Just follow this
idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))
OR
idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))
And forget all others, else the brain won't be able to map all the formats.
Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.
This feature works for <button>
and <a>
.
If you use a <button>
, you must set the data-toggle
and data-target
attributes:
<button type="button" data-toggle="collapse" data-target="#collapseExample">
Toggle
</button>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
If you use a <a>
, you must use set href
and data-toggle
:
<a data-toggle="collapse" href="#collapseExample">
Toggle
</a>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
After a bunch of installing and uninstalling of Postgres, here's what now seems to work consistently for me with Os X Mavericks, Rails 4 and Ruby 2.
In the database.yml file, I change the default usernames to my computer's username which for me is just "admin".
In the command line I run rake db:create:all
Then I run rake db:migrate
When I run the rails server and check the local host it says "Welcome aboard".
Right-click the Project. Choose Add Asp.Net Folder. Under The Folder, create two folders one named VBCodeFiles and the Other CSCodeFiles In Web.Config add a new element under compilation
<compilation debug="true" targetFramework="4.5.1">
<codeSubDirectories>
<add directoryName="VBCodeFiles"/>
<add directoryName="CSCodeFiles"/>
</codeSubDirectories>
</compilation>
Now, Create an cshtml page. Add a reference to the VBCodeFiles.Namespace.MyClassName using
@using DMH.VBCodeFiles.Utils.RCMHD
@model MyClassname
Where MyClassName is an class object found in the namespace above. now write out the object in razor using a cshtml file.
<p>@Model.FirstName</p>
Please note, the directoryName="CSCodeFiles" is redundant if this is a C# Project and the directoryName="VBCodeFiles" is redundant if this is a VB.Net project.
You can declare like this
CREATE PROCEDURE MyProcName
@Parameter1 INT = 1,
@Parameter2 VARCHAR (100) = 'StringValue',
@Parameter3 VARCHAR (100) = NULL
AS
/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
/* whatever code you desire for a missing parameter*/
INSERT INTO ........
END
/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter
Array.from(new Array(row), () => new Array(col).fill(0));
I realize I'm late to the game, but here's a slightly Yum-style (Red Hat) one I wrote (not going for 100% accuracy here, but if you're using a progress bar for that level of accuracy, then you're WRONG anyway):
import sys
def cli_progress_test(end_val, bar_length=20):
for i in xrange(0, end_val):
percent = float(i) / end_val
hashes = '#' * int(round(percent * bar_length))
spaces = ' ' * (bar_length - len(hashes))
sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
sys.stdout.flush()
Should produce something looking like this:
Percent: [############## ] 69%
... where the brackets stay stationary and only the hashes increase.
This might work better as a decorator. For another day...
There are vary solutions about this, but I couldn't find a whole thing. So I made my own solution for :
How to use :
NICInfoSummary* summary = [[[NICInfoSummary alloc] init] autorelease];
// en0 is for WiFi
NICInfo* wifi_info = [summary findNICInfo:@"en0"];
// you can get mac address in 'XX-XX-XX-XX-XX-XX' form
NSString* mac_address = [wifi_info getMacAddressWithSeparator:@"-"];
// ip can be multiple
if(wifi_info.nicIPInfos.count > 0)
{
NICIPInfo* ip_info = [wifi_info.nicIPInfos objectAtIndex:0];
NSString* ip = ip_info.ip;
NSString* netmask = ip_info.netmask;
NSString* broadcast_ip = ip_info.broadcastIP;
}
else
{
NSLog(@"WiFi not connected!");
}
You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like this
This will show you error in the JSON you are trying to decode.
One general approach I haven't seen mentioned here is to run HTML through Tidy, which can be set to spit out guaranteed-valid XHTML. Then you can use any old XML library on it.
But to your specific problem, you should take a look at this project: http://fivefilters.org/content-only/ -- it's a modified version of the Readability algorithm, which is designed to extract just the textual content (not headers and footers) from a page.
Since for some reason white isn't available for selection, I have found that mat-palette($mat-grey, 50)
was close enough to white, for my needs at least.
I would imagine that the caching DNS servers you're using aren't behaving properly (or the DNS server for the domain you're resolving isn't working properly). You can try to fix the former possibility.
Do you have at least 2 name servers registered on your network adapter? You could always swap your computer over to use a different caching DNS server to rule this out. Try Google's:
8.8.8.8
8.8.4.4
In Laravel you can add a function inside app/Helper/helper.php like
function formatDate($date = '', $format = 'Y-m-d'){
if($date == '' || $date == null)
return;
return date($format,strtotime($date));
}
And call this function on any controller like this
$start_date = formatDate($start_date,'Y-m-d');
Hope it helps!
first see the details of the error if "state" is "1" Ensure the database is set for both SQL and Windows authentication under SQL server / Properties / Security.
for other state see the above answers ....
Well I was looking for some details and didn't find any example. So I am posting a transposeImage
function which, I hope, will help others who are looking for a direct way to rotate 90° without losing data:
IplImage* transposeImage(IplImage* image) {
IplImage *rotated = cvCreateImage(cvSize(image->height,image->width),
IPL_DEPTH_8U,image->nChannels);
CvPoint2D32f center;
float center_val = (float)((image->width)-1) / 2;
center.x = center_val;
center.y = center_val;
CvMat *mapMatrix = cvCreateMat( 2, 3, CV_32FC1 );
cv2DRotationMatrix(center, 90, 1.0, mapMatrix);
cvWarpAffine(image, rotated, mapMatrix,
CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS,
cvScalarAll(0));
cvReleaseMat(&mapMatrix);
return rotated;
}
Question : Why this?
float center_val = (float)((image->width)-1) / 2;
Answer : Because it works :) The only center I found that doesn't translate image. Though if somebody has an explanation I would be interested.
Try that:
if(WIN32)
set(ADDITIONAL_LIBRARIES wsock32)
else()
set(ADDITIONAL_LIBRARIES "")
endif()
target_link_libraries(${PROJECT_NAME} bioutils ${ADDITIONAL_LIBRARIES})
You can find other useful variables here.
In IntelliJ Idea,
Check the following things are configured properly,
Step 1:
File -> Setting -> Plugins -> search javafx and make sure its enabled.
Step 2: Project Structure (Ctrl+Shift+Alt+s)
Platform Settings -> SDKs -> 1.8 -> Make sure Classpath should have "jre\lib\ext\jfxrt.jar"
Step 3:
Project Settings -> Project -> Project SDK - should be selected 1.8
Project Settings -> Project -> Project language level - configured as 8
Ubuntu: If not found jfxrt.jar in your SDKs then install sudo apt-get install openjfx
Add border-collapse: collapse
into the style
attribute value of the inner table
element. You could alternatively add the attribute cellspacing=0
there, but then you would have a double border between the cells.
I.e.:
<table class="main-story-image" style="float: left; width: 180px; margin: 0 25px 25px 25px; border-collapse: collapse">
Even though, the best approach for this situation is set custom CSS styles - an alternative could be:
Width
property and set the percentaje as you see more suitable for your purposes.In my desired scenario, I need set (2) radiobuttons/items as follows:
o Item 1 | o Item 2 |
Example:
<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server"
BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal"
EnableTheming="False" Width="40%">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>
Rendered result:
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
<tbody>
<tr>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
</td>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
</td>
</tr>
</tbody>
</table>
_x000D_
You can determin mousewhell direction.
$(window).on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta ?
e.originalEvent.wheelDelta : -e.originalEvent.detail;
if (delta >= 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
Maybe I'm too naive but, couldn't you create an event that is raised when GetStringData() is called and attach an EventHandler that calls and awaits the async method?
Something like:
public event EventHandler FireAsync;
public string GetStringData()
{
FireAsync?.Invoke(this, EventArgs.Empty);
return "hello world";
}
public async void HandleFireAsync(object sender, EventArgs e)
{
await MyAsyncMethod();
}
And somewhere in the code attach and detach from the event:
FireAsync += HandleFireAsync;
(...)
FireAsync -= HandleFireAsync;
Not sure if this might be anti-pattern somehow (if it is please let me know), but it catches the Exceptions and returns quickly from GetStringData().
You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.
Because you do not provide any context or code for your question it is not possible to give a direct answer.
I suggest you study how unicode and character encoding is done in Python:
There is no "second property" -- when you say var obj = { ... }
, the properties inside the braces are unordered. Even a 'for' loop walking through them might return them in different orders on different JavaScript implementations.
There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.
For me below solution is worked:
The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.
Multiarch is a great achievement for cross compilation!
In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:
Since this is a lot of work I have automated the above setup. You can read about it here:
When i copied the date format for timestamp and used that for date, it did not work. But changing the date format to this (DD-MON-YY HH12:MI:SS AM) worked for me.
The change has to be made in Tools->Preferences-> search for NLS
You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python.
Note that this requires a jailbroken iPhone at the moment.
Try using OPENDATASOURCE The syntax is like this:
select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable
Assuming you want no password prompt:
ssh $HOST 'echo $PASSWORD | sudo -S $COMMMAND'
Example
ssh me@localhost 'echo secret | sudo -S echo hi' # outputs 'hi'
You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.
What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".
There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests
To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).
To add new files to the repository or add changed files to staged area:
$ git add <files>
To commit them:
$ git commit
To commit unstaged but changed files:
$ git commit -a
To push to a repository (say origin
):
$ git push origin
To push only one of your branches (say master
):
$ git push origin master
To fetch the contents of another repository (say origin
):
$ git fetch origin
To fetch only one of the branches (say master
):
$ git fetch origin master
To merge a branch with the current branch (say other_branch
):
$ git merge other_branch
Note that origin/master
is the name of the branch you fetched in the previous step from origin
. Therefore, updating your master branch from origin is done by:
$ git fetch origin master
$ git merge origin/master
You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:
I also had the same issue,it can be solved by creating a config and credential file in the home directory. Below show the steps I did to solve this issue.
Create a config file :
touch ~/.aws/config
And in that file I entered the region
[default]
region = us-west-2
Then create the credential file:
touch ~/.aws/credentials
Then enter your credentials
[Profile1]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
After set all these, then my python file to connect bucket. Run this file will list all the contents.
import boto3
import os
os.environ['AWS_PROFILE'] = "Profile1"
os.environ['AWS_DEFAULT_REGION'] = "us-west-2"
s3 = boto3.client('s3', region_name='us-west-2')
print("[INFO:] Connecting to cloud")
# Retrieves all regions/endpoints that work with S3
response = s3.list_buckets()
print('Regions:', response)
You can also refer below links:
This expression (inspired from Mike, above) seems to catch all duplicates, triplicates, etc, including the ones at the end of the string, which most of the others don't:
/(^|\s+)(\S+)(($|\s+)\2)+/g, "$1$2")
I know the question asked to match duplicates only, but a triplicate is just 2 duplicates next to each other :)
First, I put (^|\s+)
to make sure it starts with a full word, otherwise "child's steak" would go to "child'steak" (the "s"'s would match). Then, it matches all full words ((\b\S+\b)
), followed by an end of string ($
) or a number of spaces (\s+
), the whole repeated more than once.
I tried it like this and it worked well:
var s = "here here here here is ahi-ahi ahi-ahi ahi-ahi joe's joe's joe's joe's joe's the result result result";
print( s.replace( /(\b\S+\b)(($|\s+)\1)+/g, "$1"))
--> here is ahi-ahi joe's the result
I had similar problem with the data frame:
group time weight.loss
1 Control wl1 4.500000
2 Diet wl1 5.333333
3 DietEx wl1 6.200000
4 Control wl2 3.333333
5 Diet wl2 3.916667
6 DietEx wl2 6.100000
7 Control wl3 2.083333
8 Diet wl3 2.250000
9 DietEx wl3 2.200000
I think the variable for x axis should be numeric, so that geom_line knows how to connect the points to draw the line.
after I change the 2nd column to numeric:
group time weight.loss
1 Control 1 4.500000
2 Diet 1 5.333333
3 DietEx 1 6.200000
4 Control 2 3.333333
5 Diet 2 3.916667
6 DietEx 2 6.100000
7 Control 3 2.083333
8 Diet 3 2.250000
9 DietEx 3 2.200000
then it works.
For Ubuntu, PIL is not working any more. I always get:
No matching distribution found for PIL
So install python-imaging:
sudo apt-get install python-imaging
I would grab date.js or else you will need to roll your own formatting function.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
IMHO it is considered as malformed header data.
You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.
The second way is true.
For Visual Basic:
[Enum].GetNames(typeof(MyEnum)).Length
did not work with me, but
[Enum].GetNames(GetType(Animal_Type)).length
did.
In a few words:
Simulator -> Hardware -> Keyboard -> Toggle Software Keyboard should solve this problem.
I can think of at least 2 different ways:
using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.
From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)
Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.
Since java.sql.Date
extends java.util.Date
, you should be able to do
java.util.Date newDate = result.getDate("VALUEDATE");
Assume that you have 2 branches,
"branchA" : includes commits you want to copy (from "commitA" to "commitB"
"branchB" : the branch you want the commits to be transferred from "branchA"
1)
git checkout <branchA>
2) get the IDs of "commitA" and "commitB"
3)
git checkout <branchB>
4)
git cherry-pick <commitA>^..<commitB>
5) In case you have a conflict, solve it and type
git cherry-pick --continue
to continue the cherry-pick process.
@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
@Part("full_name") RequestBody fullName,
@Part MultipartBody.Part image,
@Part("other") RequestBody other);
//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// add another part within the multipart request
RequestBody fullName =
RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other);
Look at the way I am passing the multipart and string params. Hope this will help you!
You can enable Jetifier
on your project, which will basically exchange the Android Support Library
dependencies in your project dependencies with AndroidX
-ones. (e.g. Your Lottie dependencies will be changed from Support to AnroidX)
From the Android Studio Documentation (https://developer.android.com/studio/preview/features/):
The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file:
- android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on. If the flag is absent, Android Studio behaves as if the flag were set to false.
- android.enableJetifier: When set to true, this flag indicates that you want to have tool support (from the Android Gradle plugin) to automatically convert existing third-party libraries as if they were written for AndroidX. If the flag is absent, Android Studio behaves as if the flag were set to false.
Precondition for Jetifier:
Android Studio 3.2
To enable jetifier, add those two lines to your gradle.properties
file:
android.useAndroidX=true
android.enableJetifier=true
Finally, please check the release notes of AndroidX, because jetifier
has still some problems with some libraries (e.g. Dagger Android): https://developer.android.com/topic/libraries/support-library/androidx-rn
Integer Types:
short -> signed short
signed short
unsigned short
int -> signed int
signed int
unsigned int
signed -> signed int
unsigned -> unsigned int
long -> signed long
signed long
unsigned long
Be careful of char:
char (is signed or unsigned depending on the implmentation)
signed char
unsigned char
// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
/**
* Sanitize HTML
*/
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
/**
* Pipe Constructor
*
* @param _sanitizer: DomSanitezer
*/
// tslint:disable-next-line
constructor(protected _sanitizer: DomSanitizer) {
}
/**
* Transform
*
* @param value: string
* @param type: string
*/
transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
}
{{ data.url | safe:'url' }}
// Public properties
itsSafe: SafeHtml;
// Private properties
private safePipe: SafePipe = new SafePipe(this.domSanitizer);
/**
* Component constructor
*
* @param safePipe: SafeHtml
* @param domSanitizer: DomSanitizer
*/
constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
}
/**
* On init
*/
ngOnInit(): void {
this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
}
You can add a div with runat="server" to the page:
<div runat="server" id="myDiv">
</div>
and then set its InnerHtml property from the code-behind:
myDiv.InnerHtml = "your html here";
If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:
<script type="text/javascript">
Sys.Application.add_load(MyLoad);
function MyLoad(sender) {
$get('<%= div.ClientID %>').innerHTML += " - text added on client";
}
</script>
DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).
Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/
And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad
As Doug Currie says use RunAsService.
From my past experience you must remember that the Service you generate will
not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.
if your button is inside your form class:
buttonOk.Click += new EventHandler(your_click_method);
(might not be exactly EventHandler
)
and in your click method:
this.Close();
If you need to show a message box:
MessageBox.Show("test");
Right click can be achieved using Java script executor as well(in cases where action class is not supported):
JavascriptExecutor js = (JavascriptExecutor) driver;
String javaScript = "var evt = document.createEvent('MouseEvents');"
+ "var RIGHT_CLICK_BUTTON_CODE = 2;"
+ "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
+ "arguments[0].dispatchEvent(evt)";
js.executeScript(javaScript, element);
public class CryptographyProcessor
{
public string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
public string GenerateHash(string input, string salt)
{
byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
SHA256Managed sHA256ManagedString = new SHA256Managed();
byte[] hash = sHA256ManagedString.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
public bool AreEqual(string plainTextInput, string hashedInput, string salt)
{
string newHashedPin = GenerateHash(plainTextInput, salt);
return newHashedPin.Equals(hashedInput);
}
}
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
TextView Content Justification: Its easy guys just use android:justificationMode="inter_word" within your TextView tag.
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:text="@string/contents"
android:layout_margin="20dp"
android:justificationMode="inter_word"
/>
Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.
Setters/getters in Swift are quite different than ObjC. The property becomes a computed property which means it does not have a backing variable such as _x
as it would in ObjC.
In the solution code below you can see the xTimesTwo
does not store anything, but simply computes the result from x
.
See Official docs on computed properties.
The functionality you want might also be Property Observers.
What you need is:
var x: Int
var xTimesTwo: Int {
set {
x = newValue / 2
}
get {
return x * 2
}
}
You can modify other properties within the setter/getters, which is what they are meant for.
If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:
build.gradle
, change compileSdkVersion
to 23
and buildToolsVersion
to 24.0.0
gradle build
$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.
Since Docker 17.05 COPY
is used with the --from
flag in multi-stage builds to copy artifacts from previous build stages to the current build stage.
from the documentation
Optionally COPY accepts a flag
--from=<name|index>
that can be used to set the source location to a previous build stage (created with FROM .. AS ) that will be used instead of a build context sent by the user.
You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
return {_x000D_
country: elem.country,_x000D_
launches: elem.launches+10,_x000D_
} _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
Arrays can hold pointers so when I want an array of objects I do that.
$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);
This will show that the object is referenced and accessible through the array.
useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html
Basically you need to use the function htmlspecialchars()
whenever you want to output something to the browser that came from the user input.
The correct way to use this function is something like this:
echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
Google Code University also has these very educational videos on Web Security:
None of the answers seemed to work well with buttons. Bootstrap v4.1.1
<div class="card bg-light">
<div class="card-body">
<button type="submit" class="btn btn-primary">
Save
</button>
<a href="/" class="btn btn-secondary">
Cancel
</a>
</div>
</div>
It is actually executing the command, changing the directory to some_directory
, however, this is performed in a sub-process shell, and affects neither make nor the shell you're working from.
If you're looking to perform more tasks within some_directory
, you need to add a semi-colon and append the other commands as well. Note that you cannot use newlines as they are interpreted by make as the end of the rule, so any newlines you use for clarity needs to be escaped by a backslash.
For example:
all:
cd some_dir; echo "I'm in some_dir"; \
gcc -Wall -o myTest myTest.c
Note also that the semicolon is necessary between every command even though you add a backslash and a newline. This is due to the fact that the entire string is parsed as a single line by the shell. As noted in the comments, you should use '&&' to join commands, which mean they only get executed if the preceding command was successful.
all:
cd some_dir && echo "I'm in some_dir" && \
gcc -Wall -o myTest myTest.c
This is especially crucial when doing destructive work, such as clean-up, as you'll otherwise destroy the wrong stuff, should the cd
fail for whatever reason.
A common usage though is to call make in the sub directory, which you might want to look into. There's a command line option for this so you don't have to call cd
yourself, so your rule would look like this
all:
$(MAKE) -C some_dir all
which will change into some_dir
and execute the Makefile
in there with the target "all". As a best practice, use $(MAKE)
instead of calling make
directly, as it'll take care to call the right make instance (if you, for example, use a special make version for your build environment), as well as provide slightly different behavior when running using certain switches, such as -t
.
For the record, make always echos the command it executes (unless explicitly suppressed), even if it has no output, which is what you're seeing.
I had a similar issue and ended up with this:
For me this has the advantage that data and annotation are not overlapping.
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
x = A[ind]
y = B[ind]
xPos = x1 + .02 * (x1 - x0)
yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
ax.annotate('',#label,
xy=(x, y), xycoords='data',
xytext=(xPos, yPos), textcoords='data',
arrowprops=dict(
connectionstyle="arc3,rad=0.",
shrinkA=0, shrinkB=10,
arrowstyle= '-|>', ls= '-', linewidth=2
),
va='bottom', ha='left', zorder=19
)
ax.text(xPos + .01 * (x1 - x0), yPos,
'({:.2f}, {:.2f})'.format(x,y),
transform=ax.transData, va='center')
plt.grid()
plt.show()
Using the text argument in .annotate
ended up with unfavorable text positions.
Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.
The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.
HTML
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Javascript
var circle = d3.select("svg").append("circle")
.attr("r", "10")
.attr("style", "fill:white;stroke:black;stroke-width:5");
You could use a @HostListener decorator. Works with Angular 4 and up.
import { HostListener } from '@angular/core';
@HostListener("window:scroll", []) onWindowScroll() {
// do some stuff here when the window is scrolled
const verticalOffset = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0;
}
Yes, there is. The -r
option tells rm
to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir
.
The other two options you should know are -i
and -f
. -i
stands for interactive; it makes rm
prompt you before deleting each and every file. -f
stands for force; it goes ahead and deletes everything without asking. -i
is safer, but -f
is faster; only use it if you're absolutely sure you're deleting the right thing. You can specify these with -r
or not; it's an independent setting.
And as usual, you can combine switches: rm -r -i
is just rm -ri
, and rm -r -f
is rm -rf
.
Also note that what you're learning applies to bash
on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm
's syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.
Have a look at the cases
function from the memisc
package. It implements case-functionality with two different ways to use it.
From the examples in the package:
z1=cases(
"Condition 1"=x<0,
"Condition 2"=y<0,# only applies if x >= 0
"Condition 3"=TRUE
)
where x
and y
are two vectors.
References: memisc package, cases example
Please check that you are running the android device over same network. This will solve the problem. have fun!!!
Import ReactiveFormsModule in the corresponded module
react-scripts
is a set of scripts from the create-react-app
starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.
react-scripts start
sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.
with create-react-app you have following features out of the box.
- React, JSX, ES6, and Flow syntax support.
- Language extras beyond ES6 like the object spread operator.
- Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
- A fast interactive unit test runner with built-in support for coverage reporting.
- A live development server that warns about common mistakes.
- A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
- An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
- Hassle-free updates for the above tools with a single dependency.
npm start
is a shortcut for npm run start
.
npm run
is used to run scripts that you define in the scripts
object of your package.json
if there is no start
key in the scripts object, it will default to node server.js
Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject
. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.
The lock event ID is 4800, and the unlock is 4801. You can find them in the Security logs. You probably have to activate their auditing using Local Security Policy (secpol.msc, Local Security Settings in Windows XP) -> Local Policies -> Audit Policy. For Windows 10 see the picture below.
Look in Description of security events in Windows 7 and in Windows Server 2008 R2 under Subcategory: Other Logon/Logoff Events.
AFAIK, there is no a interactive option for output to file, there is a previous SO question related with this: Printing mongodb shell output to File
However, you can log all the shell session if you invoked the shell with tee command:
$ mongo | tee file.txt
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
Then you'll get a file with this content:
MongoDB shell version: 2.4.2
connecting to: test
> printjson({this: 'is a test'})
{ "this" : "is a test" }
> printjson({this: 'is another test'})
{ "this" : "is another test" }
> exit
bye
To remove all the commands and keep only the json output, you can use a command similar to:
tail -n +3 file.txt | egrep -v "^>|^bye" > output.json
Then you'll get:
{ "this" : "is a test" }
{ "this" : "is another test" }
I have tested the following regex which gives the same result as Chrome Html email input validation.
[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*
You can test it out on this website: regex101
Write "LogCat" in Quick Access edit box in your eclipse window (top right corner, just before Open Prospective button). And just select LogCat it will open-up the LogCat window in your current prospect
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
This worked for me:
chmod 700 .ssh
chmod 600 .ssh/id_rsa
chmod 644 .ssh/id_rsa.pub
Then, type this:
ssh-add ~/.ssh/id_rsa
Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick:
function regexIndexOf(string, regex, startpos) {
var indexOf = string.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
function regexLastIndexOf(string, regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if(typeof (startpos) == "undefined") {
startpos = string.length;
} else if(startpos < 0) {
startpos = 0;
}
var stringToWorkWith = string.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
UPDATE: Edited regexLastIndexOf()
so that is seems to mimic lastIndexOf()
now. Please let me know if it still fails and under what circumstances.
UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.
select * FROM (SELECT
ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID,
FROM EMP ) EMP where ROWID=5
greater then values find out
select * FROM (SELECT
ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID,
FROM EMP ) EMP where ROWID>5
less then values find out
select * FROM (SELECT
ROW_NUMBER() OVER (ORDER BY sal desc),* AS ROWID,
FROM EMP ) EMP where ROWID=5
do tab, then the + sign, then space, then your content
So
* level one
+ level two tabbed
You write like this-:
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%d %b %Y' //ex- 01 Jan 2016
}
}
also check for other datetime format
http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats
Just set targetSdkVersion to 19. The notification icon will be colored. Then wait for Firebase to fix this issue.
If you don't have any version of SQLServerManagerXX.msc, then you simply do not have it installed. I noticed it does not come with SQL server management studio 2019.
It's available (client-connectivity tools) in the SQL Server Express edition or SQL Server Developer edition which is good for dev/test (non-production) usage.
Use #pragma warning ( push )
, then #pragma warning ( disable )
, then put your code, then use #pragma warning ( pop )
as described here:
#pragma warning( push )
#pragma warning( disable : WarningCode)
// code with warning
#pragma warning( pop )
if you use window.open(url, '_blank')
, it will be blocked(popup blocker) on Chrome,Firefox etc
try this,
$('#myButton').click(function () {
var redirectWindow = window.open('http://google.com', '_blank');
redirectWindow.location;
});
working js fiddle for this http://jsfiddle.net/safeeronline/70kdacL4/2/
working js fiddle for ajax window open http://jsfiddle.net/safeeronline/70kdacL4/1/
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
If the directory ../.foo/bar/
doesn't exist, you can't create a file there, so make sure you create the directory first.
Try something like this:
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
f.createNewFile();
FILE=test
while read CMD; do
echo "$CMD"
done < "$FILE"
A redirection with < "$FILE"
has a few advantages over cat "$FILE" | while ...
. It avoids a useless use of cat, saving an unnecessary child process. It also avoids a common pitfall where the loop runs in a subshell. In bash, commands in a |
pipeline run in subshells, which means variable assignments are lost after the loop ends. Redirection with <
doesn't have that problem, so you could use $CMD
after the loop or modify other variables inside the loop. It also, again, avoids unnecessary child processes.
There are some additional improvements that could be made:
IFS=
so that read
won't trim leading and trailing whitespace from each line.-r
to read to prevent from backslashes from being interpreted as escape sequences.CMD
and FILE
. The bash convention is only environmental and internal shell variables are uppercase.printf
in place of echo
which is safer if $cmd
is a string like -n
, which echo
would interpret as a flag.file=test
while IFS= read -r cmd; do
printf '%s\n' "$cmd"
done < "$file"
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
There is also a property resourceRef
of JndiObjectFactoryBean
that is, when set to true
, used to automatically prepend the string java:comp/env/
if it is not already present.
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/loc"/>
<property name="resourceRef" value="true"/>
</bean>
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
In Xcode 9.3 you can do it by using storyboard like below,
You need to set button title textAlignment to center
button.titleLabel?.textAlignment = .center
You don't need to set title text with new line (\n) like below,
button.setTitle("Good\nAnswer",for: .normal)
Simply set title,
button.setTitle("Good Answer",for: .normal)
Here is the result,
You can use the hide
and show
functions of jquery. Examples
In your case just set $('#msform').hide()
or $('#msform').show()
Use the keys
method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]
$ git add -A
$ git reset --hard
In my case, this helped when there were a bunch of empty files that git was tracking.
Noise reduction, the less types you expose the more simple your library is. Tamper proofing / Security is another (although Reflection can win against it).
<form id="myform_id" action="/myMethode" role="form" method="post" >
<a href="javascript:$('#myform_id').submit();" >submit</a>
</form>
I had this error because I was providing a string of arguments to subprocess.call
instead of an array of arguments. To prevent this, use shlex.split
:
import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)
The general theory can be found in wikipedia's article on Kademlia. The specific protocol specification used in bittorrent is here: http://wiki.theory.org/BitTorrentDraftDHTProtocol
EDIT: So facebook has changed it again! No more searching by username - have amended the answer below...
https://graph.facebook.com/{{UID}}/picture?redirect=false&height=200&width=200
e.g. https://graph.facebook.com/4/picture?redirect=false&height=200&width=200
TL;DR If some arguments in your test are null
, be sure to mock the parameter call with isNull()
instead of anyXXX()
.
I got this error when upgrading from Spring boot 1.5.x to 2.1.x. Spring boot ships with its own Mockito, which is now also upgraded to 2.x (see e.g. Dependencies of Spring boot 2.1.2)
Mockito has changed the behavior for the anyXXX()
method, where XXX
is String
, Long
, etc. Here is the javadoc of anyLong()
:
Since Mockito 2.1.0, only allow valued
Long
, thusnull
is not anymore a valid value As primitive wrappers are nullable, the suggested API to matchnull
wrapper would be#isNull()
. We felt this change would make tests harness much safer that it was with Mockito 1.x.
I'd suggest you debug to the point where your mock is about to be called and inspect, whether at least one argument is null
. In that case make sure, that you prepare your mock with isNull()
instead of e.g. anyLong()
.
So this:
when(MockedClass.method(anyString());
becomes:
when(MockedClass.method(isNull());
ImageIcon
s. For a single image, I would think about making a custom subclass of JPanel
and overriding its paintComponent
method to draw the image.use this on:
$('body').on('focus',".datumwaehlen", function(){
$(this).datepicker({
minDate: -20
});
});
Without itertools
as a flattened list:
[(list1[i], list2[j]) for i in range(len(list1)) for j in range(len(list2))]
or in Python 2:
[(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))]
Even though that this question was already answered I feel that there are missing examples in the answer that was answered.
Therefore I'll bring here what I wrote in a blog post "Android Log Levels"
Verbose
Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.
Debug
Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.
Info
For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.
Warning
When there is a potentially harmful situation.
This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.
Error
Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.
WTF (What a Terrible Failure)
Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.
I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.
You could try overwriting the CSS and use auto
I don't think this will work with color specifically, but I ran into an issue where i had a parent property such as
.parent {
left: 0px;
}
and then I was able to just define my child with something like
.child {
left: auto;
}
and it effectively "reset" the property.
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
Even I am looking for the same feature, and as of today, its yet to be implemented. I can think of two options however,
I noticed that the behavior of Chrome and Safari are quite identical; Chrome even supports the Gyroscope and other related events which are supported by Safari. I am currently debugging my Web App by enabling the debug console on Safari (Through Settings->Safari)
Also try Adobe Shadow, which allows remote debugging/inspection and Sync.
HTH.
Other than that open the "View" menu at the top of the screen and un-check "Print Layout." Page breaks will now only be shown as a dashed line.
SELECT DateName(M, DateAdd(M, @MONTHNUMBER, -1))
git checkout .
will works otherwise it won't workEither store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.
Th part of an URI after the #
is called "fragment" and is by definition only available/processed on client side (see https://en.wikipedia.org/wiki/Fragment_identifier).
On the client side, this can be accessed using javaScript with window.location.hash
.
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Here is the simplest way:
#!/bin/sh
cat -
Usage:
$ echo test | sh my_script.sh
test
To assign stdin to the variable, you may use: STDIN=$(cat -)
or just simply STDIN=$(cat)
as operator is not necessary (as per @mklement0 comment).
To parse each line from the standard input, try the following script:
#!/bin/bash
while IFS= read -r line; do
printf '%s\n' "$line"
done
To read from the file or stdin (if argument is not present), you can extend it to:
#!/bin/bash
file=${1--} # POSIX-compliant; ${1:--} can be used either.
while IFS= read -r line; do
printf '%s\n' "$line" # Or: env POSIXLY_CORRECT=1 echo "$line"
done < <(cat -- "$file")
Notes:
-
read -r
- Do not treat a backslash character in any special way. Consider each backslash to be part of the input line.- Without setting
IFS
, by default the sequences of Space and Tab at the beginning and end of the lines are ignored (trimmed).- Use
printf
instead ofecho
to avoid printing empty lines when the line consists of a single-e
,-n
or-E
. However there is a workaround by usingenv POSIXLY_CORRECT=1 echo "$line"
which executes your external GNUecho
which supports it. See: How do I echo "-e"?
See: How to read stdin when no arguments are passed? at stackoverflow SE
Try this...
<script type="text/javascript">
$(document).ready(function(){
$("#find").click(function(){
var username = $("#username").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'includes/find.php',
data: 'username='+username,
success: function( data ) {
//in data you result will be available...
response = jQuery.parseJSON(data);
//further code..
},
error: function(xhr, status, error) {
alert(status);
},
dataType: 'text'
});
});
});
</script>
<form name="Find User" id="userform" class="invoform" method="post" />
<div id ="userdiv">
<p>Name (Lastname, firstname):</p>
</label>
<input type="text" name="username" id="username" class="inputfield" />
<input type="button" name="find" id="find" class="passwordsubmit" value="find" />
</div>
</form>
<div id="userinfo"><b>info will be listed here.</b></div>
You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.
something.data()
will return a pointer to the data space of the vector.
config/database.php
strict
key inside mysql
connection settingsfalse
Let's fill in the gaps in your code, by adding the other branches in the logic, and see what happens:
SQL> DECLARE
2 str1 varchar2(4000);
3 str2 varchar2(4000);
4 BEGIN
5 str1:='';
6 str2:='sdd';
7 IF(str1<>str2) THEN
8 dbms_output.put_line('The two strings is not equal');
9 ELSIF (str1=str2) THEN
10 dbms_output.put_line('The two strings are the same');
11 ELSE
12 dbms_output.put_line('Who knows?');
13 END IF;
14 END;
15 /
Who knows?
PL/SQL procedure successfully completed.
SQL>
So the two strings are neither the same nor are they not the same? Huh?
It comes down to this. Oracle treats an empty string as a NULL. If we attempt to compare a NULL and another string the outcome is not TRUE nor FALSE, it is NULL. This remains the case even if the other string is also a NULL.
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.
BLOB A string with a maximum length of 65535 characters.
The MySQL manual says:
The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers
I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
just replace your code:
old code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd'
});
new code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd',
minDate: 0
});
Read the documentation.
http://www.postgresql.org/docs/9.1/static/functions-datetime.html
I used a query like that:
WHERE
(
date_trunc('day',table1.date_eval) = '2015-02-09'
)
or
WHERE(date_trunc('day',table1.date_eval) >='2015-02-09'AND date_trunc('day',table1.date_eval) <'2015-02-09')
Juanitos Ingenier.
You need to use a variable to track "doneness" and then test it on every iteration of the loop. If done == true then return.
var done = false;
function setBgPosition() {
if ( done ) return;
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
if ( done ) return;
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length)
{
setTimeout(run, 200);
}else
{
setBgPosition();
}
}
setTimeout(run, 200);
}
setBgPosition(); // start the loop
setTimeout( function(){ done = true; }, 5000 ); // external event to stop loop
There are already a few answers here but I found flexbox to be the cleanest and least "hacky" solution:
parent-element {
display: flex;
align-items: center;
}
To support Safari < 8, Firefox < 21 and Internet Explorer < 10 (Use this polyfill to support IE8+9) you'll need vendor prefixes:
parent-element {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
Just to give some ideas to oracle Java source developer :-)
The solution already exists in .Net and is more very more readable !
In Visual Basic .Net
Drawable drawable
= If(Common.getDrawableFromUrl(this, product.getMapPath())
,getRandomDrawable()
)
In C#
Drawable drawable
= Common.getDrawableFromUrl(this, product.getMapPath()
?? getRandomDrawable();
These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.
Just to see quickly the difference with Java solution, I have added the 2 Java solutions
Using Optional in Java
Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
Using { } in Java
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable != null)
{
drawable = getRandomDrawable();
}
Personally, I like VB.Net but I prefer ?? C#
or if {}
solution in Java ... and you ?
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
Use this:
if(typeof(String.prototype.trim) === "undefined")
{
String.prototype.trim = function()
{
return String(this).replace(/^\s+|\s+$/g, '');
};
}
The trim function will now be available as a first-class function on your strings. For example:
" dog".trim() === "dog" //true
EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.
Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.
This is working for me:
this.listCopy = Object.assign([], this.list);
In the service.ts file -
a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
@Injectable()
export class ClientListService {
private clientList;
constructor() {
this.clientList = [
{name: 'abc', address: 'Railpar'},
{name: 'def', address: 'Railpar 2'},
{name: 'ghi', address: 'Panagarh'},
{name: 'jkl', address: 'Panagarh 2'},
];
}
getClientList () {
return Observable.of(this.clientList);
}
};
In the component where we are calling the get function of the service -
this.clientListService.getClientList().subscribe(res => this.clientList = res);
I tried restart: always
, it works at some containers(like php-fpm), but i faced the problem that some containers(like nginx) is still not restarting after reboot.
Solved the problem.
crontab -e
@reboot (sleep 30s ; cd directory_has_dockercomposeyml ; /usr/local/bin/docker-compose up -d )&
Anyone who wants to do a deep copy (e.g. if your array contains objects) can use:
let arrCopy = JSON.parse(JSON.stringify(arr))
Then you can sort arrCopy
without changing arr
.
arrCopy.sort((obj1, obj2) => obj1.id > obj2.id)
Please note: this can be slow for very large arrays.
You should be able to do this by simply typing npm install -g [email protected]
. If this does not work, I am beginning to wonder what version of node and npm you are on. Try node -v
and npm -v
to find these out. You should be on node >4.5 and npm >3
Don't give up. Linux can do it with the right hardware, via "USB Gadgets." And giving the following facts:
Why is all this relevant?
Because if I was writing a linux phone I know what it would do, and how it would do it. And the answer would involve USB Gadgets.
Reading one of the links that was posted here,
It's the Linux kernel, the code is in drivers/usb/gadget/ in the kernel.org tree if you are interested. Android does have a few specific gadget patches that are not in mainline, but it's not all that much. You can see all of this by just checking out their kernel git tree, no need to bother their developers.
I would guess that you would have a shot at it - but it would involve recompiling the android kernel/operating system - or at least having a build environment in which you /could/ rebuild the kernel if you wanted.
BTW, I have an Atmel NGW100mkII, which support USB gadgets, but doesn't ship with the HID module. And I'll be having to do the above and more.
It sounds like you're asking about a function
string Left(string s, int left)
that will return the leftmost left
characters of the string s
. In that case you can just use String.Substring
. You can write this as an extension method:
public static class StringExtensions
{
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return ( value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}
and use it like so:
string left = s.Left(number);
For your specific example:
string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);