I can't see that you're adding these controls to the control hierarchy. Try:
Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );
Events won't be invoked unless the control is part of the control hierarchy.
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
Another hacked solution, though might be a little cleaner by implementing a Proxy button:
HTML:
<input id="fileInput" type="file">
<md-button class="md-raised" ng-click="upload()">
<label>AwesomeButtonName</label>
</md-button>
JS:
app.controller('NiceCtrl', function ( $scope) {
$scope.upload = function () {
angular.element(document.querySelector('#fileInput')).click();
};
};
Use CollectionUtils.isEmpty(Collection coll)
Null-safe check if the specified collection is empty. Null returns true.
Parameters: coll - the collection to check, may be null
Returns: true if empty or null
You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.
Tl;dr of the blog post:
import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))
gives you
utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ? ?
Just place "javascript:void(0)", in place of "#" in href tag
<a href="javascript:void(0);" onclick="callmymethod(24)">Call</a>
Specify a simulator using the --simulator
flag.
These are the available devices for iOS 14.0 onwards:
npx react-native run-ios --simulator="iPhone 8"
npx react-native run-ios --simulator="iPhone 8 Plus"
npx react-native run-ios --simulator="iPhone 11"
npx react-native run-ios --simulator="iPhone 11 Pro"
npx react-native run-ios --simulator="iPhone 11 Pro Max"
npx react-native run-ios --simulator="iPhone SE (2nd generation)"
npx react-native run-ios --simulator="iPhone 12 mini"
npx react-native run-ios --simulator="iPhone 12"
npx react-native run-ios --simulator="iPhone 12 Pro"
npx react-native run-ios --simulator="iPhone 12 Pro Max"
npx react-native run-ios --simulator="iPod touch (7th generation)"
npx react-native run-ios --simulator="iPad Pro (9.7-inch)"
npx react-native run-ios --simulator="iPad Pro (11-inch) (2nd generation)"
npx react-native run-ios --simulator="iPad Pro (12.9-inch) (4th generation)"
npx react-native run-ios --simulator="iPad (8th generation)"
npx react-native run-ios --simulator="iPad Air (4th generation)"
List all available iOS devices:
xcrun simctl list devices
There is currently no way to set a default.
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String
, and you declare enums with TEST("test")
If I have understood it correctly, you are trying to convert a String representing a given date, to another type.
Note: (As @Samson Scharfrichter has mentioned)
There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):
SELECT cast('2018-06-05' as date);
Result: 2018-06-05 DATE_TYPE
or (depending on your pattern)
select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)
Result: 2018-06-05 DATE_TYPE
And if you decide to convert ISO8601 to a date type:
select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);
Result: 2018-06-05 DATE_TYPE
Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:
Date and timestamp functions examples:
Convert String/Timestamp/Date to DATE
SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
Convert String/Timestamp/Date to BIGINT_TYPE
SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
Convert String/Timestamp/Date to STRING
SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
Convert BIGINT unixtime to STRING
SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE
Convert String to BIGINT unixtime
SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE
Convert String to TIMESTAMP
SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE
Idempotent (String -> String)
SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE
Idempotent (Date -> Date)
SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE
Current date / timestamp
SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE
I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).
File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.
Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.
If I understand correct you will have something like this:
<input value="default" id="sth" name="sth" type="hidden">
And to get it you have to write:
@Html.HiddenFor(m => m.sth, new { Value = "default" })
for Strongly-typed view.
TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem();
tempItem = (TreeViewItem) treeView1.Items.GetItemAt(0); // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0); // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString(); // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true; // will expand the first node
On top of your lastest jsfiddle, you just missed one thing:
#sidebar_wrap {
width:40%;
height:200px;
background:green;
float:right;
}
#sidebar {
width:inherit;
margin-top:10px;
background-color:limegreen;
position:fixed;
max-width: 240px; /*This is you missed*/
}
But, how this will solve your problem? Simple, lets explain why is bigger than expect first.
Fixed element #sidebar
will use window width size as base to get its own size, like every other fixed element, once in this element is defined width:inherit
and #sidebar_wrap
has 40% as value in width, then will calculate window.width * 40%
, then when if your window width is bigger than your .container
width, #sidebar
will be bigger than #sidebar_wrap
.
This is way, you must set a max-width in your #sidebar_wrap
, to prevent to be bigger than #sidebar_wrap
.
Check this jsfiddle that shows a working code and explain better how this works.
The one who believes that
"abc\n" . "def\n"
is multiline string is wrong. That's two strings with concatenation operator, not a multiline string. Such concatenated strings cannot be used as keys of pre-defined arrays, for example. Unfortunately php does not offer real multiline strings in form of
"abc\n"
"def\n"
only HEREDOC
and NOWDOC
syntax, which is more suitable for templates, because nested code indent is broken by such syntax.
I solved the problem by uninstalling JDK 9.
First get the commit ID using,
git log #to list all
Or
git log -p -1 #last one commit id
Copy commit id.
Now we use two methods to list changes from a specific commit,
Method 1:
git diff commit_id^! #commit id something like this 1c6a6000asad012
Method 2:
git show commit_id
For example: git show 1c6a600a
The following statement is not entirely accurate:
"So if you are calling other functionality, including static classes, from your page, you should be fine"
I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.
As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:
There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:
[WebMethod(EnableSession = true)]
By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.
Thanks to Matthew Cosier for the solution.
Just thought I'd add my two cents.
Ed
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
An alternative, I think for your purpose, is to use the round() function:
select round((10 * 1.5),2) // prints 15.00
You can try it here:
Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :
desired_capabilities['chromeOptions'] = {
"args": ["--disable-extensions"],
"extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)
The LEA (Load Effective Address) instruction is a way of obtaining the address which arises from any of the Intel processor's memory addressing modes.
That is to say, if we have a data move like this:
MOV EAX, <MEM-OPERAND>
it moves the contents of the designated memory location into the target register.
If we replace the MOV
by LEA
, then the address of the memory location is calculated in exactly the same way by the <MEM-OPERAND>
addressing expression. But instead of the contents of the memory location, we get the location itself into the destination.
LEA
is not a specific arithmetic instruction; it is a way of intercepting the effective address arising from any one of the processor's memory addressing modes.
For instance, we can use LEA
on just a simple direct address. No arithmetic is involved at all:
MOV EAX, GLOBALVAR ; fetch the value of GLOBALVAR into EAX
LEA EAX, GLOBALVAR ; fetch the address of GLOBALVAR into EAX.
This is valid; we can test it at the Linux prompt:
$ as
LEA 0, %eax
$ objdump -d a.out
a.out: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <.text>:
0: 8d 04 25 00 00 00 00 lea 0x0,%eax
Here, there is no addition of a scaled value, and no offset. Zero is moved into EAX. We could do that using MOV with an immediate operand also.
This is the reason why people who think that the brackets in LEA
are superfluous are severely mistaken; the brackets are not LEA
syntax but are part of the addressing mode.
LEA is real at the hardware level. The generated instruction encodes the actual addressing mode and the processor carries it out to the point of calculating the address. Then it moves that address to the destination instead of generating a memory reference. (Since the address calculation of an addressing mode in any other instruction has no effect on CPU flags, LEA
has no effect on CPU flags.)
Contrast with loading the value from address zero:
$ as
movl 0, %eax
$ objdump -d a.out | grep mov
0: 8b 04 25 00 00 00 00 mov 0x0,%eax
It's a very similar encoding, see? Just the 8d
of LEA
has changed to 8b
.
Of course, this LEA
encoding is longer than moving an immediate zero into EAX
:
$ as
movl $0, %eax
$ objdump -d a.out | grep mov
0: b8 00 00 00 00 mov $0x0,%eax
There is no reason for LEA
to exclude this possibility though just because there is a shorter alternative; it's just combining in an orthogonal way with the available addressing modes.
Using Java8 lambdas
List<BigDecimal> items = Arrays.asList(a, b, c, .....);
items.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
This covers cases where the some or all of the objects in the list is null.
I know this is a little bit too late but it might just help someone.
In my case I already had a method to make the Object from a json Object and make json from the object. with this you can simply create a new instance of the object and use it to restore. For instance in a function parsing a final object
public void update(final Object object){ _x000D_
final Object original = Object.makeFromJSON(object.toJSON()); _x000D_
// the original is not affected by changes made to object _x000D_
}
_x000D_
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
Try jQuery.inArray()
Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0
Example Code :
<html>
<head>
<style>
div { color:blue; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>
"Pete" is in the array, but not at or after index 2, so <span></span>
</div>
<script>
var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>
</body>
</html>
Output:
"John" found at 3 4 found at 0 "Karl" not found, so -1 "Pete" is in the array, but not at or after index 2, so -1
The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether. Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?
ArrayList
is the collections of different types data whereas List<>
is the collection of similar type of its own depedencties.
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
This query works well:
INSERT INTO `user` ( `username` , `password` )
SELECT * FROM (SELECT 'ersks', md5( 'Nepal' )) AS tmp
WHERE NOT EXISTS (SELECT `username` FROM `user` WHERE `username` = 'ersks'
AND `password` = md5( 'Nepal' )) LIMIT 1
And you can create the table using following query:
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(32) NOT NULL,
`status` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Note: Create table using second query before trying to use first query.
You could use a project post-build event to write a text file to your target directory with the current datetime. You could then read the value at run-time. It's a little hacky, but it should work.
If the issue reported from MainActivity.java then replace
import android.support.v7.app.AppCompatActivity;
with
import androidx.appcompat.app.AppCompatActivity;
Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648
Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.
I solved a similar problem by passing the value of the available parameter in the URL instead of the label of the parameter.
For instance, I have a report with a parameter named viewName and the predefined Available Values for the parameter are: (labels/values) orders/sub_orders, orderDetail/sub_orderDetail, product/sub_product.
To call this report with a URL to render automatically for parameter=product, you must specify the value not the label.
This would be wrong:
http://server/reportserver?/Data+Dictionary/DetailedInfo&viewName=product&rs:Command=Render
This is correct: http://server/reportserver?/Data+Dictionary/DetailedInfo&viewName=sub_product&rs:Command=Render
Run "setup_xampp.bat/.sh" and then Delete "\" at the end, so your ServerRoot should be like "C:.....\apache" NO "C:.....\apache\"
The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.
First you define the type like this:
CREATE TYPE UserList AS TABLE ( UserID INT );
Then you use that type in the stored procedure:
create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)
So before you call that stored procedure, you fill a table variable:
DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)
And finally call the SP:
EXEC dbo.get_user_names @UL, @username OUTPUT;
Just to be sure that this is really the "conversion" you need, please note that jks
files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.
So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool
(but in a more accessible way).
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)You can use :
-XX:MaxPermSize=128m
to increase the space. But this usually only postpones the inevitable.
You can also enable the PermGen to be garbage collected
-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled
Usually this occurs when doing lots of redeploys. I am surprised you have it using something like indexing. Use virtualvm or jconsole to monitor the Perm gen space and check it levels off after warming up the indexing.
Maybe you should consider changing to another JVM like the IBM JVM. It does not have a Permanent Generation and is immune to this issue.
You could print through a PrintStream.
PrintStream ps = new PrintStream(fop);
ps.println(nodeValue);
ps.close();
you can also use this:
echo $pageName = basename($_SERVER['SCRIPT_NAME']);
For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.
LD_LIBRARY_PATH
is searched when the program starts, LIBRARY_PATH
is searched at link time.
caveat from comments:
ld
(instead of gcc
or g++
), the LIBRARY_PATH
or LD_LIBRARY_PATH
environment variables are not read.gcc
or g++
, the LIBRARY_PATH
environment variable is read (see documentation "gcc
uses these directories when searching for ordinary libraries").Simple assigning to window.location
or window.location.href
should be fine:
window.location = newUrl;
However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:
Use the URL hash. For example, you can go from example.com
to example.com#foo
without loading a new page. You can simply set window.location.hash
to make this easy. Then, you should listen to the HTML5 hashchange
event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.
You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo
to example.com/bar
. Using this is easy:
window.history.pushState("example.com/foo");
When the user presses "back", you'll receive the window's popstate
event, which you can easily listen to (jQuery):
$(window).bind("popstate", function(e) { alert("location changed"); });
Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.
echo
has the problem that if var
contains something like -e
, it will be interpreted as a flag. Another option is printf
, but printf "$var" > "$destdir"
will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won't match. However, because printf
only interprets backslashes as escapes in the format string, you can use the %s
format specifier to store the exact variable contents to the destination file:
printf "%s" "$var" > "$destdir"
void func (vector v)
Pass variables by value when the function needs complete isolation from the environment i.e. to prevent the function from modifying the original variable as well as to prevent other threads from modifying its value while the function is being executed.
The downside is the CPU cycles and extra memory spent to copy the object.
void func (const vector& v);
This form emulates pass-by-value behavior while removing the copying overhead. The function gets read access to the original object, but cannot modify its value.
The downside is thread safety: any change made to the original object by another thread will show up inside the function while it's still executing.
void func (vector& v)
Use this when the function has to write back some value to the variable, which will ultimately get used by the caller.
Just like the const reference case, this is not thread-safe.
void func (const vector* vp);
Functionally same as pass by const-reference except for the different syntax, plus the fact that the calling function can pass NULL pointer to indicate it has no valid data to pass.
Not thread-safe.
void func (vector* vp);
Similar to non-const reference. The caller typically sets the variable to NULL when the function is not supposed to write back a value. This convention is seen in many glibc APIs. Example:
void func (string* str, /* ... */) {
if (str != NULL) {
*str = some_value; // assign to *str only if it's non-null
}
}
Just like all pass by reference/pointer, not thread-safe.
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
A simpler way is to do xcopy to make a copy of the entire directory structure using /s switch. help for /s says Copies directories and subdirectories except empty ones.
xcopy dirA dirB /S
where dirA is source with Empty folders. DirB will be the copy without empty folders
string.Format("{0:000}", myString);
This was tested and was working on iOS 9 GM seed - this is the configuration to allow a specific domain to use HTTP instead of HTTPS:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key> <!--Include your domain at this line -->
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
NSAllowsArbitraryLoads
must be false
, because it disallows all insecure connection, but the exceptions list allows connection to some domains without HTTPS.
Here is a simple way to convert Calendar
values into Date
instances.
Calendar C = new GregorianCalendar(1993,9,21);
Date DD = C.getTime();
System.out.println(DD);
[Kotlin version] I created this extension that also checks if the desired color has enough contrast to hide the System UI, like Battery Status Icon, Clock, etc, so we set the System UI white or black according to this.
fun Activity.coloredStatusBarMode(@ColorInt color: Int = Color.WHITE, lightSystemUI: Boolean? = null) {
var flags: Int = window.decorView.systemUiVisibility // get current flags
var systemLightUIFlag = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
var setSystemUILight = lightSystemUI
if (setSystemUILight == null) {
// Automatically check if the desired status bar is dark or light
setSystemUILight = ColorUtils.calculateLuminance(color) < 0.5
}
flags = if (setSystemUILight) {
// Set System UI Light (Battery Status Icon, Clock, etc)
removeFlag(flags, systemLightUIFlag)
} else {
// Set System UI Dark (Battery Status Icon, Clock, etc)
addFlag(flags, systemLightUIFlag)
}
window.decorView.systemUiVisibility = flags
window.statusBarColor = color
}
private fun containsFlag(flags: Int, flagToCheck: Int) = (flags and flagToCheck) != 0
private fun addFlag(flags: Int, flagToAdd: Int): Int {
return if (!containsFlag(flags, flagToAdd)) {
flags or flagToAdd
} else {
flags
}
}
private fun removeFlag(flags: Int, flagToRemove: Int): Int {
return if (containsFlag(flags, flagToRemove)) {
flags and flagToRemove.inv()
} else {
flags
}
}
In java 5 new feature added that is Scanner method who gives the chance to read input character by character in java.
for instance; for use Scanner method import java.util.Scanner; after in main method:define
Scanner myScanner = new Scanner(System.in); //for read character
char anything=myScanner.findInLine(".").charAt(0);
you anything store single character, if you want more read more character declare more object like anything1,anything2... more example for your answer please check in your hand(copy/paste)
import java.util.Scanner;
class ReverseWord {
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
char c1,c2,c3,c4;
c1 = myScanner.findInLine(".").charAt(0);
c2 = myScanner.findInLine(".").charAt(0);
c3 = myScanner.findInLine(".").charAt(0);
c4 = myScanner.findInLine(".").charAt(0);
System.out.print(c4);
System.out.print(c3);
System.out.print(c2);
System.out.print(c1);
System.out.println();
}
}
Add below dependency in pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.1</version>
</dependency>
Was facing the same issue as the return type cannot be bind with the MediaType of Class Foo. After adding the dependency it worked.
Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.
Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.
You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/
In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.
If I understand correctly, you're already using pandas.read_csv()
but would like to speed up the development process so that you don't have to load the file in every time you edit your script, is that right? I have a few recommendations:
you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000)
to only load the top bit of the table, while you're doing the development
use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script.
convert the csv to an HDF5 table
updated use DataFrame.to_feather()
and pd.read_feather()
to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle()
on numeric data and much faster on string data).
You might also be interested in this answer on stackoverflow.
I am working on a library that provides class like code capabilities to Javascript, currently it supports constructors, inheritance, methods overload by number of params and by types of params, mixins, statics properties and singleton.
See an example of method overloading using that library:
eutsiv.define('My.Class', {
constructor: function() {
this.y = 2;
},
x: 3,
sum: function() {
return this.x + this.y;
},
overloads: {
value: [
function() { return this.x + ', ' + this.y },
function(p1) { this.x = p1; },
function(p1, p2) { this.x = p1; this.y = p2; } // will set x and y
]
}
});
var test = new My.Class({ x: 5 }); // create the object
test.value(); // will return '5, 2'
test.sum(); // will return 7
test.value(13); // will set x to 13
test.value(); // will return '13, 2'
test.sum(); // will return 15
test.value(10, 20); // will set x to 10 and y to 20
test.value(); // will return '10, 20'
test.sum(); // will return 30
Any feedback, bug fixes, docs and tests improves are welcome!
Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var temp : String? // This is an optional.
temp = "I am a programer"
print(temp) // Optional("I am a programer")
var temp1 : String! // This is not optional.
temp1 = "I am a programer"
print(temp1) // "I am a programer"
UPDATED ANSWER
Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :
Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.
To delete the account, follow the following steps : (refer to image below)
Delete Account
Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.
Deleting a property will remove the selected property, and all the views it holds. To delete a property, delete all views it contains individually (see below for deleting views)
Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.
Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.
Use another account.
Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.
Previous Answer :
These are the steps to delete a profile from Google Support page :
Delete profiles
Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.
To delete a profile:
- Click the Admin tab at the top right of any Analytics page.
- Click the account that contains the profile you want to delete.
- Click the web property from which you want to delete the profile.
- Use the Profile menu to select the profile.
- Click the Profile Settings tab.
- Click Delete this profile at the bottom of the page.
- Click Delete in the confirmation message.
Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using
sudo passwd
If you do everything correctly, it should do something like this:
user@server[~]# sudo passwd
Changing password for user root.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
All the results were as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
If you add:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
in the head of the document it will start working as expected:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
This is due to a PHP 5.3.0 bug on Windows where MYSQL_ATTR_INIT_COMMAND is not available. The PHP bug report is:
http://bugs.php.net/bug.php?id=47224
If you are experiencing this, please update your WAMP product to a version that uses PHP 5.3.1 or later version.
Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:
newHero() {
return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>
If you need to find database objects (e.g. tables, columns, and triggers) by name - have a look at the free Redgate Software tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely free to use for any kind of use??
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
transferring file from local to remote host
scp -i (path of your key) (path for your file to be transferred) (username@ip):(path where file to be copied)
e.g scp -i aws.pem /home/user1/Desktop/testFile ec2-user@someipAddress:/home/ec2-user/
P.S. - ec2-user@someipAddress of this ip address should have access to the destination folder in my case /home/ec2-user/
In your example, you can replace the forEach
with lamdba with a simple for
loop and modify any variable freely. Or, probably, refactor your code so that you don't need to modify any variables. However, I'll explain for completeness what does the error mean and how to work around it.
Java 8 Language Specification, §15.27.2:
Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.
Basically you cannot modify a local variable (calTz
in this case) from within a lambda (or a local/anonymous class). To achieve that in Java, you have to use a mutable object and modify it (via a final variable) from the lambda. One example of a mutable object here would be an array of one element:
private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
TimeZone[] result = { null };
try {
cal.getComponents().getComponents("VTIMEZONE").forEach(component -> {
...
result[0] = ...;
...
}
} catch (Exception e) {
log.warn("Unable to determine ical timezone", e);
}
return result[0];
}
No, there's no legal and reliable way to do this.
If you find a way, it will be disabled in the future, as it has happened with every method before.
I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.
.inline li {
display: inline;
}
android.view.InflateException: Binary XML file line #16: Error inflating class com.google.android.material.bottomappbar.BottomAppBar
The view can be anything that is failing to get inflated, this kind of error comes when there is a clash in resolving the class names or name attribute of a view referred in the XML file.
When I get the same error I just got everything clean and safe in UI-XML file, the view I was using,
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomAppBar"
style="@style/Widget.MaterialComponents.BottomAppBar.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:hideOnScroll="true"
app:menu="@menu/bottom_app_bar"
app:navigationIcon="@drawable/ic__menu_24"/>
I was using a style attribute which was referring the Material components property. But my styles.xml had...
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
....
</style>
Where the class resolving was facing the conflict. My view attributes referred a property that was not defined in my app theme. The right parent theme from material components helped me. So I changed the parent attribute to...
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
...
</style>
Which resolved the issue.
<?php
$iPhone = false;
$AndroidPhone = false;
$deviceType = 0;
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
print "<br>".$ua;
if(strpos($ua,"iphone") !== false ){
$iPhone = true;
}
if(strpos($ua,"android") !== false){
if(strpos($_SERVER['HTTP_USER_AGENT'],"mobile")){
$AndroidPhone = true;
}
}
if(stripos($_SERVER['HTTP_USER_AGENT'],"iPad")){
$iPad = true;
$Tablet = true;
$iOS = true;
}
if($AndroidPhone==true || $iPhone==true)
{
$deviceType = 1;
}
?>
LogisticRegression
is not for regression but classification !
The Y
variable must be the classification class,
(for example 0
or 1
)
And not a continuous
variable,
that would be a regression problem.
Things are pretty much simpler unless they are made confusing.
To Install GD library in Ubuntu
sudo apt-get install php5-gd
To Install Freetype in Ubuntu
sudo apt-get install libfreetype6-dev:i386
There is another case where the two possibilities differ, on top of those already mentioned: if you need to call a non-public constructor (protected or private), make_shared might not be able to access it, while the variant with the new works fine.
class A
{
public:
A(): val(0){}
std::shared_ptr<A> createNext(){ return std::make_shared<A>(val+1); }
// Invalid because make_shared needs to call A(int) **internally**
std::shared_ptr<A> createNext(){ return std::shared_ptr<A>(new A(val+1)); }
// Works fine because A(int) is called explicitly
private:
int val;
A(int v): val(v){}
};
I simply copy the file directly from where the container is located from the host machine.
For example:
First find out the container id:
root@**3aed62678d54**:/home#
And then from the host, let's say the file is in the home directory:
root@saasdock:/home/dnepangue# cp cheering_nasa.gif /var/lib/docker/aufs/mnt/**3aed62678d54**a5df47a4a00a58bb0312009c2902f8a37498a1427052e8ac454b/home/
Back to the container...
root@**3aed62678d54**:/home# ls cheering_nasa.gif
To watch out the runtime changes in value of a custom directive, use $observe
method of attrs
object, instead of putting $watch
inside a custom directive.
Here is the documentation for the same ... $observe docs
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
Other possibilities for .tpl
: HTML::SimpleTemplate, example:
Hello $name
, and Template Toolkit, example:
Hello [% world %]!
Function
CREATE FUNCTION dbo.SplitToRows (@column varchar(100), @separator varchar(10))
RETURNS @rtnTable TABLE
(
ID int identity(1,1),
ColumnA varchar(max)
)
AS
BEGIN
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Insert into @rtnTable(ColumnA) Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
Insert into @rtnTable(ColumnA) select @tempString
set @position=@endAt+1;
END
return
END
Use case
select * from dbo.SplitToRows('T14; p226.0001; eee; 3554;', ';')
Or just a select with multiple result set
DECLARE @column varchar(max)= '1234; 4748;abcde; 324432'
DECLARE @separator varchar(10) = ';'
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
select @tempString
set @position=@endAt+1;
END
For me, I define some properties:
disabledFirstOption = true;
get isIEOrEdge(): boolean {
return /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
}
Then in the constructor and ngOnInit
constructor() {
this.disabledFirstOption = false;
}
ngOnInit() {
setTimeout(() => {
this.disabledFirstOption = true;
});
}
And in the template I add this as the first option inside the select element
<option *ngIf="isIEOrEdge" [value]="undefined" [disabled]="disabledFirstOption" selected></option>
If you allow to select the first option you can just remove the usage of the property disabledFirstOption
Instead of storing the options on the client-side, another way to do this is to store the options as sub-array elements of an associative/indexed array on the server-side. The values of the select tag would then just contain the keys used to dereference the sub-array.
Here is some example code. This is written in PHP since the OP mentioned PHP, but it can be adapted to whatever server-side language you are using:
<FORM action="" method="POST">
<SELECT NAME="Testing">
<OPTION VALUE="1"> One </OPTION>
<OPTION VALUE="2"> Two </OPTION>
<OPTION VALUE="3"> Three </OPTION>
</SELECT>
</FORM>
PHP:
<?php
$options = array(
1 => array('value1' => '1', 'value2' => '2010'),
2 => array('value1' => '2', 'value2' => '2122'),
3 => array('value1' => '3', 'value2' => '0'),
);
echo 'Selected option value 1: ' . $options[$_POST['Testing']]['value1'] . '<br>';
echo 'Selected option value 2: ' . $options[$_POST['Testing']]['value2'] . '<br>';
I believe that the dates have to be specified in the current culture of the application. You might want to experiment with setting CultureInvariantValues to true and see if that solves your problem. Otherwise you may need to change the DateTimeFormat for the current culture (or the culture itself) to get what you want.
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
Usage:
control.InvokeIfRequired(c => c.Visible = false);
return control.InvokeIfRequired(c => {
c.Visible = value
return c.Visible;
});
Code:
using System;
using System.ComponentModel;
namespace Extensions
{
public static class SynchronizeInvokeExtensions
{
public static void InvokeIfRequired<T>(this T obj, Action<T> action)
where T : ISynchronizeInvoke
{
if (obj.InvokeRequired)
{
obj.Invoke(action, new object[] { obj });
}
else
{
action(obj);
}
}
public static TOut InvokeIfRequired<TIn, TOut>(this TIn obj, Func<TIn, TOut> func)
where TIn : ISynchronizeInvoke
{
return obj.InvokeRequired
? (TOut)obj.Invoke(func, new object[] { obj })
: func(obj);
}
}
}
An answer to your Question from 2019:
It depends on what version of ECMAScript you use.
Pre ES6:
Use any of the answers below, e.g.:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
For ES6 (ES 2015):
You should use a Map
object, which has the entries()
function:
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
For ES8 (ES 2017):
Object.entries()
was introduced:
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
try (UPDATE)
MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date(); _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
This will give you a javascript date object with the converted time
In our case we FIXED by adding changeDetection into the component and call detectChanges() in ngAfterContentChecked, code as follows
@Component({
selector: 'app-spinner',
templateUrl: './spinner.component.html',
styleUrls: ['./spinner.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SpinnerComponent implements OnInit, OnDestroy, AfterContentChecked {
show = false;
private subscription: Subscription;
constructor(private spinnerService: SpinnerService, private changeDedectionRef: ChangeDetectorRef) { }
ngOnInit() {
this.subscription = this.spinnerService.spinnerState
.subscribe((state: SpinnerState) => {
this.show = state.show;
});
}
ngAfterContentChecked(): void {
this.changeDedectionRef.detectChanges();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Find out the format of the floating point numbers used on the CPU that directly supports floating point and break it down into those parts. The most common format is IEEE-754.
Alternatively, you could obtain those parts using a few special functions (double frexp(double value, int *exp);
and double ldexp(double x, int exp);
) as shown in this answer.
Another option is to use %a
with printf()
.
To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir();
to get the allowed directory for the app.
Or:
getCashDir();
<-- should work
context.getCashDir();
(if in a broadcast receiver)
getDataDir();
<--Api 24
In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:
$(function() {
$(".draggable").draggable({
opacity: .4,
create: function(){$(this).data('position',$(this).position())},
cursor:'move',
start:function(){$(this).stop(true,true)}
});
$('.active').droppable({
over: function(event, ui) {
$(ui.helper).unbind("mouseup");
},
drop:function(event, ui){
snapToMiddle(ui.draggable,$(this));
},
out:function(event, ui){
$(ui.helper).mouseup(function() {
snapToStart(ui.draggable,$(this));
});
}
});
});
function snapToMiddle(dragger, target){
var topMove = target.position().top - dragger.data('position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
var leftMove= target.position().left - dragger.data('position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
dragger.animate({top:topMove,left:leftMove},{duration:600,easing:'easeOutBack'});
}
function snapToStart(dragger, target){
dragger.animate({top:0,left:0},{duration:600,easing:'easeOutBack'});
}
Add android.permission.READ_EXTERNAL_STORAGE in manifest, worked for me
You can try DBVisualizer some features are not free, but you can get an evaluate license...
Go to Project > properties > Debug Tab and set the Launch to "Project"
To make a batch file for its current directory and sub directories:
cd %~dp0
attrib -h -r -s /s /d /l *.*
Install qt using:
sudo apt install qt5-qmake
Open ~/.bashrc
file:
vim ~/.bashrc
Added the path below to the ~/.bashrc
file:
export PATH="/opt/Qt/5.15.1/gcc_64/bin/:$PATH"
Execute/load a ~/.bashrc
file in your current shell
source ~/.bashrc`
Try now qmake
by using the version command below:
qmake --version
You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:
$('.owl-carousel').owlCarousel({
autoplay: true,
autoplayTimeout: 5000,
navigation: false,
margin: 10,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 2
}
}
})
Chris' answer is good but could be made more idiomatic by using a set to check for seen directories, which also avoids using an exception for control flow:
def directory_size(path):
total_size = 0
seen = set()
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
try:
stat = os.stat(fp)
except OSError:
continue
if stat.st_ino in seen:
continue
seen.add(stat.st_ino)
total_size += stat.st_size
return total_size # size in bytes
Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.
But you may not know that inside Sql Engine, it is also parse in the sequence of 'From->Where->Select', To validate it, you can try a simple script
select id as i from table where i=3
and it will not work, the reason is engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try
select * from (select id as i from table) as t where i = 3
One can also use the command line utilities included in poppler-utils
package:
sudo apt-get install poppler-utils
pdftoppm --help
pdftocairo --help
Example:
pdftocairo -png mypage.pdf mypage.png
Your jQuery code works perfectly. The hidden field is being updated.
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
There is cppcheck which is supported also by Hudson via the plugin of the same name.
OP, YOU ARE CORRECT. The else after try/except in Python is ugly. it leads to another flow-control object where none is needed:
try:
x = blah()
except:
print "failed at blah()"
else:
print "just succeeded with blah"
A totally clear equivalent is:
try:
x = blah()
print "just succeeded with blah"
except:
print "failed at blah()"
This is far clearer than an else clause. The else after try/except is not frequently written, so it takes a moment to figure what the implications are.
Just because you CAN do a thing, doesn't mean you SHOULD do a thing.
Lots of features have been added to languages because someone thought it might come in handy. Trouble is, the more features, the less clear and obvious things are because people don't usually use those bells and whistles.
Just my 5 cents here. I have to come along behind and clean up a lot of code written by 1st-year out of college developers who think they're smart and want to write code in some uber-tight, uber-efficient way when that just makes it a mess to try and read / modify later. I vote for readability every day and twice on Sundays.
Add this code before the HttpsURLConnection
and it will be done. I got it.
private void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
}
I hope this helps you.
You could use the short form like below if you want to add all props to state and retain the same names.
constructor(props) {
super(props);
this.state = {
...props
}
//...
}
You should follow the instructions provided in the documentation, using the web.config
.
<aspNetCore processPath="dotnet"
arguments=".\MyApp.dll"
stdoutLogEnabled="false"
stdoutLogFile="\\?\%home%\LogFiles\aspnetcore-stdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
<environmentVariable name="CONFIG_DIR" value="f:\application_config" />
</environmentVariables>
</aspNetCore>
Note that you can also set other environment variables as well.
The ASP.NET Core Module allows you specify environment variables for the process specified in the processPath attribute by specifying them in one or more environmentVariable child elements of an environmentVariables collection element under the aspNetCore element. Environment variables set in this section take precedence over system environment variables for the process.
You can use the linux bash core utility split
split -b 1M -d file.txt file
Note that M
or MB
both are OK but size is different. MB is 1000 * 1000, M is 1024^2
If you want to separate by lines you can use -l
parameter.
UPDATE
a=(`wc -l yourfile`) ; lines=`echo $(($a/12)) | bc -l` ; split -l $lines -d file.txt file
Another solution as suggested by Kirill, you can do something like the following
split -n l/12 file.txt
Note that is l
not one
, split -n
has a few options, like N
, k/N
, l/k/N
, r/N
, r/k/N
.
The pure tr
solutions can only replace with a single character, and the pure sed
solutions don't replace the last newline of the input. The following solution fixes these problems, and seems to be safe for binary data (even with a UTF-8 locale):
printf '1\n2\n3\n' |
sed 's/%/%p/g;s/@/%a/g' | tr '\n' @ | sed 's/@/<br>/g;s/%a/@/g;s/%p/%/g'
Result:
1<br>2<br>3<br>
It can be done like this
(function(X, Y) {_x000D_
_x000D_
// X is the local name of the 'class'_x000D_
// Doo is default value if param X is empty_x000D_
var X = (typeof X == 'string') ? X: 'Doo';_x000D_
var Y = (typeof Y == 'string') ? Y: 'doo';_x000D_
_x000D_
// this refers to the local X defined above_x000D_
this[X] = function(doo) {_x000D_
// object variable_x000D_
this.doo = doo || 'doo it';_x000D_
}_x000D_
// prototypal inheritance for methods_x000D_
// defined by another_x000D_
this[X].prototype[Y] = function() {_x000D_
return this.doo || 'doo';_x000D_
};_x000D_
_x000D_
// make X global_x000D_
window[X] = this[X];_x000D_
}('Dooa', 'dooa')); // give the names here_x000D_
_x000D_
// test_x000D_
doo = new Dooa('abc');_x000D_
doo2 = new Dooa('def');_x000D_
console.log(doo.dooa());_x000D_
console.log(doo2.dooa());
_x000D_
Ecu, if you do myObj.a
, then it looks for the property named a of myObj.
If you do myObj[a] =b
then it looks for the a.valueOf()
property of myObj.
Container splitR(const std::string& input, const std::string& delims) {
Container out;
size_t delims_len = delims.size();
auto begIdx = 0;
auto endIdx = input.find(delims, begIdx);
if (endIdx == std::string::npos && input.size() != 0) {
insert_in_container(out, input);
}
while (endIdx != std::string::npos) {
insert_in_container(out, input.substr(begIdx, endIdx - begIdx));
begIdx = endIdx + delims_len;
endIdx = input.find(delims, begIdx);
if (endIdx == std::string::npos) {
insert_in_container(out, input.substr(begIdx, input.length() - begIdx));
}
}
return out;
}
If the types can be directly cast this is the cleanest way to do it:
var target = yourList.ConvertAll(x => (TargetType)x);
If the types can't be directly cast then you can map the properties from the orginal type to the target type.
var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });
If you using JavaScript to test your Regex, try \\.
instead of \.
.
It acts on the same way because JS remove first backslash.
This is due to the series df[cat]
containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna
operation.
In other words
pandas data type 'Object' indicates mixed types rather than str type
so using the following line:
df[cat] = le.fit_transform(df[cat].astype(str))
should help
I had the same issue in Win7 regarding running a script (.bat) at startup (When the computer boots vs when someone logs in) that would modify the network parameters using netsh. What ended up working for me was the following:
Click on “Create New Task” on the right hand side of the screen and set the parameters as follows:
a. Set the user account to SYSTEM
b. Choose "Run with highest privileges"
c. Choose the OS for Windows7
No, it's not possible in java.
You can do this way .. But try to avoid it.
String one, two, three;
one = two = three = "";
Placeholdr is a super-lightweight drop-in placeholder jQuery polyfill that I wrote. It's less than 1 KB minified.
I made sure that this library addresses both of your concerns:
Placeholdr extends the jQuery $.fn.val() function to prevent unexpected return values when text is present in input fields as a result of Placeholdr. So if you stick with the jQuery API for accessing your fields' values, you won't need to change a thing.
Placeholdr listens for form submits, and it removes the placeholder text from fields so that the server simply sees an empty value.
Again, my goal with Placeholdr is to provide a simple drop-in solution to the placeholder issue. Let me know on Github if there's anything else you'd be interested in having Placeholdr support.
I want to add one more answer :
It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.
there is difference between parameter and argument
you can read in detail about here Arguments and Parameter in python
def hello(a,b=1, *args):
print(a, b, *args)
hello(1, 2, 3, 4,a=12)
since we have three parameters :
a is positional parameter
b=1 is keyword and default parameter
*args is variable length parameter
so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :
one is positional value: a=1
second is keyworded value which is a=12
We have to change hello(1, 2, 3, 4,a=12)
to hello(1, 2, 3, 4,12)
so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)
if we want that *args should get 2,3,4 and a should get 1 and b should get 12
then we can do like this
def hello(a,*args,b=1):
pass
hello(1, 2, 3, 4,b=12)
Something more :
def hello(a,*c,b=1,**kwargs):
print(b)
print(c)
print(a)
print(kwargs)
hello(1,2,1,2,8,9,c=12)
output :
1
(2, 1, 2, 8, 9)
1
{'c': 12}
Hint - with a saving file:
$pdf->Output('sandbox/pdf/example.pdf', 'F');
From angular 7 on-wards the following two commands are working
ng --version
ng version
You could increase the width of the box and move the arrow closer to the left of the arrow. this then allows you to cover the arrow with an empty white div.
Have a look: http://jsbin.com/aniyu4/86/edit
This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:
First, create a duplicate column with a temporary name:
alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;
Next, get the name of your primary key constraint:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';
Now try drop the primary key constraint for your column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..
Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:
ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id)
commit;
Finally, add the FK constraints back in:
alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..
El Fin!
I know its about a year late, but you can also create a 9 path image There's a tool that comes with android SDK which helps in creating such image See this link: http://developer.android.com/tools/help/draw9patch.html
PS: the image can be infinitely scaled as well
Another alternative using library(purrr)
(that seems to be a bit quicker on large data.frames)
flatten(by_row(xy.df, ..f = function(x) flatten_chr(x), .labels = FALSE))
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by
method accepts multiple arguments, you could easily chain them:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):
>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name
:
>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
...
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)
And now the combined order_by
call:
>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
As you can see it is the same result as the first one, meaning it doesn't work as you would expect.
If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.
create schema tableName authorization dbo
go
IF OBJECT_ID ('tableName.put_fieldValue', 'P' ) IS NOT NULL
drop proc tableName.put_fieldValue
go
create proc tableName.put_fieldValue(@fieldValue int) as
declare @tableid int = 0
select @tableid = tableid from table where fieldValue=''
if @tableid = 0 begin
insert into table(fieldValue) values('')
select @tableid = scope_identity()
end
return @tableid
go
declare @tablid int = 0
exec @tableid = tableName.put_fieldValue('')
You can increase the limit from php.ini file. If you are using windows, you will the get php.ini file from C:\xampp\php directory.
Now changes the following lines & set your limit
post_max_size = 128M
upload_max_filesize = 128M
max_execution_time = 2000
max_input_time = 3000
memory_limit = 256M
AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.
This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.
myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)
Output
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Both #2s in your lists are being deprecated. You can still use find(params[:id])
though.
Generally, where()
works in most situations.
Here's a great post: https://web.archive.org/web/20150206131559/http://m.onkey.org/active-record-query-interface
$(selector).filter(function(){return this.value==yourval}).remove();
A somewhat different approach using ggplot2:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
library(reshape2)
dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value, fill = row)) +
geom_bar(stat = "identity") +
xlab("\nType") +
ylab("Time\n") +
guides(fill = FALSE) +
theme_bw()
this gives:
When you want to include a legend, delete the guides(fill = FALSE)
line.
I had the same problem with me yesterday and my solution is: 1. uninstall from controlpanel not from your cli 2. download and install the latest or desired version of node from its website 3. if by mistake you tried uninstalling through cli (it will not remove completely most often) then you do not get uninstall option in cpanel in this case install the same version of node and then follow my 1. step
Hope it helps someone.
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
I cobbled together this solution by scouring the Internet including
This solution seems to work in all browsers including IE6+, using scale(-1,1)
(a proper mirror) and appropriate filter
/-ms-filter
properties when necessary (IE6-8):
/* Cross-browser mirroring of content. Note that CSS pre-processors
like Less cough on the media hack.
Microsoft recommends using BasicImage as a more efficent/faster form of
mirroring, instead of FlipH or some kind of Matrix scaling/transform.
@see http://msdn.microsoft.com/en-us/library/ms532972%28v=vs.85%29.aspx
@see http://msdn.microsoft.com/en-us/library/ms532992%28v=vs.85%29.aspx
*/
/* IE8 only via hack: necessary because IE9+ will also interpret -ms-filter,
and mirroring something that's already mirrored results in no net change! */
@media \0screen {
.mirror {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(mirror=1)";
}
}
.mirror {
/* IE6 and 7 via hack */
*filter: progid:DXImageTransform.Microsoft.BasicImage(mirror=1);
/* Standards browsers, including IE9+ */
-moz-transform: scale(-1,1);
-ms-transform: scale(-1,1);
-o-transform: scale(-1,1); /* Op 11.5 only */
-webkit-transform: scale(-1,1);
transform: scale(-1,1);
}
Simplest Solution With Simple Date Format: SimpleDateFormat("ZZZZZ"):
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("ZZZZZ",Locale.getDefault());
String localTime = date.format(currentLocalTime);
System.out.println(localTime+ " TimeZone " );
==> Output is : +05:30
For people, who are searching for a easier solution.
Add the UITextField
inside a UIView
. To simulate an inset around text field I keep 10 px left and width is 20px less than the view. For a rounded corner border around the textfield, use the view's border
viewBG.layer.cornerRadius = 8.0;
viewBG.layer.borderColor = [UIColor darkGrayColor].CGColor;
viewBG.layer.borderWidth = 1.0;
#First Example:
from datetime import datetime, timezone
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)
Output: 1572878043380
#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)
Output: 1572878043
If you don't want it to add it to a link, you can just enclose it within a span and that would work.
<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>
in your css, then you can:
#clickableAwesomeFont {
cursor: pointer
}
Then in java script, you can just add a click handler.
In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.
if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:
<c:out value="${map['key']}"/>
where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
Gradle's local repository folder is:
Defined dependencies will be loaded from remote repositories into gradle's local repository folder. For each loaded file, gradle will be create a new folder named with md5 value of the original file (pom,jar,..). Full path for the dependency file is made up from :
If our defined dependency is:
Then the library will be loaded into :
wordpress users add line:
@ini_set('memory_limit', '-1');
in wp-settings.php which you can find in the wordpress installed root folder
I'm assuming I can answer my own question.... This worked for me.
Out of curiousity I compared the structure of the old .gradle and the new one... they were pretty different !
So I'll see how 0.4.2 goes :)
You need $route defined in your module and change the JS to this.
$scope.backLinkClick = function () {
window.location.reload();
};
that works fine for me.
$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
This is what I did in order to handle both key entry and copy/paste.
Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox.TextChanged
Dim digitsOnly As Regex = New Regex("[^\d]")
TextBox.Text = digitsOnly.Replace(TextBox.Text, "")
End Sub
If you want to allow decimals and negative amount, add
AndAlso Not e.KeyChar = "." AndAlso Not e.keyChar = "-"
to the if statement in the KeyPress section.
Use the below code
Character.isLetterOrDigit(string.charAt(index))
public class Matrix
{
public static void main(String[] args)
{
double Matrix [] []={
{0*1,0*2,0*3,0*4),
{0*1,1*1,2*1,3*1),
{0*2,1*2,2*2,3*2),
{0*3,1*3,2*3,3*3)
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
System.out.print(Matrix [i] [j] + " ");
System.out.println();
}
}
}
Is the tblPersoon
implementing IEnumerable<T>
? You may need to do it using:
var query = (from p in tblPersoon.Cast<Person>() select p).Single();
This kind of error (Could not find an implementation of the query pattern) usually occurs when:
using System.Linq
)IEnumerable<T>
Edit:
Apart from fact you query type (tblPersoon
) instead of property tblPersoons
, you also need an context instance (class that defines tblPersoons
property), like this:
public tblPersoon GetPersoonByID(string id)
{
var context = new DataClasses1DataContext();
var query = context.tblPersoons.Where(p => p.id == id).Single();
// ...
Build a list from the columns and remove the column you don't want to calculate the Z score for:
In [66]:
cols = list(df.columns)
cols.remove('ID')
df[cols]
Out[66]:
Age BMI Risk Factor
0 6 48 19.3 4
1 8 43 20.9 NaN
2 2 39 18.1 3
3 9 41 19.5 NaN
In [68]:
# now iterate over the remaining columns and create a new zscore column
for col in cols:
col_zscore = col + '_zscore'
df[col_zscore] = (df[col] - df[col].mean())/df[col].std(ddof=0)
df
Out[68]:
ID Age BMI Risk Factor Age_zscore BMI_zscore Risk_zscore \
0 PT 6 48 19.3 4 -0.093250 1.569614 -0.150946
1 PT 8 43 20.9 NaN 0.652753 0.074744 1.459148
2 PT 2 39 18.1 3 -1.585258 -1.121153 -1.358517
3 PT 9 41 19.5 NaN 1.025755 -0.523205 0.050315
Factor_zscore
0 1
1 NaN
2 -1
3 NaN
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
In mathematics, I think the dot in numpy makes more sense
dot(a,b)_{i,j,k,a,b,c} =
since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices
As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as
So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get
matmul(a,b)_{i,j,k,l} =
for example.
From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)
To use dot(a,b) you need
To use matmul(a,b) you need
Use the following piece of code to convince yourself.
import numpy as np
for it in xrange(10000):
a = np.random.rand(5,6,2,4)
b = np.random.rand(6,4,3)
c = np.matmul(a,b)
d = np.dot(a,b)
#print 'c shape: ', c.shape,'d shape:', d.shape
for i in range(5):
for j in range(6):
for k in range(2):
for l in range(3):
if not c[i,j,k,l] == d[i,j,k,j,l]:
print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them
For me the answer to this was available here on StackOverflow:
Unfortunately, this change can cause problems for users who have previously trusted the Fiddler root certificate; the browser may show an error message like NET::ERR_CERT_AUTHORITY_INVALID or The certificate was not issued by a trusted certificate authority.
(Quote from the original source)
I had this ERR_CERT_AUTHORITY_INVALID error on the browser and ERR_INSECURE_RESPONSE shown in Developer Tools of Chrome.
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
This will give you duplicate rows:
vocabulary[duplicated(vocabulary$id),]
This will give you the number of duplicates:
dim(vocabulary[duplicated(vocabulary$id),])[1]
Example:
vocabulary2 <-rbind(vocabulary,vocabulary[1,]) #creates a duplicate at the end
vocabulary2[duplicated(vocabulary2$id),]
# id year sex education vocabulary
#21639 20040001 2004 Female 9 3
dim(vocabulary2[duplicated(vocabulary2$id),])[1]
#[1] 1 #=1 duplicate
OK, with the additional information, here's what you should do: duplicated
has a fromLast
option which allows you to get duplicates from the end. If you combine this with the normal duplicated
, you get all duplicates. The following example adds duplicates to the original vocabulary object (line 1 is duplicated twice and line 5 is duplicated once). I then use table
to get the total number of duplicates per ID.
#Create vocabulary object with duplicates
voc.dups <-rbind(vocabulary,vocabulary[1,],vocabulary[1,],vocabulary[5,])
#List duplicates
dups <-voc.dups[duplicated(voc.dups$id)|duplicated(voc.dups$id, fromLast=TRUE),]
dups
# id year sex education vocabulary
#1 20040001 2004 Female 9 3
#5 20040008 2004 Male 14 1
#21639 20040001 2004 Female 9 3
#21640 20040001 2004 Female 9 3
#51000 20040008 2004 Male 14 1
#Count duplicates by id
table(dups$id)
#20040001 20040008
# 3 2
Bootstrap 4.0
*:focus
{
box-shadow: none !important;
border: solid 1px red( any color ) !important;
}
Use >
and <
for 'greater-than' and 'less-than' respectively
Yeah, your current solution is prone to SQL injection attacks.
The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use this one from my blog) and then join that to your table. Something like:
SELECT d.[Name]
FROM Department d
JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
I simply wanted to remove packages installed by the project, and not other packages I've installed (things like neovim
, mypy
and pudb
which I use for local dev but are not included in the app requirements). So I did:
cat requirements.txt| sed 's/=.*//g' | xargs pip uninstall -y
which worked well for me.
/**
* Method that checks if all tables exist
* If a table doesnt exist it creates the table
*/
public void checkTables() {
try {
startConn();// method that connects with mysql database
String useDatabase = "USE " + getDatabase() + ";";
stmt.executeUpdate(useDatabase);
String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
DatabaseMetaData metadata = conn.getMetaData();
for(int i=0; i< tables.length; i++) {
ResultSet rs = metadata.getTables(null, null, tables[i], null);
if(!rs.next()) {
createTable(tables[i]);
System.out.println("Table " + tables[i] + " created");
}
}
} catch(SQLException e) {
System.out.println("checkTables() " + e.getMessage());
}
closeConn();// Close connection with mysql database
}
The easiest to solve this, without reverting to an older gradle version is to add the '-t' option in the run configurations (for pm install).
testOnly='false' had no effect whatsoever. The error is caused by the alpha version of gradle plugin that makes debug APK 'for test only purposes'. The -t option allows such APK to be installed. Setting it in run configuration makes it automatically install you APK as usual.
this should be close!
public static void OpenWithDefaultProgram(string path)
{
Process fileopener = new Process();
fileopener.StartInfo.FileName = "explorer";
fileopener.StartInfo.Arguments = "\"" + path + "\"";
fileopener.Start();
}
I had the same issue, I did the following to fix the problem.
gen - automated code in project (from dependencies and references)
src - source code in project
There was no need to restart the Eclipse. It just started working.
Honestly I have never tried "Android Tools > Fix Project Properties", sometimes it might be doing the same thing. I do not know, I just did above after seen the error message, thinking something is wrong with the build paths.
Edit
Later on it was not sufficient, I was getting the error again. Then I "checked" all the dependencies listed in that view. Now it works again. So far so good. I will keep this updated if it fails again.
FYI: in my last attempt, I tried "Android Tools > Fix Project Properties", but it didn't work out for me.
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
After a detailed investigation, this issue seems to happen every time after Mac OS X is rebooted (or the Docker virtual machine is restarted) which prevents the Docker client from connecting to the Docker daemon.
To solve the issue, you can either:
A) Reinstall Docker Toolbox using the official installer (https://www.docker.com/products/docker-toolbox), or simply
B) Run the following commands in order:
# First make sure that the virtual machine is running
docker-machine start default
# Regenerate TLS connection certs, requires confirmation
docker-machine regenerate-certs default
# Finally, set env
eval "$(docker-machine env default)"
C) Same as (B), you can also copy and paste the following line to run all of the three commands:
docker-machine start default; docker-machine regenerate-certs default; eval "$(docker-machine env default)"
In case you get the following error:
Error getting SSH command: Something went wrong running an SSH command!
command : cat /etc/os-release
err : exit status 255
output :
just re-run the three commands another time, and it should work the second time.
There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.
Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:
public class A {
public static String VALUE = "Aaa";
}
public class B extends A {
public static String VALUE = "Bbb";
}
Direct access to the static variable:
A.VALUE (="Aaa")
B.VALUE (="Bbb")
Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):
new B().VALUE (="Bbb")
So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.
Now to the point where it gets tricky: Interfaces can also have static variables.
public interface C {
public static String VALUE = "Ccc";
}
public interface D {
public static String VALUE = "Ddd";
}
Let's remove the static variable from B, and observe following situations:
B implements C, D
B extends A implements C
B extends A implements C, D
B extends A implements C
where A implements D
B extends A implements C
where C extends D
The statement new B().VALUE
is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:
error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match
And that's exactly the reason why static variables should be accessed in a static way.
Here is the simplest and the easiest way to find the position of the clicked item:
I've also faced the same problem.
I wanted to find of the position of the clicked/selected item of the RecyclerView() and perform some specific operations on that particular item.
getAdapterPosition() method works like a charm for these kind of stuff. I found this method after a day of long research and after trying numerous other methods.
int position = getAdapterPosition();
Toast.makeText(this, "Position is: "+position, Toast.LENGTH_SHORT).show();
You do not have to use any extra method. Just create a global variable named 'position' and initialize it with getAdapterPosition() in any of the major method of the adapter (class or similar).
Here is a brief documentation from this link.
getAdapterPosition added in version 22.1.0 int getAdapterPosition () Returns the Adapter position of the item represented by this ViewHolder. Note that this might be different than the getLayoutPosition() if there are pending adapter updates but a new layout pass has not happened yet. RecyclerView does not handle any adapter updates until the next layout traversal. This may create temporary inconsistencies between what user sees on the screen and what adapter contents have. This inconsistency is not important since it will be less than 16ms but it might be a problem if you want to use ViewHolder position to access the adapter. Sometimes, you may need to get the exact adapter position to do some actions in response to user events. In that case, you should use this method which will calculate the Adapter position of the ViewHolder.
Happy to help. Feel free to ask doubts.
Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE)
from the place where you show the dialog, and then when your dialog is finished, from it you can call getTargetFragment().onActivityResult(getTargetRequestCode(), ...)
, and implement onActivityResult()
in the containing fragment.
It seems like an abuse of onActivityResult()
, especially as it doesn't involve activities at all. But I've seen it recommended by official google people, and maybe even in the api demos. I think it's what g/setTargetFragment()
were added for.
public myClass{
private Stage dialogStage;
public void msgBox(String title){
dialogStage = new Stage();
GridPane grd_pan = new GridPane();
grd_pan.setAlignment(Pos.CENTER);
grd_pan.setHgap(10);
grd_pan.setVgap(10);//pading
Scene scene =new Scene(grd_pan,300,150);
dialogStage.setScene(scene);
dialogStage.setTitle("alert");
dialogStage.initModality(Modality.WINDOW_MODAL);
Label lab_alert= new Label(title);
grd_pan.add(lab_alert, 0, 1);
Button btn_ok = new Button("fermer");
btn_ok.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
// TODO Auto-generated method stub
dialogStage.hide();
}
});
grd_pan.add(btn_ok, 0, 2);
dialogStage.show();
}
}
I have written a sort of "idiots guide" to the Y-Combinator in both Clojure and Scheme in order to help myself come to grips with it. They are influenced by material in "The Little Schemer"
In Scheme: https://gist.github.com/z5h/238891
or Clojure: https://gist.github.com/z5h/5102747
Both tutorials are code interspersed with comments and should be cut & pastable into your favourite editor.
compile function -
syntax
function compile(tElement, tAttrs, transclude) { ... }
controller
pre - link
The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.
You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function
Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called
post-link
directive that only has link function, angular treats the function as a post link
post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic
Error : error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Executing sudo apt-get install python-dev
solved the error.
Since JavaScript is a scripting language, I feel that its introspection should support getting function parameter names. Punting on that functionality is a violation of first principles, so I decided to explore the issue further.
That led me to this question but no built-in solutions. Which led me to this answer which explains that arguments
is only deprecated outside the function, so we can no longer use myFunction.arguments
or we get:
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
Time to roll up our sleeves and get to work:
? Retrieving function parameters requires a parser because complex expressions like 4*(5/3)
can be used as default values. So Gaafar's answer or James Drew's answer are so far the best approaches.
I tried the babylon and esprima parsers but unfortunately they can't parse standalone anonymous functions, as pointed out in Mateusz Charytoniuk's answer. I figured out another workaround though by surrounding the code in parentheses, so as not to change the logic:
const ast = parser.parse("(\n" + func.toString() + "\n)")
The newlines prevent issues with //
(single-line comments).
? If a parser is not available, the next-best option is to use a tried-and-true technique like Angular.js's dependency injector regular expressions. I combined a functional version of Lambder's answer with humbletim's answer and added an optional ARROW
boolean for controlling whether ES6 fat arrow functions are allowed by the regular expressions.
Here are two solutions I put together. Note that these have no logic to detect whether a function has valid syntax, they only extract the arguments. This is generally ok since we usually pass parsed functions to getArguments()
so their syntax is already valid.
I will try to curate these solutions as best I can, but without effort from the JavaScript maintainers, this will remain an open problem.
Node.js version (not runnable until StackOverflow supports Node.js):
const parserName = 'babylon';_x000D_
// const parserName = 'esprima';_x000D_
const parser = require(parserName);_x000D_
_x000D_
function getArguments(func) {_x000D_
const maybe = function (x) {_x000D_
return x || {}; // optionals support_x000D_
}_x000D_
_x000D_
try {_x000D_
const ast = parser.parse("(\n" + func.toString() + "\n)");_x000D_
const program = parserName == 'babylon' ? ast.program : ast;_x000D_
_x000D_
return program_x000D_
.body[0]_x000D_
.expression_x000D_
.params_x000D_
.map(function(node) {_x000D_
return node.name || maybe(node.left).name || '...' + maybe(node.argument).name;_x000D_
});_x000D_
} catch (e) {_x000D_
return []; // could also return null_x000D_
}_x000D_
};_x000D_
_x000D_
////////// TESTS //////////_x000D_
_x000D_
function logArgs(func) {_x000D_
let object = {};_x000D_
_x000D_
object[func] = getArguments(func);_x000D_
_x000D_
console.log(object);_x000D_
// console.log(/*JSON.stringify(*/getArguments(func)/*)*/);_x000D_
}_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// MISC //////////');_x000D_
_x000D_
logArgs((a, b) => {});_x000D_
logArgs((a, b = 1) => {});_x000D_
logArgs((a, b, ...args) => {});_x000D_
logArgs(function(a, b, ...args) {});_x000D_
logArgs(function(a, b = 1, c = 4 * (5 / 3), d = 2) {});_x000D_
logArgs(async function(a, b, ...args) {});_x000D_
logArgs(function async(a, b, ...args) {});_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// FUNCTIONS //////////');_x000D_
_x000D_
logArgs(function(a, b, c) {});_x000D_
logArgs(function() {});_x000D_
logArgs(function named(a, b, c) {});_x000D_
logArgs(function(a /* = 1 */, b /* = true */) {});_x000D_
logArgs(function fprintf(handle, fmt /*, ...*/) {});_x000D_
logArgs(function(a, b = 1, c) {});_x000D_
logArgs(function(a = 4 * (5 / 3), b) {});_x000D_
// logArgs(function (a, // single-line comment xjunk) {});_x000D_
// logArgs(function (a /* fooled you {});_x000D_
// logArgs(function (a /* function() yes */, \n /* no, */b)/* omg! */ {});_x000D_
// logArgs(function ( A, b \n,c ,d \n ) \n {});_x000D_
logArgs(function(a, b) {});_x000D_
logArgs(function $args(func) {});_x000D_
logArgs(null);_x000D_
logArgs(function Object() {});_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// STRINGS //////////');_x000D_
_x000D_
logArgs('function (a,b,c) {}');_x000D_
logArgs('function () {}');_x000D_
logArgs('function named(a, b, c) {}');_x000D_
logArgs('function (a /* = 1 */, b /* = true */) {}');_x000D_
logArgs('function fprintf(handle, fmt /*, ...*/) {}');_x000D_
logArgs('function( a, b = 1, c ) {}');_x000D_
logArgs('function (a=4*(5/3), b) {}');_x000D_
logArgs('function (a, // single-line comment xjunk) {}');_x000D_
logArgs('function (a /* fooled you {}');_x000D_
logArgs('function (a /* function() yes */, \n /* no, */b)/* omg! */ {}');_x000D_
logArgs('function ( A, b \n,c ,d \n ) \n {}');_x000D_
logArgs('function (a,b) {}');_x000D_
logArgs('function $args(func) {}');_x000D_
logArgs('null');_x000D_
logArgs('function Object() {}');
_x000D_
Full working example:
https://repl.it/repls/SandybrownPhonyAngles
Browser version (note that it stops at the first complex default value):
function getArguments(func) {_x000D_
const ARROW = true;_x000D_
const FUNC_ARGS = ARROW ? /^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m : /^(function)\s*[^\(]*\(\s*([^\)]*)\)/m;_x000D_
const FUNC_ARG_SPLIT = /,/;_x000D_
const FUNC_ARG = /^\s*(_?)(.+?)\1\s*$/;_x000D_
const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;_x000D_
_x000D_
return ((func || '').toString().replace(STRIP_COMMENTS, '').match(FUNC_ARGS) || ['', '', ''])[2]_x000D_
.split(FUNC_ARG_SPLIT)_x000D_
.map(function(arg) {_x000D_
return arg.replace(FUNC_ARG, function(all, underscore, name) {_x000D_
return name.split('=')[0].trim();_x000D_
});_x000D_
})_x000D_
.filter(String);_x000D_
}_x000D_
_x000D_
////////// TESTS //////////_x000D_
_x000D_
function logArgs(func) {_x000D_
let object = {};_x000D_
_x000D_
object[func] = getArguments(func);_x000D_
_x000D_
console.log(object);_x000D_
// console.log(/*JSON.stringify(*/getArguments(func)/*)*/);_x000D_
}_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// MISC //////////');_x000D_
_x000D_
logArgs((a, b) => {});_x000D_
logArgs((a, b = 1) => {});_x000D_
logArgs((a, b, ...args) => {});_x000D_
logArgs(function(a, b, ...args) {});_x000D_
logArgs(function(a, b = 1, c = 4 * (5 / 3), d = 2) {});_x000D_
logArgs(async function(a, b, ...args) {});_x000D_
logArgs(function async(a, b, ...args) {});_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// FUNCTIONS //////////');_x000D_
_x000D_
logArgs(function(a, b, c) {});_x000D_
logArgs(function() {});_x000D_
logArgs(function named(a, b, c) {});_x000D_
logArgs(function(a /* = 1 */, b /* = true */) {});_x000D_
logArgs(function fprintf(handle, fmt /*, ...*/) {});_x000D_
logArgs(function(a, b = 1, c) {});_x000D_
logArgs(function(a = 4 * (5 / 3), b) {});_x000D_
// logArgs(function (a, // single-line comment xjunk) {});_x000D_
// logArgs(function (a /* fooled you {});_x000D_
// logArgs(function (a /* function() yes */, \n /* no, */b)/* omg! */ {});_x000D_
// logArgs(function ( A, b \n,c ,d \n ) \n {});_x000D_
logArgs(function(a, b) {});_x000D_
logArgs(function $args(func) {});_x000D_
logArgs(null);_x000D_
logArgs(function Object() {});_x000D_
_x000D_
console.log('');_x000D_
console.log('////////// STRINGS //////////');_x000D_
_x000D_
logArgs('function (a,b,c) {}');_x000D_
logArgs('function () {}');_x000D_
logArgs('function named(a, b, c) {}');_x000D_
logArgs('function (a /* = 1 */, b /* = true */) {}');_x000D_
logArgs('function fprintf(handle, fmt /*, ...*/) {}');_x000D_
logArgs('function( a, b = 1, c ) {}');_x000D_
logArgs('function (a=4*(5/3), b) {}');_x000D_
logArgs('function (a, // single-line comment xjunk) {}');_x000D_
logArgs('function (a /* fooled you {}');_x000D_
logArgs('function (a /* function() yes */, \n /* no, */b)/* omg! */ {}');_x000D_
logArgs('function ( A, b \n,c ,d \n ) \n {}');_x000D_
logArgs('function (a,b) {}');_x000D_
logArgs('function $args(func) {}');_x000D_
logArgs('null');_x000D_
logArgs('function Object() {}');
_x000D_
Full working example:
I had the same problem and spent about 6 hours to solve it. I didn't find that answer for exactly my situation so maybe it could be useful for somebody.
When I created project, I pointed GroupId in pom.xml as "myproject.myapp" but I didn't create first "prime" package with that name in the project, where would be other packages inside of this main package (like /src/main/app etc). When I created prime package "myproject.myapp" and moved other packages inside of it, the problem was solved.
Remove or show the title using:
getActionBar().setDisplayShowTitleEnabled(true);
Remove or show the logo using:
getActionBar().setDisplayUseLogoEnabled(false);
Remove all:
getActionBar().setDisplayShowHomeEnabled(false);
template <typename T>
const T to(const string& sval)
{
T val;
stringstream ss;
ss << sval;
ss >> val;
if(ss.fail())
throw runtime_error((string)typeid(T).name() + " type wanted: " + sval);
return val;
}
And then you can use it like that:
double d = to<double>("4.3");
or
int i = to<int>("4123");
First, create a empty DataFrame with column names, after that, inside the for loop, you must define a dictionary (a row) with the data to append:
df = pd.DataFrame(columns=['A'])
for i in range(5):
df = df.append({'A': i}, ignore_index=True)
df
A
0 0
1 1
2 2
3 3
4 4
If you want to add a row with more columns, the code will looks like this:
df = pd.DataFrame(columns=['A','B','C'])
for i in range(5):
df = df.append({'A': i,
'B': i * 2,
'C': i * 3,
}
,ignore_index=True
)
df
A B C
0 0 0 0
1 1 2 3
2 2 4 6
3 3 6 9
4 4 8 12
I recommend creating a .json file (ex: config.json). Then paste all of your json object and format it. And thus you will be able to remove all of that things that is breaking your json-object, and get clean copy-paste json-object.
An open source GUI tool is available at keystore-explorer.org
KeyStore Explorer
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Following screens will help (they are from the official site)
Default screen that you get by running the command:
shantha@shantha:~$./Downloads/kse-521/kse.sh
And go to Examine
and Examine a URL
option and then give the web URL that you want to import.
The result window will be like below if you give google site link.
This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)
You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.
Windows does not have (need?) this.
Run the command with the sudo removed from the start.
The solutions so far cover some cases but miss some (see below). Here's my attempt at a more thorough (safe) conversion. I know of one corner case which this solution doesn't handle which is single character symbols made up of odd, but allowed characters. For example {:> => :<}
is a valid ruby hash.
I put this code up on github as well. This code starts with a test string to exercise all the conversions
require 'json'
# Example ruby hash string which exercises all of the permutations of position and type
# See http://json.org/
ruby_hash_text='{"alpha"=>{"first second > third"=>"first second > third", "after comma > foo"=>:symbolvalue, "another after comma > foo"=>10}, "bravo"=>{:symbol=>:symbolvalue, :aftercomma=>10, :anotheraftercomma=>"first second > third"}, "charlie"=>{1=>10, 2=>"first second > third", 3=>:symbolvalue}, "delta"=>["first second > third", "after comma > foo"], "echo"=>[:symbol, :aftercomma], "foxtrot"=>[1, 2]}'
puts ruby_hash_text
# Transform object string symbols to quoted strings
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')
# Transform object string numbers to quoted strings
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')
# Transform object value symbols to quotes strings
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')
# Transform array value symbols to quotes strings
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')
# Transform object string object value delimiter to colon delimiter
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')
puts ruby_hash_text
puts JSON.parse(ruby_hash_text)
Here are some notes on the other solutions here
eval
which is too scary for me (as Toms rightly points out).The main difference between localStorage
and sessionStorage
is that sessionStorage
is unique per tab. If you close the tab the sessionStorage
gets deleted, localStorage
does not. Also you cannot communicate between tabs :)
Another subtle difference is that for example on Safari (8.0.3) localStorage
has a limit of 2551 k characters but sessionStorage
has unlimited storage
On Chrome (v43) both localStorage
and sessionStorage
are limited to 5101 k characters (no difference between normal / incognito mode)
On Firefox both localStorage
and sessionStorage
are limited to 5120 k characters (no difference between normal / private mode )
No difference in speed whatsoever :)
There's also a problem with Mobile Safari and Mobile Chrome, Private Mode Safari & Chrome have a maximum space of 0KB
If we are trying to replace NA
s when exporting, for example when writing to csv, then we can use:
write.csv(data, "data.csv", na = "0")
There's an even simpler solution - delete the cache folder at user/.android/built-cache and go back to android studio and sync with gradle again, if that still doesn't work delete the cache folder again, and restart android studio and re-import the project
Variables names are only locally meaningful.
Once you hit
return s1,s2,s3,s4
at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.
If you want the variable names to be meaningful after you hit return
in the method, you must create an object or dictionary.
To stop a running program, use Ctrl+C to terminate the process.
To handle it programmatically in python, import the sys
module and use sys.exit()
where you want to terminate the program.
import sys
sys.exit()
Use Excel's AdvancedFilter function to do this.
Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:
Copy values in Column A and insert the unique values in column B:
Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True
It works with multiple columns too:
Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True
Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates
Here I remove duplicate columns based on the third column:
Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo
Here I remove duplicate columns based on the second and third column:
Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo