To prevent flickering when your main command takes perceivable time to complete, you can capture the output and only clear screen when it's done.
function watch {while :; do a=$($@); clear; echo "$(date)\n\n$a"; sleep 1; done}
Then use it by:
watch istats
You can listen resize
event and fire where some dimension change
directive
(function() {
'use strict';
angular
.module('myApp.directives')
.directive('resize', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
function onResize(){
// uncomment for only fire when $window.innerWidth change
// if (scope.width !== $window.innerWidth)
{
scope.width = $window.innerWidth;
scope.$digest();
}
};
function cleanUp() {
angular.element($window).off('resize', onResize);
}
angular.element($window).on('resize', onResize);
scope.$on('$destroy', cleanUp);
}
}]);
})();
In html
<div class="row" resize> ,
<div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod">
<h4 ng-bind="::v.known_as"></h4>
</div>
</div>
Controller :
$scope.$watch('width', function(old, newv){
console.log(old, newv);
})
Facebook's watchman, available via Homebrew, also looks nice. It supports also filtering:
These two lines establish a watch on a source directory and then set up a trigger named "buildme" that will run a tool named "minify-css" whenever a CSS file is changed. The tool will be passed a list of the changed filenames.
$ watchman watch ~/src
$ watchman -- trigger ~/src buildme '*.css' -- minify-css
Notice that the path must be absolute.
This is another modification of Tim Goldan's script that runs on unix types and adds a simple watcher for file modification by using a dict (file=>time).
usage: whateverName.py path_to_dir_to_watch
#!/usr/bin/env python
import os, sys, time
def files_to_timestamp(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
return dict ([(f, os.path.getmtime(f)) for f in files])
if __name__ == "__main__":
path_to_watch = sys.argv[1]
print('Watching {}..'.format(path_to_watch))
before = files_to_timestamp(path_to_watch)
while 1:
time.sleep (2)
after = files_to_timestamp(path_to_watch)
added = [f for f in after.keys() if not f in before.keys()]
removed = [f for f in before.keys() if not f in after.keys()]
modified = []
for f in before.keys():
if not f in removed:
if os.path.getmtime(f) != before.get(f):
modified.append(f)
if added: print('Added: {}'.format(', '.join(added)))
if removed: print('Removed: {}'.format(', '.join(removed)))
if modified: print('Modified: {}'.format(', '.join(modified)))
before = after
Setting the objectEquality
parameter (third parameter) of the $watch
function is definitely the correct way to watch ALL properties of the array.
$scope.$watch('columns', function(newVal) {
alert('columns changed');
},true); // <- Right here
Piran answers this well enough and mentions $watchCollection
as well.
More Detail
The reason I'm answering an already answered question is because I want to point out that wizardwerdna's answer is not a good one and should not be used.
The problem is that the digests do not happen immediately. They have to wait until the current block of code has completed before executing. Thus, watch the length
of an array may actually miss some important changes that $watchCollection
will catch.
Assume this configuration:
$scope.testArray = [
{val:1},
{val:2}
];
$scope.$watch('testArray.length', function(newLength, oldLength) {
console.log('length changed: ', oldLength, ' -> ', newLength);
});
$scope.$watchCollection('testArray', function(newArray) {
console.log('testArray changed');
});
At first glance, it may seem like these would fire at the same time, such as in this case:
function pushToArray() {
$scope.testArray.push({val:3});
}
pushToArray();
// Console output
// length changed: 2 -> 3
// testArray changed
That works well enough, but consider this:
function spliceArray() {
// Starting at index 1, remove 1 item, then push {val: 3}.
$testArray.splice(1, 1, {val: 3});
}
spliceArray();
// Console output
// testArray changed
Notice that the resulting length was the same even though the array has a new element and lost an element, so as watch as the $watch
is concerned, length
hasn't changed. $watchCollection
picked up on it, though.
function pushPopArray() {
$testArray.push({val: 3});
$testArray.pop();
}
pushPopArray();
// Console output
// testArray change
The same result happens with a push and pop in the same block.
Conclusion
To watch every property in the array, use a $watch
on the array iteself with the third parameter (objectEquality) included and set to true. Yes, this is expensive but sometimes necessary.
To watch when object enter/exit the array, use a $watchCollection
.
Do NOT use a $watch
on the length
property of the array. There is almost no good reason I can think of to do so.
You can always use the good old observer pattern if you want to avoid the tyranny and overhead of $watch
.
In the service:
factory('aService', function() {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
//example of when you may want to notify observers
this.foo = someNgResource.query().$then(function(){
notifyObservers();
});
});
And in the controller:
function FooCtrl($scope, aService){
var updateFoo = function(){
$scope.foo = aService.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)
Some time your $watch is calling dynamically
and it will create its instances so you have to call deregistration function before your $watch
function
if(myWatchFun)
myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});
Here is a simple solution. Example calls that could be used in any method:
StopWatch.start();
StopWatch.stop();
StopWatch.displayDiff();
displays difference in minutes and seconds between start and stop. (elapsed time)
import java.time.Duration;
import java.time.Instant;
public class StopWatch {
private static Instant start;
private static Instant stop;
private void StopWatch() {
// not called
}
public static void start() {
start = Instant.now();
}
public static void stop() {
stop = Instant.now();
}
public static void displayDiff() {
Duration totalTime = Duration.between(start, stop);
System.out.println(totalTime.toMinutes() + " Minutes "
+ totalTime.toMillis() / 1000 + " Seconds");
}
}
Try this when your application still demands $parse
, $eval
, $watch
like behavior in Angular
It will work in IE7. But here you need to fixed the size
less than the number of option
and not use overflow-y:scroll
. In your example you have 2 option
but you set size=10
, which will not work.
Suppose your select has 10 option
, then fixed size=9
.
Here, in your code reference you used height:100px
with size:2
. I remove the height
css, because its not necessary and change the size:5
and it works fine.
Here is your modified code from jsfiddle:
<select size="5" style="width:100px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
this will generate a larger select box than size:2
create.In case of small size
the select box will not display the scrollbar,you have to check with appropriate size
quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2
and size
greater than 2
(e.g: 3,5).
Here is your desired result. I think this will help you:
CSS
.wrapper{
border: 1px dashed red;
height: 150px;
overflow-x: hidden;
overflow-y: scroll;
width: 150px;
}
.wrapper .selection{
width:150px;
border:1px solid #ccc
}
HTML
<div class="wrapper">
<select size="15" class="selection">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
For people having a startTime
(like 12h:30:30) and a duration
(value in minutes like 120), you can guess the endTime
like so:
const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))
gives
$`1`
num let LET
3 3 c C
6 6 f F
10 10 j J
12 12 l L
14 14 n N
15 15 o O
17 17 q Q
18 18 r R
20 20 t T
21 21 u U
22 22 v V
23 23 w W
26 26 z Z
$`2`
num let LET
1 1 a A
2 2 b B
4 4 d D
5 5 e E
7 7 g G
8 8 h H
9 9 i I
11 11 k K
13 13 m M
16 16 p P
19 19 s S
24 24 x X
25 25 y Y
You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl
column in mtcars
:
split(mtcars,mtcars$cyl)
I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you
public static String getHtml(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
return result;
}
I too had this problem. My solution was:
sc.setSoLinger(true, 10);
COPY FROM A WEBSITE -->By using the setSoLinger()
method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.
Maybe it is not the answer to everybody but to some people.
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined
. I am passing JSONWebToken
as part of header.
.ajax({
url: 'api/outletadd',
type: 'post',
data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
headers: {
authorization: storedJWT
},
dataType: 'json',
success: function (data){
alert("Outlet Created");
},
error: function (data){
alert("Outlet Creation Failed, please try again.");
}
});
I am not sure if you are trying to create a remote branch from a local branch or vice versa, so I've outlined both scenarios as well as provided information on merging the remote and local branches.
Creating a remote called "github":
git remote add github git://github.com/jdoe/coolapp.git
git fetch github
List all remote branches:
git branch -r
github/gh-pages
github/master
github/next
github/pu
Create a new local branch (test) from a github's remote branch (pu):
git branch test github/pu
git checkout test
Merge changes from github's remote branch (pu) with local branch (test):
git fetch github
git checkout test
git merge github/pu
Update github's remote branch (pu) from a local branch (test):
git push github test:pu
Creating a new branch on a remote uses the same syntax as updating a remote branch. For example, create new remote branch (beta) on github from local branch (test):
git push github test:beta
Delete remote branch (pu) from github:
git push github :pu
If you are using Java 8 Do it as below
import static java.lang.Math.toIntExact;
public class DateFormatSampleCode {
public static void main(String[] args) {
long longValue = 1223321L;
int longTointValue = toIntExact(longValue);
System.out.println(longTointValue);
}
}
Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.
When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:
class A {..}
class B : A {...}
class C : B {...}
C c;
When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.
To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.
Derived() : Base(5)
{
}
If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.
You can always do fdisk -l
which seems to work pretty well, even on strange setups such as EC2 xvda devices.
Here is a dump for a m1.large instance:
root@ip-10-126-247-82:~# fdisk -l
Disk /dev/xvda1: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/xvda1 doesn't contain a valid partition table
Disk /dev/xvda2: 365.0 GB, 365041287168 bytes
255 heads, 63 sectors/track, 44380 cylinders, total 712971264 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/xvda2 doesn't contain a valid partition table
Disk /dev/xvda3: 939 MB, 939524096 bytes
255 heads, 63 sectors/track, 114 cylinders, total 1835008 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/xvda3 doesn't contain a valid partition table
While mount
says:
root@ip-10-126-247-82:~# mount
/dev/xvda1 on / type ext4 (rw)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
fusectl on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
/dev/xvda2 on /mnt type ext3 (rw)
And /proc/partitions
says:
root@ip-10-126-247-82:~# cat /proc/partitions
major minor #blocks name
202 1 10485760 xvda1
202 2 356485632 xvda2
202 3 917504 xvda3
How fdisk -l
works is something I would love to know myself.
When the compiler sees add(3, 4)
it needs to know what that means. With the forward declaration you basically tell the compiler that add
is a function that takes two ints and returns an int. This is important information for the compiler becaus it needs to put 4 and 5 in the correct representation onto the stack and needs to know what type the thing returned by add is.
At that time, the compiler is not worried about the actual implementation of add
, ie where it is (or if there is even one) and if it compiles. That comes into view later, after compiling the source files when the linker is invoked.
Here is my full post with topic: PHP find difference between two datetimes
USAGE EXAMPLE
echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2017-08-30 00:01:59', 'Y-m-d H:i:s', false, '%a days %h hours');
#459 days 22 hours (string)
echo timeDifference('2016-05-27 02:00:00', 'Y-m-d H:i:s', '2016-05-27 07:00:00', 'Y-m-d H:i:s', true, 'hours',true);
#-5 (int)
If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.
class BaseService {
public void validate(){
fail(" I must not be called");
}
public void save(){
//Save method of super will still be called.
validate();
}
}
class ChildService extends BaseService{
public void load(){}
public void save(){
super.save();
load();
}
}
@Test
public void testSave() {
ChildService classToTest = Mockito.spy(new ChildService());
// Prevent/stub logic in super.save()
Mockito.doNothing().when((BaseService)classToTest).validate();
// When
classToTest.save();
// Then
verify(classToTest).load();
}
Here is a tidyverse
option that might work depending on the data, and some caveats on its usage:
library(tidyverse)
starting_df %>%
rownames_to_column() %>%
gather(variable, value, -rowname) %>%
spread(rowname, value)
rownames_to_column()
is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column()
and replace rowname
with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths
sample data would be:
smiths %>%
gather(variable, value, -subject) %>%
spread(subject, value)
Using the example starting_df
with the tidyverse
approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths
data will not give that warning because all columns except for subject
are doubles.
The earlier answer using as.data.frame(t())
will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE
is added,
whereas the tidyverse
option converts everything to a character by default if
there are mixed column types.
I had a problem similar to the one posed in the original question. I was intrigued by the divs styled as table elements (didn't know you could do that!) and gave it a run. However, my solution was to keep my tables wrapped in tags, but rename each input and select option to become the keys of array, which I'm now parsing to get each element in the selected row.
Here's a single row from the table. Note that key [4] is the rendered ID of the row in the database from which this table row was retrieved:
<table>
<tr>
<td>DisabilityCategory</td>
<td><input type="text" name="FormElem[4][ElemLabel]" value="Disabilities"></td>
<td><select name="FormElem[4][Category]">
<option value="1">General</option>
<option value="3">Disability</option>
<option value="4">Injury</option>
<option value="2"selected>School</option>
<option value="5">Veteran</option>
<option value="10">Medical</option>
<option value="9">Supports</option>
<option value="7">Residential</option>
<option value="8">Guardian</option>
<option value="6">Criminal</option>
<option value="11">Contacts</option>
</select></td>
<td>4</td>
<td style="text-align:center;"><input type="text" name="FormElem[4][ElemSeq]" value="0" style="width:2.5em; text-align:center;"></td>
<td>'ccpPartic'</td>
<td><input type="text" name="FormElem[4][ElemType]" value="checkbox"></td>
<td><input type="checkbox" name="FormElem[4][ElemRequired]"></td>
<td><input type="text" name="FormElem[4][ElemLabelPrefix]" value=""></td>
<td><input type="text" name="FormElem[4][ElemLabelPostfix]" value=""></td>
<td><input type="text" name="FormElem[4][ElemLabelPosition]" value="before"></td>
<td><input type="submit" name="submit[4]" value="Commit Changes"></td>
</tr>
</table>
Then, in PHP, I'm using the following method to store in an array ($SelectedElem) each of the elements in the row corresponding to the submit button. I'm using print_r()
just to illustrate:
$SelectedElem = implode(",", array_keys($_POST['submit']));
print_r ($_POST['FormElem'][$SelectedElem]);
Perhaps this sounds convoluted, but it turned out to be quite simple, and it preserved the organizational structure of the table.
Instead of using a split, I think it would be easier to simply execute a match and process all the found matches.
This expression will:
Regex: (?:^|,)(?=[^"]|(")?)"?((?(1)[^"]*|[^,"]*))"?(?=,|$)
Sample Text
123,2.99,AMO024,Title,"Description, more info",,123987564
ASP example using the non-java expression
Set regEx = New RegExp
regEx.Global = True
regEx.IgnoreCase = True
regEx.MultiLine = True
sourcestring = "your source string"
regEx.Pattern = "(?:^|,)(?=[^""]|("")?)""?((?(1)[^""]*|[^,""]*))""?(?=,|$)"
Set Matches = regEx.Execute(sourcestring)
For z = 0 to Matches.Count-1
results = results & "Matches(" & z & ") = " & chr(34) & Server.HTMLEncode(Matches(z)) & chr(34) & chr(13)
For zz = 0 to Matches(z).SubMatches.Count-1
results = results & "Matches(" & z & ").SubMatches(" & zz & ") = " & chr(34) & Server.HTMLEncode(Matches(z).SubMatches(zz)) & chr(34) & chr(13)
next
results=Left(results,Len(results)-1) & chr(13)
next
Response.Write "<pre>" & results
Matches using the non-java expression
Group 0 gets the entire substring which includes the comma
Group 1 gets the quote if it's used
Group 2 gets the value not including the comma
[0][0] = 123
[0][1] =
[0][2] = 123
[1][0] = ,2.99
[1][1] =
[1][2] = 2.99
[2][0] = ,AMO024
[2][1] =
[2][2] = AMO024
[3][0] = ,Title
[3][1] =
[3][2] = Title
[4][0] = ,"Description, more info"
[4][1] = "
[4][2] = Description, more info
[5][0] = ,
[5][1] =
[5][2] =
[6][0] = ,123987564
[6][1] =
[6][2] = 123987564
I had exactly the same issue: was cleaning up my folders, rearranging and moving files. I entered: git rm . and hit enter; and then felt my bowels loosen a bit. Luckily, I didn't type in git commit -m "" straightaway.
However, the following command
git checkout .
restored everything, and saved my life.
There are a number of obvious differences between Git and GitHub.
Git itself is really focused on the essential tasks of version control. It maintains a commit history, it allows you to reverse changes through reset and revert commands, and it allows you to share code with other developers through push and pull commands. I think those are the essential features every developer wants from a DVCS tool.
No Scope Creep with Git
But one thing about Git is that it is really just laser focused on source code control and nothing else. That's awesome, but it also means the tool lacks many features organizations want. For example, there is no built-in user management facilities to authenticate who is connecting and committing code. Integration with things like Jira or Jenkins are left up to developers to figure out through things like hooks. Basically, there are a load of places where features could be integrated. That's where organizations like GitHub and GitLab come in.
Additional GitHub Features
GitHub's primary 'value-add' is that it provides a cloud based platform for Git. That in itself is awesome. On top of that, GitHub also offers:
So GitHub really adds polish and refinement to an already popular DVCS tool.
Git and GitHub competitors
Sometimes when it comes to differentiating between Git and GitHub, I think it's good to look at who they compete against. Git competes on a plane with tools like Mercurial, Subversion and RTC, whereas GitHub is more in the SaaS space competing against cloud vendors such as GitLab and Atlassian's BitBucket.
No GitHub Required
One thing I always like to remind people of is that you don't need GitHub or GitLab or BitBucket to use Git. Git was released in what, 2005? GitHub didn't come on the scene until 2007 or 2008, so big organizations were doing distributed version control with Git long before the cloud hosting vendors came along. So Git is just fine on its own. It doesn't need a cloud hosting service to be effective. But at the same time, having a PaaS provider certainly doesn't hurt.
Working with GitHub Desktop
By the way, you mentioned the mismatch between the repositories in your GitHub account and the repos you have locally? That's understandable. Until you've connected and done a pull or a fetch, the local Git repo doesn't know about the remote GitHub repo. Having said that, GitHub provides a tool known as the GitHub desktop that allows you to connect to GitHub from a desktop client and easily load local Git repos to GitHub, or bring GitHub repos onto your local machine.
I'm not overly impressed by the tool, as once you know Git, these things aren't that hard to do in the Bash shell, but it's an option.
There are a few misunderstandings in the discussion above.
First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.
As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION @transaction
Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)
This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.
As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.
If you are using Java 6 or higher you can use wildcards of this form:
java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:
java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
There is nothing like lib\*\*
or lib\**
wildcard for the kind of job you want to be done.
First copy the source range then paste-special on target range with Transpose:=True, short sample:
Option Explicit
Sub test()
Dim sourceRange As Range
Dim targetRange As Range
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
Set targetRange = ActiveSheet.Cells(6, 1)
sourceRange.Copy
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub
The Transpose function takes parameter of type Varaiant and returns Variant.
Sub transposeTest()
Dim transposedVariant As Variant
Dim sourceRowRange As Range
Dim sourceRowRangeVariant As Variant
Set sourceRowRange = Range("A1:H1") ' one row, eight columns
sourceRowRangeVariant = sourceRowRange.Value
transposedVariant = Application.Transpose(sourceRowRangeVariant)
Dim rangeFilledWithTransposedData As Range
Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
rangeFilledWithTransposedData.Value = transposedVariant
End Sub
I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.
First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.
If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.
Hope i did not confuse u, my english is bad, sorry :-).
First of all you can't make a POST request using JSONP.
What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.
Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.
This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.
The best thing to do is adding &callback=? to you url.
At the server side you've got to make sure that your data is wrapped in this callback function.
ie.
echo $_GET['callback'] . '(' . $data . ')';
EDIT:
Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.
Replace Liam's line
echo "{'fullname' : 'Jeff Hansen'}";
with
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1
This takes the value from an unbound custom field, processes, and saves it into my real description field:
class WidgetForm(forms.ModelForm):
extra_field = forms.CharField(required=False)
def processData(self, input):
# example of error handling
if False:
raise forms.ValidationError('Processing failed!')
return input + " has been processed"
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# self.description = "my result" note that this does not work
# Get the form instance so I can write to its fields
instance = super(WidgetForm, self).save(commit=commit)
# this writes the processed data to the description field
instance.description = self.processData(extra_field)
if commit:
instance.save()
return instance
class Meta:
model = Widget
fields = "__all__"
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
This class-based javascript animation works in AngularJS 1.2 (and 1.4 tested)
Edit: I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations.
myApp.animation('.ng-show-toggle-slidedown', function(){
return {
beforeAddClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).slideUp({duration: 400}, done);
} else {done();}
},
beforeRemoveClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).css({display:'none'});
$(element).slideDown({duration: 400}, done);
} else {done();}
}
}
});
Simply add the .ng-hide-toggle-slidedown
class to the container element, and the jQuery slide down behavior will be implemented based on the ng-hide class.
You must include the $(element).css({display:'none'})
line in the beforeRemoveClass
method because jQuery will not execute a slideDown unless the element is in a state of display: none
prior to starting the jQuery animation. AngularJS uses the CSS
.ng-hide:not(.ng-hide-animate) {
display: none !important;
}
to hide the element. jQuery is not aware of this state, and jQuery will need the display:none
prior to the first slide down animation.
The AngularJS animation will add the .ng-hide-animate
and .ng-animate
classes while the animation is occuring.
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
Use this code "./" as root on the server as it works for me
<a href="./fruits/index.html">Back to Fruits List</a>
but when you are on a local machine use the following code "../" as the root relative path
<a href="../fruits/index.html">Back to Fruits List</a>
public void Letters(JTextField a) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
char c = e.getKeyChar();
if (Character.isDigit(c)) {
e.consume();
}
if (Character.isLetter(c)) {
e.setKeyChar(Character.toUpperCase(c));
}
}
});
}
public void Numbers(JTextField a) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume();
}
}
});
}
public void Caracters(final JTextField a, final int lim) {
a.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent ke) {
if (a.getText().length() == lim) {
ke.consume();
}
}
});
}
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.
For example, using the Content-type
header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.
Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".
A MIME type is a string identifier composed of two parts: a type
and a subtype
.
The x-
prefix of a MIME subtype simply means that it's non-standard.
The vnd
prefix means that the MIME value is vendor specific.
In Android its very Simple .Just use the Calender class to get currentTimeMillis.
Timestamp stamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
Date date = new Date(stamp.getTime());
Log.d("Current date Time is " +date.toString());
In Java just Use System.currentTimeMillis() to get current timestamp
here is a copy-paste example that worked for me.
http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-swift/
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
toast("Your Message")
OR
toast(R.string.some_message)
Just add two methods in your BaseActivity
. Or create new BaseActivity
if you are not already using.
public class BaseActivity extends AppCompatActivity {
public void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
public void toast(@StringRes int msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
and extend all your activities by BaseActivity
.
public class MainActivity extends BaseActivity
Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:
>>> 0.4/100.
0.0040000000000000001
If you actually want a decimal value, do this:
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.
Why do you use new Array();
for hash? You need to use new Object()
instead.
And i think you will get what you want.
Assuming you mean a column like the SQL Server identity column?
In Oracle, you use a SEQUENCE to achieve the same functionality. I'll see if I can find a good link and post it here.
Update: looks like you found it yourself. Here is the link anyway: http://www.techonthenet.com/oracle/sequences.php
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
Command-line arguments are passed in the first String[]
parameter to main()
, e.g.
public static void main( String[] args ) {
}
In the example above, args
contains all the command-line arguments.
The short, sweet answer to the question posed is:
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
// oh noes!?
}
}
Just add an doctype declaration before the html tag
ex.: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd">
It is gonna work in JSP files as well. For further info: HTML Doctype Declaration
ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback
as long as you support api 24+.
In Kotlin:
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
})
}
You can use SQL on the command line:
echo 'CREATE DATABASE dbname;' | mysql <...>
Or you can use mysqladmin
:
mysqladmin create dbname
for simple comments:
set serveroutput on format wrapped;
begin
DBMS_OUTPUT.put_line('simple comment');
end;
/
-- do something
begin
DBMS_OUTPUT.put_line('second simple comment');
end;
/
you should get:
anonymous block completed
simple comment
anonymous block completed
second simple comment
if you want to print out the results of variables, here's another example:
set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
DBMS_OUTPUT.put_line(a_comment);
end;
/
-- do something
declare
a_comment VARCHAR2(200) :='comment';
begin
DBMS_OUTPUT.put_line(a_comment || 2);
end;
your output should be:
anonymous block completed
first comment
anonymous block completed
comment2
Try this, this works for my code name is a String:
cursor = rdb.query(true, TABLE_PROFILE, new String[] { ID,
REMOTEID, FIRSTNAME, LASTNAME, EMAIL, GENDER, AGE, DOB,
ROLEID, NATIONALID, URL, IMAGEURL },
LASTNAME + " like ?", new String[]{ name+"%" }, null, null, null, null);
In some cases your directive runs twice when you simply not correct close you directive like this:
<my-directive>Some content<my-directive>
This will run your directive twice. Also there is another often case when your directive runs twice:
make sure you are not including your directive in your index.html
TWICE!
Save yourself some troubleshooting time and log your require call, like so:
console.log(require('dotenv').config())
You should see an error with more detailed info on the problem.
try changing in the gradle file the targetSdkVersion to 8
targetSdkVersion 8
Make use of the zfill()
helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
Sample usage:
print str(1).zfill(3);
# Expected output: 001
Description:
When applied to a value, zfill()
returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Go to cmd and type: node "C:\Path\To\File\Sample.js"
I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client)
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
});
I have found a solution. It is just a workaround to my problem but currently the only solution.
ViewPager PagerAdapter not updating the View
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Does anyone know whether this is a bug or not?
I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).
Read my answer there for a fuller explaination, but in short:
They removed it deliberately, because compat mode is not actually really very good for testing compatibility.
If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.
The only way to get compat mode in IE11 is to set the X-UA-Compatible
header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
I was trying to install YII 2.0
php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha
I got the same error:
Could not open input file: composer.phar
Then i gave the full path of .phar like this:
php C:\ProgramData\Composer\bin\composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha
and it worked.
You could do this:
if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
// it was an input
}
or this, which is slower, but shorter and cleaner:
if( ctrl.is('input') ) {
// it was an input
}
If you want to be more specific, you can test the type:
if( ctrl.is('input:text') ) {
// it was an input
}
There are two definitions in data mining "Supervised" and "Unsupervised". When someone tells the computer, algorithm, code, ... that this thing is like an apple and that thing is like an orange, this is supervised learning and using supervised learning (like tags for each sample in a data set) for classifying the data, you'll get classification. But on the other hand if you let the computer find out what is what and differentiate between features of the given data set, in fact learning unsupervised, for classifying the data set this would be called clustering. In this case data that are fed to the algorithm don't have tags and the algorithm should find out different classes.
Generically, you can use a custom font using @font-face
in your CSS. Here's a very basic example:
@font-face {
font-family: 'YourFontName'; /*a name to be used later*/
src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}
Then, trivially, to use the font on a specific element:
.classname {
font-family: 'YourFontName';
}
(.classname
is your selector).
Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.
You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face
rules, so you don't have to write your own).
while also preventing people from having free access to download the font, if possible
Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.
I hope that helped!
This works in all browsers including earlier IE versions.
var arr = [];
[].push.apply(arr, htmlCollection);
Since jsperf is still down at the moment, here is a jsfiddle that compares the performance of different methods. https://jsfiddle.net/qw9qf48j/
Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx
Is it correct to do the following?
IF EXISTS(SELECT * FROM dbo.Scores) DROP TABLE dbo.Scores
No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).
Instead, for a permanent table you can use
IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL
DROP TABLE dbo.Scores;
Or, for a temporary table you can use
IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
DROP TABLE #TempTableName;
SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …
. See the answer by @Jovan.
Does not equal. The opposite of =
, equivalent to !=
.
Also, for everyone's info, this can return a non-zero number of rows. I see the OP has reformatted his question so it's a bit clearer, but as far as I can tell, this finds records where product ID is among those found in order #605, as is quantity, but it's not actually order #605. If order #605 contains 1 apple, 2 bananas and 3 crayons, #604 should match if it contains 2 apples (but not 3 dogs). It just won't match order #605. (And if ordid
is unique, then it would find exact duplicates.)
This function will return the byte size of any UTF-8 string you pass to it.
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
JavaScript engines are free to use UCS-2 or UTF-16 internally. Most engines that I know of use UTF-16, but whatever choice they made, it’s just an implementation detail that won’t affect the language’s characteristics.
The ECMAScript/JavaScript language itself, however, exposes characters according to UCS-2, not UTF-16.
As of 1st September 2014, the best locations by price for C and C++ standards documents in PDF are:
C++17 – ISO/IEC 14882:2017: $116 from ansi.org
C++14 – ISO/IEC 14882:2014: $90 NZD (about $60 US) from Standards New Zealand
C++11 – ISO/IEC 14882:2011: $60 from ansi.org $60 from Techstreet
C++03 – ISO 14882:2003: $30 from ansi.org $48 from SAI Global
C++98 – ISO/IEC 14882:1998: $90 NZD (about $60 US) from Standards New Zealand
C17/C18 – ISO/IEC 9899:2018: $185 from SAI Global / $116 from INCITS/ANSI / N2176 / c17_updated_proposed_fdis.pdf draft from November 2017 (Link broken, see Wayback Machine N2176)
C11 – ISO/IEC 9899:2011: $30 $60 from ansi.org / WG14 draft version N1570
C99 – ISO 9899:1999: $30 $60 from ansi.org / WG14 draft version N1256
C90 – AS 3955-1991: $141 from ansi.org $175 from Techstreet (the Australian version of C90, identical to ISO 9899:1990)
C90 – 9899:1990 Hardcopy available from SAI Global ($88 + shipping)
You cannot usually get old revisions of a standard (any standard) directly from the standards bodies shortly after a new edition of the standard is released. Thus, standards for C89, C90, C99, C++98, C++03 will be hard to find for purchase from a standards body. If you need an old revision of a standard, check Techstreet as one possible source. For example, it can still provide the Canadian version CAN/CSA-ISO/IEC 9899:1990 standard in PDF, for a fee.
Print copies of the standards are available from national standards bodies and ISO but are very expensive.
If you want a hardcopy of the C90 standard for much less money than above, you may be able to find a cheap used copy of Herb Schildt's book The Annotated ANSI Standard at Amazon, which contains the actual text of the standard (useful) and commentary on the standard (less useful - it contains several dangerous and misleading errors).
The C99 and C++03 standards are available in book form from Wiley and the BSI (British Standards Institute):
The working drafts for future standards are often available from the committee websites:
If you want to get drafts from the current or earlier C/C++ standards, there are some available for free on the internet:
ANSI X3.159-198 (C89): I cannot find a PDF of C89, but it is almost the same as the below draft for ISO/IEC 9899:1990 (C90). The only differences are in the boilerplate and section numbering.
ISO/IEC 9899:1990 (C90): https://www.pdf-archive.com/2014/10/02/ansi-iso-9899-1990-1/ansi-iso-9899-1990-1.pdf
(Almost the same as ANSI X3.159-198 (C89) except for the frontmatter and section numbering. Note that the conversion between ANSI and ISO/IEC Standard is seen inside this document, the document refers to its name as "ANSI/ISO: 9899/99" although this isn't the right name of the later made standard of it, the right name is "ISO/IEC 9899:1990")
ISO/IEC 9899:1999 (C99): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
ISO/IEC 9899:2011 (C11): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
ISO/IEC 9899:2018 (C17/C18): https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf (N2176)
ISO/IEC 14882:1998 (C++98): http://www.lirmm.fr/~ducour/Doc-objets/ISO+IEC+14882-1998.pdf
ISO/IEC 14882:2003 (C++03): https://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf
ISO/IEC 14882:2011 (C++11): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
ISO/IEC 14882:2014 (C++14): https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf?raw=true
ISO/IEC 14882:2017 (C++17): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf
ISO/IEC 14882:2020 (C++20): https://isocpp.org/files/papers/N4860.pdf
Note that these documents are not the same as the standard, though the versions just prior to the meetings that decide on a standard are usually very close to what is in the final standard. The FCD (Final Committee Draft) versions are password protected; you need to be on the standards committee to get them.
Even though the draft versions might be very close to the final ratified versions of the standards, some of this post's editors would strongly advise you to get a copy of the actual documents — especially if you're planning on quoting them as references. Of course, starving students should go ahead and use the drafts if strapped for cash.
It appears that, if you are willing and able to wait a few months after ratification of a standard, to search for "INCITS/ISO/IEC" instead of "ISO/IEC" when looking for a standard is the key. By doing so, one of this post's editors was able to find the C11 and C++11 standards at reasonable prices. For example, if you search for "INCITS/ISO/IEC 9899:2011" instead of "ISO/IEC 9899:2011" on webstore.ansi.org you will find the reasonably priced PDF version.
The site https://wg21.link/ provides short-URL links to the C++ current working draft and draft standards, and committee papers:
The current draft of the standard is maintained as LaTeX sources on Github. These sources can be converted to HTML using cxxdraft-htmlgen. The following sites maintain HTML pages so generated:
Tim Song also maintains generated HTML and PDF versions of the Networking TS and Ranges TS.
To do this in the Code Behind (VB.NET)
Dim txtCol As New DataGridTextColumn
Dim style As New Style(GetType(TextBlock))
Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
style.Triggers.Add(tri)
xtCol.ElementStyle = style
You can always see the console in a different window by opening the Organiser, clicking on the Devices tab, choosing your device and selecting it's console.
Of course, this doesn't work for the simulator :(
In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false
'secure' => env('SESSION_SECURE_COOKIE', false),
You should use dateutil. With that, you can use relativedelta, it's an improved version of timedelta.
>>> import datetime
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relativedelta(months=-1)
2012-02-15 12:33:04.281248
You Should Used Collection keyword in Controller. Like Here..
public function ApiView(){
return User::collection(Profile::all());
}
Here, User is Resource Name and Profile is Model Name. Thank You.
You can write a VBScript script to get the file version info:
VersionInfo.vbs
set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit
You can call this from the command line like this:
cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll
val = -3.1234
fraction = abs(val - as.integer(val) )
Truncate table
is faster than delete * from XXX
. Delete
is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.
setInterval
fires again and again in intervals, while setTimeout
only fires once.
See reference at MDN.
Here's yet another way to do it, but with extremely clean and simple code, that works in Python 3.7 in 2021:
import ctypes
def kill_thread(thread):
"""
thread: a threading.Thread object
"""
thread_id = thread.ident
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
Adapted from here: https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
var list1 = new List<Type1>();
var list2 = new List<Type2>();
list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));
Thanks! This solved a similar problem I had with a data attribute inside a Div.
<div id="prop_sample" data-want="data I want">data I do not want</div>
Use this xpath: //*[@id="prop_sample"]/@data-want
Hope this helps someone else!
You can try doing
<p>
<a href="MY WEBSITE LINK" target="_blank">
<img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
</a>
</p>
This should scale your image if in a fluid layout.
For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media
queries in CSS to change the width of the image.
Note that changing the height of the image will mess with the ratio.
If you are using iscroll.js on webkit browser or mobile browser, you could try:
$('#pageWrapper>div:last-child').css('top', "0px");
As others have stated, this won't work out of the box with Mockito. I would suggest using reflection to set the specific fields on the object that is being used by the code under test. If you find yourself doing this a lot, you can wrap this functionality in a library.
As an aside, if you are the one marking classes final, stop doing that. I ran across this question because I am working with an API where everything was marked final to prevent my legitimate need for extension (mocking), and I wish that the developer had not assumed that I would never need to extend the class.
2019-04-07 UPDATE: I tested today with a new version of windows 10 (build 1809, "2018 October's update") and not only the open SSH client is no longer in beta, as it is already installed. So, all you need to do is create the key and set your client to use open SSH instead of putty(pagent):
ssh-keygen
and press enterI tested on Git Extensions and Source Tree and it worked with my personal repo in GitHub. If you are in an earlier windows version or prefer a graphical client for SSH, please read below.
2018-06-04 UDPATE:
On windows 10, starting with version 1709 (win+R and type winver
to find the build number), Microsoft is releasing a beta of the OpenSSH client and server.
To be able to create a key, you'll need to install the OpenSSH server. To do this follow these steps:
Now you can open a prompt and ssh-keygen
and the client will be recognized by windows. I have not tested this.
If you do not have windows 10 or do not want to use the beta, follow the instructions below on how to use putty.
ssh-keygen
does not come installed with windows. Here's how to create an ssh key with Putty:
For openssh keys, a few more steps are required:
Now that the keys are saved. Start pagent
and add the private key there ( the ppk file in Putty's format)
Remember that pagent
must be running for the authentication to work
You may try RegExp
function isValidEmail( value ) {_x000D_
return /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,5}$/.test( value );_x000D_
}_x000D_
_x000D_
console.log( isValidEmail("[email protected]") )
_x000D_
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
Please try this-
ALTER TABLE TABLE_NAME DROP INDEX `PRIMARY`, ADD PRIMARY KEY (COLUMN1, COLUMN2,..);
Both nginx -t
and nginx -V
would print out the default nginx config file path.
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ nginx -V
nginx version: nginx/1.11.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...
If you want, you can get the config file by:
$ nginx -V 2>&1 | grep -o '\-\-conf-path=\(.*conf\)' | cut -d '=' -f2
/etc/nginx/nginx.conf
Even if you have loaded some other config file, they would still print out the default value.
ps aux
would show you the current loaded nginx config file.
$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 11 0.0 0.2 31720 2212 ? Ss Jul23 0:00 nginx: master process nginx -c /app/nginx.conf
So that you could actually get the config file by for example:
$ ps aux | grep "[c]onf" | awk '{print $(NF)}'
/app/nginx.conf
Many years since the original post. Now there is a great library called 'object-path'. https://github.com/mariocasciaro/object-path
Available on NPM and BOWER https://www.npmjs.com/package/object-path
It's as easy as:
objectPath.get(obj, "a.c.1"); //returns "f"
objectPath.set(obj, "a.j.0.f", "m");
And works for deeply nested properties and arrays.
// int year =2000; int month =9 ; int day=30;
public int getAge (int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);//current day
cal.set(year, month, day);// here ur date
noofyears = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--noofyears;
}
if(noofyears < 0)
throw new IllegalArgumentException("age < 0");
System.out.println(noofyears);
return noofyears;
This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.
The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"
This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.
Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]
However, the below links is perfect, it works for me.
http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0
Regards, Bilal
sp_help tablename in sql server -- sp_help [ [ @objname = ] 'name' ]
desc tablename in oracle -- DESCRIBE { table-Name | view-Name }
A late answer, yet another definition:
A package is represented by an imported top-entity which could either be a self-contained module, or the
__init__.py
special module as the top-entity from a set of modules within a sub directory structure.
So physically a package is a distribution unit, which provides one or more modules.
In the latest and greatest Hibernate, I was able to resolve the dependency by including the hibernate-jpa-2.0-api-1.0.0.Final.jar within lib/jpa directory. I didn't find the ejb-persistence jar in the most recent download.
There are a lot of awkward and unnecessarily complicated answers on this page. The highest rated one, @amateur's, is quite good, although it has a bit of unnecessary fluff in the RegExp. Here is a slightly more optimal solution with cleaner RegExp and a cleaner replace
call:
function updateQueryStringParamsNoHash(uri, key, value) {
var re = new RegExp("([?&])" + key + "=[^&]*", "i");
return re.test(uri)
? uri.replace(re, '$1' + key + "=" + value)
: uri + separator + key + "=" + value
;
}
As an added bonus, if uri
is not a string, you won't get errors for trying to call match
or replace
on something that may not implement those methods.
And if you want to handle the case of a hash (and you've already done a check for properly formatted HTML), you can leverage the existing function instead of writing a new function containing the same logic:
function updateQueryStringParams(url, key, value) {
var splitURL = url.split('#');
var hash = splitURL[1];
var uri = updateQueryStringParamsNoHash(splitURL[0]);
return hash == null ? uri : uri + '#' + hash;
}
Or you can make some slight changes to @Adam's otherwise excellent answer:
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=[^&#]*", "i");
if (re.test(uri)) {
return uri.replace(re, '$1' + key + "=" + value);
} else {
var matchData = uri.match(/^([^#]*)(#.*)?$/);
var separator = /\?/.test(uri) ? "&" : "?";
return matchData[0] + separator + key + "=" + value + (matchData[1] || '');
}
}
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
header=['name','age','weight']
try:
with open('output'+str(date.today())+'.csv',mode='w',encoding='utf8',newline='') as output_to_csv:
dict_csv_writer = csv.DictWriter(output_to_csv, fieldnames=header,dialect='excel')
dict_csv_writer.writeheader()
dict_csv_writer.writerows(toCSV)
print('\nData exported to csv succesfully and sample data')
except IOError as io:
print('\n',io)
Always better to install a previous version or in the installation make sure you specify the '/data' in a separate directory folder "C:\data"
This is a simple mix of the solutions. It work with Nullable types.
public static DataTable ToDataTable<T>(this IList<T> list)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = props[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
return table;
}
app.use(bodyParser.urlencoded({extended: true}));
I have the same problem but this work for me. You can try this extended part.
As per mysql documentation, TRUNCATE cannot be used on tables with foreign key relationships. There is no complete alternative AFAIK.
Dropping the contraint still does not invoke the ON DELETE and ON UPDATE. The only solution I can ATM think of is to either:
It would seem TRUNCATE in MySQL is not a complete feature yet (it also does not invoke triggers).
See comment
Solution for Windows:
.box
filevagrant box add --name name_of_my_box 'name_of_my_box.box'
vagrant box list
should show the new box in the listSolution for MAC:
.box
filevagrant box add --name name_of_my_box "./name_of_my_box.box"
vagrant box list
should show the new box in the listUse APPLICATIONFOLDER="path" for latest msiexec
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
Here is my code , To get Manufacturer,Brand name,Os version and support API Level
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL + " " + android.os.Build.BRAND +" ("
+ android.os.Build.VERSION.RELEASE+")"
+ " API-" + android.os.Build.VERSION.SDK_INT;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
Output:
System.out: button press on device name = Lava Alfa L iris(5.0) API-21
To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.
This is my full example approach of how you can do it effecively
After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.
static<T>void sort(T[]array,Comparator<?super T>comp)
take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.
The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:
return strB.compareToIgnoreCase(strA);
import java.util.Comparator;
public class IgnoreCaseComp implements Comparator<String> {
@Override
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
import java.util.Arrays;
public class IgnoreCaseSort {
public static void main(String[] args) {
String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
System.out.print("Initial order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
IgnoreCaseComp icc = new IgnoreCaseComp();
Arrays.sort(strs, icc);
System.out.print("Case-insesitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
Arrays.sort(strs);
System.out.print("Default, case-sensitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
}
}
run:
Initial order: Hello This is Sorting Example
Case-insesitive sorted order: Hello This Example is Sorting
Default, case-sensitive sorted order: Hello This Example Sorting is
BUILD SUCCESSFUL (total time: 0 seconds)
The method compareToIgnoreCase()
, although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare()
from java.text.Collator.
You can find a collator for your location by calling the method getInstance()
. After that you should set this Collator's strength property. This can be done with the setStrength()
method together with Collator.PRIMARY
as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location
import java.text.Collator;
import java.util.Comparator;
//this comparator uses one Collator to determine
//the right sort usage with no sensitive type
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {
Collator col;
IgnoreCaseComp() {
//default locale
col = Collator.getInstance();
//this will consider only PRIMARY difference ("a" vs "b")
col.setStrength(Collator.PRIMARY);
}
@Override
public int compare(String strA, String strB) {
return col.compare(strA, strB);
}
}
My take to keep Redux from referencing to the same variable of the initial state:
// write the default state as a function
const defaultOptionsState = () => ({
option1: '',
option2: 42,
});
const initialState = {
options: defaultOptionsState() // invoke it in your initial state
};
export default (state = initialState, action) => {
switch (action.type) {
case RESET_OPTIONS:
return {
...state,
options: defaultOptionsState() // invoke the default function to reset this part of the state
};
default:
return state;
}
};
if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.
df[["product_id","customer_id","store_id"]]
/**
* Extension of TreeMap to provide default value getter/creator.
*
* NOTE: This class performs no null key or value checking.
*
* @author N David Brown
*
* @param <K> Key type
* @param <V> Value type
*/
public abstract class Hash<K, V> extends TreeMap<K, V> {
private static final long serialVersionUID = 1905150272531272505L;
/**
* Same as {@link #get(Object)} but first stores result of
* {@link #create(Object)} under given key if key doesn't exist.
*
* @param k
* @return
*/
public V getOrCreate(final K k) {
V v = get(k);
if (v == null) {
v = create(k);
put(k, v);
}
return v;
}
/**
* Same as {@link #get(Object)} but returns specified default value
* if key doesn't exist. Note that default value isn't automatically
* stored under the given key.
*
* @param k
* @param _default
* @return
*/
public V getDefault(final K k, final V _default) {
V v = get(k);
return v == null ? _default : v;
}
/**
* Creates a default value for the specified key.
*
* @param k
* @return
*/
abstract protected V create(final K k);
}
Example Usage:
protected class HashList extends Hash<String, ArrayList<String>> {
private static final long serialVersionUID = 6658900478219817746L;
@Override
public ArrayList<Short> create(Short key) {
return new ArrayList<Short>();
}
}
final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
You need to include the appropriate header
#include <stdio.h>
If you're not sure which header a standard function is defined in, the function's man page will state this.
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
Thanks @vpekar for your implementation. It helped a lot. I just found that it misses the tf-idf weight while calculating the cosine similarity. The Counter(word) returns a dictionary which has the list of words along with their occurence.
cos(q, d) = sim(q, d) = (q · d)/(|q||d|) = (sum(qi, di)/(sqrt(sum(qi2)))*(sqrt(sum(vi2))) where i = 1 to v)
Please feel free to view my code here. But first you will have to download the anaconda package. It will automatically set you python path in Windows. Add this python interpreter in Eclipse.
On Button
click event write this:
Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
that open the your URL.
Wouldn't unlinking it and creating the new one do the same thing in the end anyway?
To the people complaining about the noise when doing git diff:
git diff -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'
What I did was use an alias:
alias gd="git diff --ignore-all-space --ignore-space-at-eol --ignore-space-change --ignore-blank-lines -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'"
To ignore package-lock.json in diffs for the entire repository (everyone using it), you can add this to .gitattributes
:
package-lock.json binary
yarn.lock binary
This will result in diffs that show "Binary files a/package-lock.json and b/package-lock.json differ whenever the package lock file was changed. Additionally, some Git services (notably GitLab, but not GitHub) will also exclude these files (no more 10k lines changed!) from the diffs when viewing online when doing this.
Do as Rabbott says, or if you refuse jQuery:
<script type="text/javascript">
function get_action() { // inside script tags
return form_action;
}
</script>
<form action="" onsubmit="this.action=get_action();">
...
</form>
<asp:DropDownList ID="DdlMonths" runat="server">
<asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
<asp:ListItem Text="January" Value="1"></asp:ListItem>
<asp:ListItem Text="February" Value="2"></asp:ListItem>
....
<asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>
You can even use a RequiredFieldValidator
which ignore this item, it considers it as unselected.
<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
InitialValue="-1">
</asp:RequiredFieldValidator>
To change default db folder C:\data\db
in windows, the command is:
--dbpath
For example:
\mongod --dbpath C:\myfolder
This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.
There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:
Old question but still relevant.
I recommend using negative text-indent
.
list-style-position
must be outside
.
Pros:
Cons:
jsCH has worked great for me. Below is an example of a method that will connect to sftp server and download files to specified directory. It is recommended to stay away from disabling StrictHostKeyChecking. Although a little bit more difficult to set up, for security reasons specifying the known hosts should be the norm.
jsch.setKnownHosts("C:\Users\test\known_hosts"); recommended
JSch.setConfig("StrictHostKeyChecking", "no"); - not recommended
import com.jcraft.jsch.*;
public void downloadFtp(String userName, String password, String host, int port, String path) {
Session session = null;
Channel channel = null;
try {
JSch ssh = new JSch();
JSch.setConfig("StrictHostKeyChecking", "no");
session = ssh.getSession(userName, host, port);
session.setPassword(password);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.get(path, "specify path to where you want the files to be output");
} catch (JSchException e) {
System.out.println(userName);
e.printStackTrace();
} catch (SftpException e) {
System.out.println(userName);
e.printStackTrace();
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
Indeed an implementation fault.
The native approach in MySQL is to update a creation date yourself ( if you need one ) and have MySQL worry about the timestamp update date ? update date : creation date
like so:
CREATE TABLE tracked_data(
`data` TEXT,
`timestamp` TIMESTAMP,
`creation_date` TIMESTAMP
) ENGINE=INNODB;
On creation Insert NULL:
INSERT INTO tracked_data(`data`,`creation_date`) VALUES ('creation..',NULL);
NULL values for timestamp are interperted as CURRENT_TIMESTAMP by default.
In MySQL the first TIMESTAMP column of a table gets both DEFAULT CURRENT_TIMESTAMP
and ON UPDATE CURRENT_TIMESTAMP
attribute, if no attributes are given for it.
this is why TIMESTAMP column with attributes must come first or you get the error described in this thread.
You can't. However, you can replace the array with a new one which contains the extra element.
But it is easier and gives better performance to use an List<T>
(uses interface IList
) for this. List<T>
does not resize the array every time you add an item - instead it doubles it when needed.
Try:
class Student
{
IList<Subject> subjects = new List<Subject>();
}
class Subject
{
string Name;
string referenceBook;
}
Now you can say:
someStudent.subjects.Add(new Subject());
If you have more than one join you could use comma separated USING statements:
DELETE
FROM
AAA AS a
USING
BBB AS b,
CCC AS c
WHERE
a.id = b.id
AND a.id = c.id
AND a.uid = 12345
AND c.gid = 's434sd4'
The chosen answer is a good answer, but be careful with the object returned.
string test = null;
string test2 = "";
if (test is string)
Console.WriteLine("This will never be hit.");
if (test2 is string)
Console.WriteLine("Always hit.");
Extrapolating...
string test = GetDefault(typeof(string));
if (test is string)
Console.WriteLine("This will never be hit.");
I don't think just turning off DocLint is a good solution, at least not long term. It is good that Javadoc has become a bit more strict so the right way to fix the build problem is to fix the underlying problem. Yes, you'll ultimately need to fix those source code files.
Here are the things to look out for that you could previously get away with:
{@link }
s. (same goes for similar tags such as @see
)@author
values. This used to be accepted : @author John <[email protected]>
but not so anymore because of the un-escaped brackets.You'll simply have to fix your source code files and keep building your Javadoc until it can build without a failure. Cumbersome yes, but personally I like when I have brought my projects up to DocLint level because it means I can be more confident that the Javadoc I produce is actually what I intend.
There's of course the problem if you are generating Javadoc on some source code you've not produced yourself, for example because it comes from some code generator, e.g. wsimport. Strange that Oracle didn't prepare their own tools for JDK8 compliance before actually releasing JDK8. It seems it won't be fixed until Java 9. Only in this particular case I suggest to turn off DocLint as documented elsewhere on this page.
I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.
Teaser:
public class SampleViewModel: BaseViewModelStub
{
public string Name { get; set; }
[UiCommand]
public void HelloWorld()
{
MessageBox.Show("Hello World!");
}
[UiCommand]
public void Print()
{
MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
}
public bool CanPrint()
{
return !String.IsNullOrEmpty(Name);
}
}
}
UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.
Here is your article for doing it with code
private void Form1_Load(object sender, System.EventArgs e)
{
// Create the ToolTip and associate with the Form container.
ToolTip toolTip1 = new ToolTip();
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;
// Set up the ToolTip text for the Button and Checkbox.
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}
If you want to read the whole file into a variable:
#!/bin/bash
value=`cat sources.xml`
echo $value
If you want to read it line-by-line:
while read line; do
echo $line
done < file.txt
Using def change
means you should write migrations that are reversible. And change_column
is not reversible. You can go up but you cannot go down, since change_column
is irreversible.
Instead, though it may be a couple extra lines, you should use def up
and def down
So if you have a column with no default value, then you should do this to add a default value.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: nil
end
Or if you want to change the default value for an existing column.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: true
end
Try this if you want to display one of duplicate rows based on RequestID and CreatedDate and show the latest HistoryStatus.
with t as (select row_number()over(partition by RequestID,CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)
or if you want to select one of duplicate rows considering CreatedDate only and show the latest HistoryStatus then try the query below.
with t as (select row_number()over(partition by CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t where rnum = (SELECT Max(rnum) FROM t)
Or if you want to select one of duplicate rows considering Request ID only and show the latest HistoryStatus then use the query below
with t as (select row_number()over(partition by RequestID order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)
All the above queries I have written in sql server 2005.
You can also use shift()
.
var streetaddress = addy.split(',').shift();
According to MDN Web Docs:
The
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
Even after installing python-tk, python3-tk I was getting error your python is not configured for Tk.
So I additionally installed tk8.6-dev Then I build my Python again, run following again: make, make install.
When I did this I saw messages on screen that it is building _tkinter and related modules. Once that is done, I tried 'import tkinter" and it worked.
On MacOS: add source ~/.bash_profile
to the end of ~/.zshrc
.
Then this profile will be in effect when you open zsh.
You can do this by adding a parameter &hd=1
to the video URL. That forces the video to start in the highest resolution available for the video. However you cannot specifically set it to 720p, because not every video has that hd ish.
http://code.google.com/apis/youtube/player_parameters.html
UPDATE: as of 2014, hd is deprecated https://developers.google.com/youtube/player_parameters?csw=1#Deprecated_Parameters
Use the builtin function zip()
:
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
If you want a fixed size website this should be fairly simple:
// Override container sizes_x000D_
@container-sm: 700px;_x000D_
@container-md: 700px;_x000D_
@container-lg: 700px;_x000D_
_x000D_
// Fixate media queries to tablet view only (lower viewports set to 0px, desired one to 1px, and the higher to ~9999px)_x000D_
_x000D_
@screen-xs-min: 0px;_x000D_
@screen-sm-min: 1px;_x000D_
@screen-md-min: 9999px;_x000D_
@screen-lg-min: 9999px;_x000D_
_x000D_
// Disable responsive features such as navbar-collapse_x000D_
@grid-float-breakpoint: 9999px;
_x000D_
Unless you are using .container-fluid, then also add:
.container-fluid {
width: 700px;
}
body {
width: 700px + @general-min-width;
}
Incorrect:
people:
empId: 123
empName: John
empDept: IT
Correct:
people:
emp:
id: 123
name: John
dept: IT
to upload a file using curl in Windows I found that the path requires escaped double quotes
e.g.
curl -v -F 'upload=@\"C:/myfile.txt\"' URL
I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.
I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).
Example:
We have following table structure:
CREATE TABLE tablename(
[msgid] [int] NOT NULL,
[userid] [int] NOT NULL,
[username] [varchar](70) NOT NULL,
[message] [varchar](5000) NOT NULL
)
Now there are at least two datasets in the table:
+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
| 1 | 1 | userA | hello |
| 2 | 1 | userB | world |
+-------+--------+----------+---------+
Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:
SELECT m.userid,
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC
For those errors where modelstate.isvalid is false, I generally send the error as it is thrown by the code. Its easy to understand for the developer who is consuming my service. I generally send the result using below code.
if(!ModelState.IsValid) {
List<string> errorlist=new List<string>();
foreach (var value in ModelState.Values)
{
foreach(var error in value.Errors)
errorlist.Add( error.Exception.ToString());
//errorlist.Add(value.Errors);
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest,errorlist);}
This sends the error to the client in below format which is basically a list of errors:
[
"Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: abc. Path 'Country',** line 6, position 16.\r\n
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)",
"Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: ab. Path 'State'**, line 7, position 13.\r\n
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)"
]
The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require()
. This was previously done using packages like typings
, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:
npm install --save-dev @types/node
Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.
There is a batch file called resetroot.bat
located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin
passwords. Then all you need to do is start the MySQL
service in xamp
and click the admin button.
"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:
String text = "N/A";
int intVal = 0;
try {
intVal = Integer.parseInt(text);
} catch (NumberFormatException e) {
//Log it if needed
intVal = //default fallback value;
}
Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
The default TEMPLATE_CONTEXT_PROCESSORS :
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")
First of all, you don't need the entitlements file unless you are adding custom key/value pairs that do not exist in the provisioning profile. When your app is built, any entitlements from the provisioning profile will be copied to the app.
Given that you still see an error message about missing entitlements, I can only assume the code signing options are not correct in the build settings.
You need to make sure the correct profile is selected for the "Debug" configuration, and to be safe, that you have selected the correct profile for both the "Debug" and child-node labelled "Any iOS SDK":
Although this screenshot shows the "Automatic Developer" profile selected, choose the exact provisioning profile you want from the drop down, just for testing purposes. It could be that Xcode is automatically choosing a different profile than the one you want.
Also be sure to do a clean build, completely delete the app from your device, etc. This is just to make sure you don't have some old fluff hanging around.
This should do the trick:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} // Author: silentnuke
Don't forget to add the internet permission in your manifest.
These answers are overly complicated. You can change the main body font size (as well as any other CSS you might want to change) simply by embedding CSS directly into the Rmarkdown document using the html <style>
tag. You do not need an entire CSS file for something so simple. If you are doing a lot of CSS then use a separate CSS file. If you are just modifying a couple of simple things I would do it like this.
---
title: "Untitled"
author: "James"
date: "9/29/2020"
output: html_document
---
<style type="text/css">
body{
font-size: 12pt;
}
</style>
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
With the advent of the CSS Flexible Box, many of web designers' nightmares1 have been resolved. One of the most hacky ones, the vertical alignment. Now it is possible even in unknown heights.
"Two decades of layout hacks are coming to an end. Maybe not tomorrow, but soon, and for the rest of our lives."
— CSS Legendary Eric Meyer at W3Conf 2013
Flexible Box (or in short, Flexbox), is a new layout system that is specifically designed for layout purposes. The specification states:
Flex layout is superficially similar to block layout. It lacks many of the more complex text- or document-centric properties that can be used in block layout, such as floats and columns. In return it gains simple and powerful tools for distributing space and aligning content in ways that webapps and complex web pages often need.
How can it help in this case? Well, let's see.
Using Twitter Bootstrap we have .row
s having some .col-*
s. All we need to do is to display the desired .row
2 as a flex container box and then align all its flex items (the columns) vertically by align-items
property.
EXAMPLE HERE (Please read the comments with care)
<div class="container">
<div class="row vertical-align"> <!--
^-- Additional class -->
<div class="col-xs-6"> ... </div>
<div class="col-xs-6"> ... </div>
</div>
</div>
.vertical-align {
display: flex;
align-items: center;
}
Colored area displays the padding-box of columns.
align-items: center
8.3 Cross-axis Alignment: the
align-items
propertyFlex items can be aligned in the cross axis of the current line of the flex container, similar to
justify-content
but in the perpendicular direction.align-items
sets the default alignment for all of the flex container’s items, including anonymous flex items.
align-items: center;
By center value, the flex item’s margin box is centered in the cross axis within the line.
Important note #1: Twitter Bootstrap doesn't specify the width
of columns in extra small devices unless you give one of .col-xs-#
classes to the columns.
Therefore in this particular demo, I have used .col-xs-*
classes in order for columns to be displayed properly in mobile mode, because it specifies the width
of the column explicitly.
But alternatively you could switch off the Flexbox layout simply by changing display: flex;
to display: block;
in specific screen sizes. For instance:
/* Extra small devices (767px and down) */
@media (max-width: 767px) {
.row.vertical-align {
display: block; /* Turn off the flexible box layout */
}
}
Or you could specify .vertical-align
only on specific screen sizes like so:
/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
.row.vertical-align {
display: flex;
align-items: center;
}
}
In that case, I'd go with @KevinNelson's approach.
Important note #2: Vendor prefixes omitted due to brevity. Flexbox syntax has been changed during the time. The new written syntax won't work on older versions of web browsers (but not that old as Internet Explorer 9! Flexbox is supported on Internet Explorer 10 and later).
This means you should also use vendor-prefixed properties like display: -webkit-box
and so on in production mode.
If you click on "Toggle Compiled View" in the Demo, you'll see the prefixed version of CSS declarations (thanks to Autoprefixer).
As you see in the previous demo, columns (the flex items) are no longer as high as their container (the flex container box. i.e. the .row
element).
This is because of using center
value for align-items
property. The default value is stretch
so that the items can fill the entire height of the parent element.
In order to fix that, you can add display: flex;
to the columns as well:
EXAMPLE HERE (Again, mind the comments)
.vertical-align {
display: flex;
flex-direction: row;
}
.vertical-align > [class^="col-"],
.vertical-align > [class*=" col-"] {
display: flex;
align-items: center; /* Align the flex-items vertically */
justify-content: center; /* Optional, to align inner flex-items
horizontally within the column */
}
Colored area displays the padding-box of columns.
Last, but not least, notice that the demos and code snippets here are meant to give you a different idea, to provide a modern approach to achieve the goal. Please mind the "Big Alert" section if you are going to use this approach in real world websites or applications.
For further reading including browser support, these resources would be useful:
1. Vertically align an image inside a div with responsive height
2. It's better to use an additional class in order not to alter Twitter Bootstrap's default .row
.
use the .not() method and check for an attribute:
$('p').not('[class]');
Check it here: http://jsfiddle.net/AWb79/
Since jQuery 1.9, the :target
selector will match the URL hash. So you could do:
$(":target").show(); // or $("ul:target").show();
Which would select the element with the ID matching the hash and show it.
I was getting this error in PyroCMS.
You can improve the error message in the Loader.php file that is in the code of the library.
Open the Loader.php file and find any calls to show_error
. I replaced mine with the following:
show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));
I was then able to see which file was causing the issues for me.
If you want the first line and then you want to perform some operation on file this code will helpful.
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
The endroid/QrCode library is easy to use, well maintained, and can be installed using composer. There is also a bundle to use directly with Symfony.
Installing :
$ composer require endroid/qrcode
Usage :
<?php
use Endroid\QrCode\QrCode;
$qrCode = new QrCode();
$qrCode
->setText('Life is too short to be generating QR codes')
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setLabel('Scan the code')
->setLabelFontSize(16)
->setImageType(QrCode::IMAGE_TYPE_PNG)
;
// now we can directly output the qrcode
header('Content-Type: '.$qrCode->getContentType());
$qrCode->render();
// or create a response object
$response = new Response($qrCode->get(), 200, array('Content-Type' => $qrCode->getContentType()));
If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)
In common LDAP is used to organize records in hierarchical structure.
Another way to find all View:
SELECT DISTINCT table_name FROM information_schema.TABLES WHERE table_type = 'VIEW'
If you are using Table.query
property:
from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()
If you are using session.query()
method (as stated in miniwark's answer):
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
I got this error when I set ft_min_word_len = 2
in my.cnf
, which lowers the minimum word length in a full text index to 2, from the default of 4.
Repairing the table fixed the problem.
Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg'
in your constructor. It will work definitely.
Create a method in AppDelegate Class for ex
func sharedInstance() -> AppDelegate{
return UIApplication.sharedApplication().delegate as! AppDelegate
}
and call it some where else for ex
let appDelegate : AppDelegate = AppDelegate().sharedInstance()
func sharedInstance() -> AppDelegate{
return UIApplication.shared.delegate as! AppDelegate
}
This is my solution using css+.
First of all, if the first child (flex-1) should be 100px, it shouldn't be flex.
In css+ in fact you can set flexible and/or static elements (columns or rows) and your example become as easy as this:
<div class="container">
<div class="EXTENDER">
<div class="COLS">
<div class="CELL _100px" style="background-color:blue">100px</div>
<div class="CELL _FLEX" style="background-color:red">flex</div>
</div>
</div>
</div>
Container CSS:
.container {
height: 200px;
width: 500px;
position: relative;
}
And obviously include css+ 0.2 core.
Here is the fiddle.
The performance tests here are not correct:
e.g.
timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit()
good tests can be found here: http://markandclick.com/1/post/2012/01/python-list-append-vs.html
Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show
.
using System.Runtime.InteropServices;
using HWND = System.IntPtr;
/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<HWND, string> GetOpenWindows()
{
HWND shellWindow = GetShellWindow();
Dictionary<HWND, string> windows = new Dictionary<HWND, string>();
EnumWindows(delegate(HWND hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int length = GetWindowTextLength(hWnd);
if (length == 0) return true;
StringBuilder builder = new StringBuilder(length);
GetWindowText(hWnd, builder, length + 1);
windows[hWnd] = builder.ToString();
return true;
}, 0);
return windows;
}
private delegate bool EnumWindowsProc(HWND hWnd, int lParam);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern int GetWindowTextLength(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern bool IsWindowVisible(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern IntPtr GetShellWindow();
}
And here’s some code that uses it:
foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
IntPtr handle = window.Key;
string title = window.Value;
Console.WriteLine("{0}: {1}", handle, title);
}
<input type="hidden" id="CDate" value="<%=DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")%>" />
In order to convert the date to JS date(all numbers):
var JSDate = $("#CDate").val();
JSDate = Date.parse(JSDate);
Give the same name in urls.py
path('detail/<int:id>', views.detail, name="detail"),
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
This can happen in more than one scenario, below is a list of well known scenarios :
// calling empty on a function
empty(myFunction($myVariable)); // the return value of myFunction should be saved into a variable
// then you can use empty on your variable
// using parenthesis to access an element of an array, parenthesis are used to call a function
if (isset($_POST('sms_code') == TRUE ) { ...
// that should be if(isset($_POST['sms_code']) == TRUE)
This also could be triggered when we try to increment the result of a function like below:
$myCounter = '356';
$myCounter = intVal($myCounter)++; // we try to increment the result of the intVal...
// like the first case, the ++ needs to be called on a variable, a variable should hold the the return of the function then we can call ++ operator on it.
As said above you can put it inside a ScrollView
... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView
... and if you want your component (or layout) to support both put inside both of them like this:
<HorizontalScrollView>
<ScrollView>
<!-- SOME THING -->
</ScrollView>
</HorizontalScrollView>
and with setting the layout_width
and layout_height
ofcourse.
Well, this is an old post but I will just contribute to the question -- someone may find it useful later:
adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:
int main(){ string fname, lname;
//ask user to enter name first and last name
cout << "Please enter your first name: ";
cin >> fname;
cout << "Please enter your last name: ";
cin >> lname;
cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: "
<< lname <<endl;
//stop program from exiting before printing results on the screen
cin.get();
return 0;
}
will give you info about the currently logged-in user, but you'll need to supply an oauth token. See:
I've done what you suggest, and I don't see a "Renew" button either.
The following is how I got mine renewed.
I see my three profiles (companynameProfile, "Team Provisioning Profile", and productnameProfile). THe first and third are going to expire within a couple of weeks. The second (and only the second) is flagged as "managed by Xcode". The profile names appear in a table with columns labelled: "Provisioning Profile", App ID, Status, and Actions. The status for all three is "Active". First 1 and 3, the Actions column has a "Download" button, and an "Edit" link. For 2, gthe Actions column has only the "Download" button.
There is no "Renew" (or "Refresh") button / link anywhere (and I did a view-source and searched that too :)
So, I thought...click on "Edit" on #3 ... two choices pop-up: Modify and Duplicate. I chose "Modify"
There is still no renew/refresh ... but there is a "Submit" button ... which doesn't work (turns out its sort of grayed out, but that's not at all obvious...bad UI design).
I discovered that if I change something on the screen (in my case, I selected a previously unused device), "Submit" darkens (becomes available). Click on "Submit". You're quietly (another UI problem :) taken back to the prior page, and the "Download" and "Edit" buttons are gone, and the status column should say "Pending"!
After awhile, I refreshed the window (reloaded) (don't know if it would have auto-refreshed) ... and saw that the status column had changed to "Active".
Now...I downloaded the new profile (the one that the darn page doesn't tell you is new, and doesn't LIST THE EXPIRATION DATE so you could tell yourself ... third UI flaw already :)
I downloaded the profile, deleted the old profile from the list in the Organizer window of Xcode, then dragged the new one into the Organizer window of Xcode, and ... voila, Organizer shows a new expiration date (of about 3 months from today).
Hope that helps,
Stan Cupertino, CA, USA
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
functionName() : ReturnType { ... }
Ever heard about appserver
from techdivision?
It is written in php and works as a appserver managing multithreads for high traffic php applications. Is still in beta but very promesing.
Same as the updating existing collection field, $set
will add a new fields if the specified field does not exist.
Check out this example:
> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
EDIT:
In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents
db.your_collection.update(
{},
{ $set: {"new_field": 1} },
false,
true
)
EDIT:
In the above example last 2 fields false, true
specifies the upsert
and multi
flags.
Upsert: If set to true, creates a new document when no document matches the query criteria.
Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.
This is for Mongo versions
prior to 2.2
. For latest versions the query is changed a bit
db.your_collection.update({},
{$set : {"new_field":1}},
{upsert:false,
multi:true})
A bracket - [
or ]
- means that end of the range is inclusive -- it includes the element listed. A parenthesis - (
or )
- means that end is exclusive and doesn't contain the listed element. So for [first1, last1)
, the range starts with first1
(and includes it), but ends just before last1
.
Assuming integers:
Project build settings have a block 'Swift Compiler - Languages', which stores information about Swift Language Version in key-value format. It will show you all available (supported) Swift Language Version for your Xcode and active version also by a tick mark.
Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift_version' in the Search bar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it (and there will be a tick mark on any one of list-item, that will be current swift version).
Look at this snapshot, for easy understanding:
With help of following code, programmatically you can find Swift version supported by your project.
#if swift(>=5.3)
print("Hello, Swift 5.3")
#elseif swift(>=5.2)
print("Hello, Swift 5.2")
#elseif swift(>=5.1)
print("Hello, Swift 5.1")
#elseif swift(>=5.0)
print("Hello, Swift 5.0")
#elseif swift(>=4.2)
print("Hello, Swift 4.2")
#elseif swift(>=4.1)
print("Hello, Swift 4.1")
#elseif swift(>=4.0)
print("Hello, Swift 4.0")
#elseif swift(>=3.2)
print("Hello, Swift 3.2")
#elseif swift(>=3.0)
print("Hello, Swift 3.0")
#elseif swift(>=2.2)
print("Hello, Swift 2.2")
#elseif swift(>=2.1)
print("Hello, Swift 2.1")
#elseif swift(>=2.0)
print("Hello, Swift 2.0")
#elseif swift(>=1.2)
print("Hello, Swift 1.2")
#elseif swift(>=1.1)
print("Hello, Swift 1.1")
#elseif swift(>=1.0)
print("Hello, Swift 1.0")
#endif
Here is result using Playground (with Xcode 11.x)
You have to do a shift and mask (AND) operation. Let b be any byte and p be the index (>= 0) of the bit from which you want to take n bits (>= 1).
First you have to shift right b by p times:
x = b >> p;
Second you have to mask the result with n ones:
mask = (1 << n) - 1;
y = x & mask;
You can put everything in a macro:
#define TAKE_N_BITS_FROM(b, p, n) ((b) >> (p)) & ((1 << (n)) - 1)
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
To change the default setting to display line numbers in vi/vim:
vi ~/.vimrc
then add the following line to the file:
set number
Either we can source ~/.vimrc
or save and quit by :wq
, now future vi/vim sessions will have numbering :)
<div style = "display: flex; justify-content:flex-end">
<button>Click me!</button>
</div>
_x000D_
<div style = "display: flex; justify-content: flex-end">
<button>Click me!</button>
</div>
To use await
, its executing context needs to be async
in nature
As it said, you need to define the nature of your executing context
where you are willing to await
a task before anything.
Just put async
before the fn
declaration in which your async
task will execute.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Explanation:
In your question, you are importing a method
which is asynchronous
in nature and will execute in parallel. But where you are trying to execute that async
method is inside a different execution context
which you need to define async
to use await
.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Wondering what's going under the hood
await
consumes promise/future / task-returning methods/functions and async
marks a method/function as capable of using await.
Also if you are familiar with promises
, await
is actually doing the same process of promise/resolve. Creating a chain of promise and executes you next task in resolve
callback.
For more info you can refer to MDN DOCS.
Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.
{
"env": {
"browser": true,
"node": true
}
}
You have to go to the /etc/nginx/sites-enabled/
and if this is the default configuration, then there should be a file by name: default
.
Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.
server {
listen 81;
}
To start the server, run the command line below;
sudo service nginx start
You may now access your application on port 81 (for localhost, http://localhost:81).
For EF 6
using System.Data.Entity;
query.Include(x => x.Collection.Select(y => y.Property))
Make sure to add using System.Data.Entity;
to get the version of Include
that takes in a lambda.
For EF Core
Use the new method ThenInclude
query.Include(x => x.Collection)
.ThenInclude(x => x.Property);
var linkGo = function(item) {_x000D_
$(item).on('click', function() {_x000D_
var _$this = $(this);_x000D_
var _urlBlank = _$this.attr("data-link");_x000D_
var _urlTemp = _$this.attr("data-url");_x000D_
if (_urlBlank === "_blank") {_x000D_
window.open(_urlTemp, '_blank');_x000D_
} else {_x000D_
// cross-origin_x000D_
location.href = _urlTemp;_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
I had to send my context through a constructor on a custom adapter displayed in a fragment and had this issue with getApplicationContext(). I solved it with:
this.getActivity().getWindow().getContext()
in the fragments' onCreate
callback.
Change in your html with adding the function on the button click
<input type="button" value="Clear" onclick="javascript:eraseText();">
<textarea id='output' rows=20 cols=90></textarea>
Try this in your js file:
function eraseText() {
document.getElementById("output").value = "";
}
I managed to do it by using the following code.
@Html.TextBoxFor(model => model.EndTime, new { type = "time" })
In WSDL definition, bindings contain operations, here comes style for each operation.
Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.
In WSDL types element looks as follows:
<types>
<xsd:schema>
<xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
</xsd:schema>
</types>
The schema is importing from external reference.
RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.
<types/>
<message name="getHelloWorldAsString">
<part name="arg0" type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return" type="xsd:string"/>
</message>
RPC : No types in WSDL
Document: Types section would be available in WSDL
I checked the "Put NetBeans metadata in separate directory" tick and it works fine.
This is in 2. Name and Location after you choose PHP from existing source
Add the CSS and JS in The Layout Folder.Access anywhere in the project
<!--// Stylesheets //-->
<?php
$themepath=Yii::app()->theme->baseUrl;
Yii::app()->clientScript->registerCoreScript("jquery");
?>
<link href="<?php echo $themepath."/css/custom.css"; ?>" rel="stylesheet" media="all" />
<!--// Javascript //-->
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
</script> -->
<script type="text/javascript" src="<?php echo $themepath; ?>/js/video.min.js"></script>
Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :
python3 your_file_name.py
But it doesn't work.
What worked for me however was:
python -u my_file_name.py
In windows, if Python is installed into the default directory (For me it is):
cd C:\Python27
You then proceed to type
"python.exe "[FULLPATH]\[name].py"
to run your Python script in Command Prompt
Python 3
from urllib.error import HTTPError
Python 2
from urllib2 import HTTPError
Just catch HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
See the Python tutorial.
e.g. complete example for Pyhton 2
import urllib2
from urllib2 import HTTPError
try:
urllib2.urlopen("some url")
except HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:
> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct
Example of Integer:
> x<- 2L
> print(x)
Example of Numeric (kind of like double/float from other programming languages)
> x<-3.4
> print(x)