It might be a wrong path. Ensure in your main app file you have:
app.use(express.static(path.join(__dirname,"public")));
Example link to your css as:
<link href="/css/clean-blog.min.css" rel="stylesheet">
similar for link to js files:
<script src="/js/clean-blog.min.js"></script>
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
The javascript has
var canvasW = 640;
var canvasH = 480;
in it. Try changing those as well as the css for the canvas.
Or better yet, have the initialize function determine the size of the canvas from the css!
in response to your edits, change your init function:
function init()
{
canvas = document.getElementById("mainCanvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
if( canvas.getContext )
{
setup();
setInterval( run , 33 );
}
}
Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.
html, body {
overflow: hidden;
}
Edit: document.width
and document.height
are obsolete. Replace with document.body.clientWidth
and document.body.clientHeight
Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.
Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.
So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
I've just did a hard reset on wrong project. What saved my life was Eclipse's local history. IntelliJ Idea is said to have one, too, and so may your editor, it's worth checking:
You can simply subtract two dates. You have to cast it first, using to_date
:
select to_date('2000-01-01', 'yyyy-MM-dd')
- to_date('2000-01-02', 'yyyy-MM-dd')
datediff
from dual
;
The result is in days, to the difference of these two dates is -1
(you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.
There are two methods in super class as java.lang.Object. We need to override them to custom object.
public boolean equals(Object obj)
public int hashCode()
Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
public class Test
{
private int num;
private String data;
public boolean equals(Object obj)
{
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Test at this point
Test test = (Test)obj;
return num == test.num &&
(data == test.data || (data != null && data.equals(test.data)));
}
public int hashCode()
{
int hash = 7;
hash = 31 * hash + num;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
return hash;
}
// other methods
}
If you want get more, please check this link as http://www.javaranch.com/journal/2002/10/equalhash.html
This is another example, http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html
Have Fun! @.@
The use of transition: none
seems to be supported (with a specific adjustment for Opera) given the following HTML:
<a href="#" class="transition">Content</a>
<a href="#" class="transition">Content</a>
<a href="#" class="noTransition">Content</a>
<a href="#" class="transition">Content</a>
...and CSS:
a {
color: #f90;
-webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;
-moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;
-o-transition:color 0.8s ease-in, background-color 0.1s ease-in;
transition:color 0.8s ease-in, background-color 0.1s ease-in;
}
a:hover {
color: #f00;
-webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;
-moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;
-o-transition:color 0.8s ease-in, background-color 0.1s ease-in;
transition:color 0.8s ease-in, background-color 0.1s ease-in;
}
a.noTransition {
-moz-transition: none;
-webkit-transition: none;
-o-transition: color 0 ease-in;
transition: none;
}
Tested with Chromium 12, Opera 11.x and Firefox 5 on Ubuntu 11.04.
The specific adaptation to Opera is the use of -o-transition: color 0 ease-in;
which targets the same property as specified in the other transition
rules, but sets the transition time to 0
, which effectively prevents the transition from being noticeable. The use of the a.noTransition
selector is simply to provide a specific selector for the elements without transitions.
Edited to note that @Frédéric Hamidi's answer, using all
(for Opera, at least) is far more concise than listing out each individual property-name that you don't want to have transition.
Updated JS Fiddle demo, showing the use of all
in Opera: -o-transition: all 0 none
, following self-deletion of @Frédéric's answer.
In GitExtensions you can select both branches in revision grid with Ctrl pressed. Then you can see files that differ between those branches. When you select a file you will see diff for it.
Taken from here
If you want to set an html content containg script tag to iframe, you have access to the iframe you created with:
$(iframeElement).contentWindow.document
so you can set innerHTML of any element in this.
But, for script tag, you should create and append an script tag, like this:
According to the docs: May 17, 2017
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
So,you should use both of the payload notification + data:
{
"to": "FCM registration ID",
"notification": {
"title" : "title",
"body" : "body text",
"icon" : "ic_notification"
},
"data": {
"someData" : "This is some data",
"someData2" : "etc"
}
}
There is no need to use click_action.You should just get exras from intent on LAUNCHER activity
<activity android:name=".MainActivity">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Java code should be on onCreate method on MainActivity :
Intent intent = getIntent();
if (intent != null && intent.getExtras() != null) {
Bundle extras = intent.getExtras();
String someData= extras.getString("someData");
String someData2 = extras.getString("someData2");
}
You can test both of the payload notification + data from Firebase Notifications Console . Don't forget to fill custom data fields on Advanced options section
I would answer this with multiple options actually, the some of which actually render in the body.
<input onclick="myfunction()"/>
- better to put it in event handlers in your script body instead.Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).
EDIT: references:
Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; }
on the div)
Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html
EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.
You can also upload using HTML5. You can use this AJAX uploader.
The JS code is basically:
$scope.doPhotoUpload = function () {
// ..
var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
myUploader.send();
// ..
}
Which reads from an HTML input element
<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">
#include <iostream>
#include <iomanip>
int main(void)
{
float value;
cin >> value;
cout << setprecision(4) << value;
return 0;
}
You can also use myform.$invalid
E.g.
if($scope.myform.$invalid){return;}
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
for me theme wasn't working with accentColor. But it did work with colorControlActivated
<style name="Progressbar.White" parent="AppTheme">
<item name="colorControlActivated">@color/white</item>
</style>
<ProgressBar
android:layout_width="@dimen/d_40"
android:layout_height="@dimen/d_40"
android:indeterminate="true"
android:theme="@style/Progressbar.White"/>
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
Select id,name,age
from
(
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
) results
order by name
Most likely the problem lies outside the code you are showing us here. You are trying to update an object that is not associated with the current session. If it is not the Invoice, then maybe it is an InvoiceItem that has already been persisted, obtained from the db, kept alive in some sort of session and then you try to persist it on a new session. This is not possible. As a general rule, never keep your persisted objects alive across sessions.
The solution will ie in obtaining the whole object graph from the same session you are trying to persist it with. In a web environment this would mean:
If you keep having issues post some of the code that is calling your service.
just remove and reDownload wrapper gradle.
Mac Home/.gradle/wrapper/dists/
remove gradle version and sync gradle in project and run project.
I have written two simple utility services that help me track service properties changes.
If you want to skip the long explanation, you can go strait to jsfiddle
mod.service('WatchObj', ['$rootScope', WatchObjService]);_x000D_
_x000D_
function WatchObjService($rootScope) {_x000D_
// returns watch function_x000D_
// obj: the object to watch for_x000D_
// fields: the array of fields to watch_x000D_
// target: where to assign changes (usually it's $scope or controller instance)_x000D_
// $scope: optional, if not provided $rootScope is use_x000D_
return function watch_obj(obj, fields, target, $scope) {_x000D_
$scope = $scope || $rootScope;_x000D_
//initialize watches and create an array of "unwatch functions"_x000D_
var watched = fields.map(function(field) {_x000D_
return $scope.$watch(_x000D_
function() {_x000D_
return obj[field];_x000D_
},_x000D_
function(new_val) {_x000D_
target[field] = new_val;_x000D_
}_x000D_
);_x000D_
});_x000D_
//unregister function will unregister all our watches_x000D_
var unregister = function unregister_watch_obj() {_x000D_
watched.map(function(unregister) {_x000D_
unregister();_x000D_
});_x000D_
};_x000D_
//automatically unregister when scope is destroyed_x000D_
$scope.$on('$destroy', unregister);_x000D_
return unregister;_x000D_
};_x000D_
}
_x000D_
This service is used in the controller in the following way: Suppose you have a service "testService" with the properties 'prop1', 'prop2', 'prop3'. You want to watch and assign to scope 'prop1' and 'prop2'. With the watch service it will look like that:
app.controller('TestWatch', ['$scope', 'TestService', 'WatchObj', TestWatchCtrl]);_x000D_
_x000D_
function TestWatchCtrl($scope, testService, watch) {_x000D_
$scope.prop1 = testService.prop1;_x000D_
$scope.prop2 = testService.prop2;_x000D_
$scope.prop3 = testService.prop3;_x000D_
watch(testService, ['prop1', 'prop2'], $scope, $scope);_x000D_
}
_x000D_
mod.service('apply', ['$timeout', ApplyService]);_x000D_
_x000D_
function ApplyService($timeout) {_x000D_
return function apply() {_x000D_
$timeout(function() {});_x000D_
};_x000D_
}
_x000D_
I would trigger it in the end of my async code to trigger the $digest loop. Like that:
app.service('TestService', ['apply', TestService]);_x000D_
_x000D_
function TestService(apply) {_x000D_
this.apply = apply;_x000D_
}_x000D_
TestService.prototype.test3 = function() {_x000D_
setTimeout(function() {_x000D_
this.prop1 = 'changed_test_2';_x000D_
this.prop2 = 'changed2_test_2';_x000D_
this.prop3 = 'changed3_test_2';_x000D_
this.apply(); //trigger $digest loop_x000D_
}.bind(this));_x000D_
}
_x000D_
So, all of that together will look like that (you can run it or open fiddle):
// TEST app code_x000D_
_x000D_
var app = angular.module('app', ['watch_utils']);_x000D_
_x000D_
app.controller('TestWatch', ['$scope', 'TestService', 'WatchObj', TestWatchCtrl]);_x000D_
_x000D_
function TestWatchCtrl($scope, testService, watch) {_x000D_
$scope.prop1 = testService.prop1;_x000D_
$scope.prop2 = testService.prop2;_x000D_
$scope.prop3 = testService.prop3;_x000D_
watch(testService, ['prop1', 'prop2'], $scope, $scope);_x000D_
$scope.test1 = function() {_x000D_
testService.test1();_x000D_
};_x000D_
$scope.test2 = function() {_x000D_
testService.test2();_x000D_
};_x000D_
$scope.test3 = function() {_x000D_
testService.test3();_x000D_
};_x000D_
}_x000D_
_x000D_
app.service('TestService', ['apply', TestService]);_x000D_
_x000D_
function TestService(apply) {_x000D_
this.apply = apply;_x000D_
this.reset();_x000D_
}_x000D_
TestService.prototype.reset = function() {_x000D_
this.prop1 = 'unchenged';_x000D_
this.prop2 = 'unchenged2';_x000D_
this.prop3 = 'unchenged3';_x000D_
}_x000D_
TestService.prototype.test1 = function() {_x000D_
this.prop1 = 'changed_test_1';_x000D_
this.prop2 = 'changed2_test_1';_x000D_
this.prop3 = 'changed3_test_1';_x000D_
}_x000D_
TestService.prototype.test2 = function() {_x000D_
setTimeout(function() {_x000D_
this.prop1 = 'changed_test_2';_x000D_
this.prop2 = 'changed2_test_2';_x000D_
this.prop3 = 'changed3_test_2';_x000D_
}.bind(this));_x000D_
}_x000D_
TestService.prototype.test3 = function() {_x000D_
setTimeout(function() {_x000D_
this.prop1 = 'changed_test_2';_x000D_
this.prop2 = 'changed2_test_2';_x000D_
this.prop3 = 'changed3_test_2';_x000D_
this.apply();_x000D_
}.bind(this));_x000D_
}_x000D_
//END TEST APP CODE_x000D_
_x000D_
//WATCH UTILS_x000D_
var mod = angular.module('watch_utils', []);_x000D_
_x000D_
mod.service('apply', ['$timeout', ApplyService]);_x000D_
_x000D_
function ApplyService($timeout) {_x000D_
return function apply() {_x000D_
$timeout(function() {});_x000D_
};_x000D_
}_x000D_
_x000D_
mod.service('WatchObj', ['$rootScope', WatchObjService]);_x000D_
_x000D_
function WatchObjService($rootScope) {_x000D_
// target not always equals $scope, for example when using bindToController syntax in _x000D_
//directives_x000D_
return function watch_obj(obj, fields, target, $scope) {_x000D_
// if $scope is not provided, $rootScope is used_x000D_
$scope = $scope || $rootScope;_x000D_
var watched = fields.map(function(field) {_x000D_
return $scope.$watch(_x000D_
function() {_x000D_
return obj[field];_x000D_
},_x000D_
function(new_val) {_x000D_
target[field] = new_val;_x000D_
}_x000D_
);_x000D_
});_x000D_
var unregister = function unregister_watch_obj() {_x000D_
watched.map(function(unregister) {_x000D_
unregister();_x000D_
});_x000D_
};_x000D_
$scope.$on('$destroy', unregister);_x000D_
return unregister;_x000D_
};_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div class='test' ng-app="app" ng-controller="TestWatch">_x000D_
prop1: {{prop1}}_x000D_
<br>prop2: {{prop2}}_x000D_
<br>prop3 (unwatched): {{prop3}}_x000D_
<br>_x000D_
<button ng-click="test1()">_x000D_
Simple props change_x000D_
</button>_x000D_
<button ng-click="test2()">_x000D_
Async props change_x000D_
</button>_x000D_
<button ng-click="test3()">_x000D_
Async props change with apply_x000D_
</button>_x000D_
</div>
_x000D_
I had the same problem with a similar string like yours
{id:1,field1:"someField"},{id:2,field1:"someOtherField"}
The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the []
with this the parser recognized
var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)
Hope it helps,
If anyone has a more elegant approach please share.
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:
angular.module('myApp', ['myApp.directives', 'myApp.services']);
plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview
create constant file with any name like my_constants.py declare constant like that
CONSTANT_NAME = "SOME VALUE"
For accessing constant in your code import file like that
import my_constants as constant
and access the constant value as -
constant.CONSTANT_NAME
This worked great for me
$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
I'll take a little exception to jichao's answer. You can actually do everything he just talked about fairly easily. Instead of looking for a \n
, just look for carriage return at the end of the line.
sed -i 's/\r$//' "${FILE_NAME}"
To change from unix back to dos, simply look for the last character on the line and add a form feed to it. (I'll add -r
to make this easier with grep regular expressions.)
sed -ri 's/(.)$/\1\r/' "${FILE_NAME}"
Theoretically, the file could be changed to mac style by adding code to the last example that also appends the next line of input to the first line until all lines have been processed. I won't try to make that example here, though.
Warning: -i changes the actual file. If you want a backup to be made, add a string of characters after -i
. This will move the existing file to a file with the same name with your characters added to the end.
map.get(myCode)
margin: 50%;
You can adjust the percentage as needed. It seems to work for me in responsive emails.
How about BOM, the magical character Microsoft adds to start of files (at least XML)?
Here is mine solution (hope it is plug-n-play enough too):
// SlideAlongScroll_x000D_
var SlideAlongScroll = function(el) {_x000D_
var _this = this;_x000D_
this.el = el;_x000D_
// elements original position_x000D_
this.elpos_original = el.parent().offset().top; _x000D_
// scroller timeout_x000D_
this.scroller_timeout;_x000D_
// scroller calculate function_x000D_
this.scroll = function() {_x000D_
// 20px gap for beauty_x000D_
var windowpos = $(window).scrollTop() + 20;_x000D_
// targeted destination_x000D_
var finaldestination = windowpos - this.elpos_original;_x000D_
// define stopper object and correction amount_x000D_
var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it_x000D_
var stophere = stopper - el.outerHeight() - this.elpos_original - 20;_x000D_
// decide what to do_x000D_
var realdestination = 0;_x000D_
if(windowpos > this.elpos_original) {_x000D_
if(finaldestination >= stophere) {_x000D_
realdestination = stophere;_x000D_
} else {_x000D_
realdestination = finaldestination;_x000D_
}_x000D_
}_x000D_
el.css({'top': realdestination });_x000D_
};_x000D_
// scroll listener_x000D_
$(window).on('scroll', function() {_x000D_
// debounce it_x000D_
clearTimeout(_this.scroller_timeout);_x000D_
// set scroll calculation timeout_x000D_
_this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300);_x000D_
});_x000D_
// initial position (in case page is pre-scrolled by browser after load)_x000D_
this.scroll();_x000D_
};_x000D_
// init action, little timeout for smoothness_x000D_
$(document).ready(function() {_x000D_
$('.slide-along-scroll').each(function(i, el) {_x000D_
setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el));_x000D_
});_x000D_
});
_x000D_
/* part you need */_x000D_
.slide-along-scroll {_x000D_
padding: 20px;_x000D_
background-color: #CCCCCC;_x000D_
transition: top 300ms ease-out;_x000D_
position: relative;_x000D_
}_x000D_
/* just demo */_x000D_
div { _x000D_
box-sizing: border-box;_x000D_
}_x000D_
.side-column {_x000D_
float: left;_x000D_
width: 20%; _x000D_
}_x000D_
.main-column {_x000D_
padding: 20px;_x000D_
float: right;_x000D_
width: 75%;_x000D_
min-height: 1200px;_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
.body { _x000D_
padding: 20px 0; _x000D_
}_x000D_
.body:after {_x000D_
content: ' ';_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
.header {_x000D_
padding: 20px;_x000D_
text-align: center;_x000D_
border-bottom: 2px solid #CCCCCC; _x000D_
}_x000D_
.footer {_x000D_
padding: 20px;_x000D_
border-top: 2px solid #CCCCCC;_x000D_
min-height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="header">_x000D_
<h1>Your super-duper website</h1>_x000D_
</div>_x000D_
<div class="body"> _x000D_
<div class="side-column">_x000D_
<!-- part you need -->_x000D_
<div class="slide-along-scroll">_x000D_
Side menu content_x000D_
<ul>_x000D_
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>_x000D_
<li>Aliquam tincidunt mauris eu risus.</li>_x000D_
<li>Vestibulum auctor dapibus neque.</li>_x000D_
</ul> _x000D_
</div>_x000D_
</div>_x000D_
<div class="main-column">_x000D_
Main content area (1200px)_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
Footer (slide along is limited by it)_x000D_
</div>_x000D_
</div>
_x000D_
You can store orther disk or path (not C) EX : D\
C:\Program Files\Java\jre1.8.0_101\bin>keytool -genkey -alias server -keyalg RSA -keysize 2048 -keystore D:\myserver.jks -dname "CN=myserver,OU=IT-WebDev, O=TIACHOP, L=HCM, ST=0753, C=VN" && keytool -certreq -alias server -file D:\myserver.csr -keystore D:\myserver.jks
Hash.merge! is the cleanest solution
o = { a: 'a', b: 'b' }
o.merge!(o) { |key, value| "%#{ value }%" }
puts o.inspect
> { :a => "%a%", :b => "%b%" }
Please do not mark this response as correct as smitec has already answered correctly. I'm including a convenience function I keep in my .First library that makes converting a windows path to the format that works in R (the methods described by Sacha Epskamp). Simply copy the path to your clipboard (ctrl + c) and then run the function as pathPrep()
. No need for an argument. The path is printed to your console correctly and written to your clipboard for easy pasting to a script. Hope this is helpful.
pathPrep <- function(path = "clipboard") {
y <- if (path == "clipboard") {
readClipboard()
} else {
cat("Please enter the path:\n\n")
readline()
}
x <- chartr("\\", "/", y)
writeClipboard(x)
return(x)
}
If you are using phpmyadmin then this feature is already there.
Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH()
and CHARACTER_LENGTH()
as well.
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
In order to create an Android Wear emulator you need to follow the instructions below:
If your version of Android SDK Tools is lower than 22.6, you must update
Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.
Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.
Below is the snapshot of what it should look like:
Then you must check the following in order to create a Wearable AVD:
For the Device, select Android Wear Square or Android Wear Round.
For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).
For the CPU/ABI, select Android Wear ARM (armeabi-v7a).
For the Skin, select AndroidWearSquare or AndroidWearRound.
Leave all other options set to their defaults and click OK.
Then you are good to go. For more information you can always refer to the developer site.
insert this line driver.execute_script("window.scrollBy(0,925)", "")
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
foreach ( int number in numbers )
{
if ( number < 0 )
{
continue;
}
//otherwise process number
}
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
I ran into a problem where the typical position: fixed
and bottom: 0
didn't work. Discovered a neat functionality with position: sticky
. Note it's "relatively" new so it won't with IE/Edge 15 and earlier.
Here's an example for w3schools.
<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
position: sticky;
bottom: 0;
background-color: yellow;
padding: 30px;
font-size: 20px;
}
</style>
</head>
<body>
<p>Lorem ipsum dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dlerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas dolor nteger frinegestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas </p>
<div class="sticky">I will stick to the screen when you reach my scroll position</div>
</body>
</html>
_x000D_
Easy to use date in blade template use Carbon that way
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
Date Between Query
SELECT *
FROM emp
WHERE HIREDATE between to_date (to_char(sysdate, 'yyyy') ||'/09/01', 'yyyy/mm/dd')
AND to_date (to_char(sysdate, 'yyyy') + 1|| '/08/31', 'yyyy/mm/dd');
window.fbAsyncInit = function () {_x000D_
FB.init({_x000D_
appId: 'Your-appId',_x000D_
cookie: false, // enable cookies to allow the server to access _x000D_
// the session_x000D_
xfbml: true, // parse social plugins on this page_x000D_
version: 'v2.0' // use version 2.0_x000D_
});_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
var js, fjs = d.getElementsByTagName(s)[0];_x000D_
if (d.getElementById(id)) return;_x000D_
js = d.createElement(s); js.id = id;_x000D_
js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
_x000D_
function fb_login() {_x000D_
FB.login(function (response) {_x000D_
_x000D_
if (response.authResponse) {_x000D_
console.log('Welcome! Fetching your information.... ');_x000D_
//console.log(response); // dump complete info_x000D_
access_token = response.authResponse.accessToken; //get access token_x000D_
user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
FB.api('/me', function (response) {_x000D_
var email = response.email;_x000D_
var name = response.name;_x000D_
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true); _x000D_
});_x000D_
_x000D_
} else {_x000D_
//user hit cancel button_x000D_
console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
}_x000D_
}, {_x000D_
scope: 'email'_x000D_
});_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
</fb:login-button>
_x000D_
For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.
Update for Swift 3:
Update Info.plist with the following info:
View controller-based status bar appearance: NO
Then, in a ViewController or elsewhere:
UIApplication.shared.isStatusBarHidden = true
In the "give a man a fish, feed him for a day; teach a man to fish, get rid of him for the whole weekend" vein,
g++ --helpshows compiler options. The g++ -v option helps:
-v Display the programs invoked by the compiler
Look through the output for bogus paths. In my case the original command:
g++ -v "d:/UW_Work/EasyUnit/examples/1-BasicUnitTesting/main.cpp"
generated output including this little gem:
-iprefix c:\olimexods\yagarto\arm-none-eabi\bin\../lib/gcc/arm-none-eabi/4.5.1/
which would explain the "no such file or directory" message.
The "../lib/gcc/arm-none-eabi/4.5.1/" segment is coming from built-in specs:
g++ -dumpspecs
I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / "with" statements. It's a pretty annoying difference.
Swift iOS8
// prgm mark ----
// convert images into base64 and keep them into string
func convertImageToBase64(image: UIImage) -> String {
var imageData = UIImagePNGRepresentation(image)
let base64String = imageData.base64EncodedStringWithOptions(.allZeros)
return base64String
}// end convertImageToBase64
// prgm mark ----
// convert images into base64 and keep them into string
func convertBase64ToImage(base64String: String) -> UIImage {
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0) )
var decodedimage = UIImage(data: decodedData!)
return decodedimage!
}// end convertBase64ToImage
Well I'm not sure about the regex or your situation..
How about CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines and viola all blank line gone.
A side note - if the line is blank i.e. does not contain spaces, this will work
No for the moment.
I doubt it will be possible for the future for ActiveX support will be discontinued in near future (as MS stated).
Look here about HTML Object tag, but not anything will be accepted. You should try.
I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.
Choose Second Method of Authentication while installing.
I've solved this. In my case I just changed my configuration. 'hostname' became 'localhost'
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
Here is a simple method to troubleshoot connection issues:
If you want to grab the query parameter value in the URL, follow below code pieces
//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid
If you want to grab the URL parameter using Express param function
Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.
This can be used for validations or grabbing important information about item.
An example for this would be:
// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {
// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';
// save name to the request
req.tagid= modified;
next();
});
// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});
If this is happening in Angular 2+ application, you can just uncomment string polyfills in polyfills.ts:
import 'core-js/es6/string';
as suggested here solving the famous LazyInitializationException is one of the following methods:
(1) Use Hibernate.initialize
Hibernate.initialize(topics.getComments());
(2) Use JOIN FETCH
You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.
(3) Use OpenSessionInViewFilter
LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.
An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with
npm install connect-timeout
and in the code it has to be (Edited as per comment, how to include it in the code)
var timeout = require('connect-timeout');
app.use(timeout('100s'));
There are several ways to accomplish that in Vim. I don't know which are most similar to Sublime Text's though.
The first one would be via multiline insert mode. Put your cursor to the
second "a" in the first line, press Ctrl-V
, select all lines, then press I
, and
put in a doublequote. Pressing <esc>
will repeat the operation on every line.
The second one is via macros. Put the cursor on the first character, and start
recording a macro with qa
.
Go the your right with llll
, enter insert mode with
a
, put down a doublequote, exit insert mode, and go back to the beginning of
your row with <home>
(or equivalent). Press j
to move down one row.
Stop recording with q
.
And then replay the macro with @a
. Several times.
Does any of the above approaches work for you?
In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.
please paste below code on surfaceview extend class constructor.............
constructor coding
SurfaceHolder holder = getHolder();
holder.addCallback(this);
SurfaceView sur = (SurfaceView)findViewById(R.id.surfaceview);
sur.setZOrderOnTop(true); // necessary
holder = sur.getHolder();
holder.setFormat(PixelFormat.TRANSPARENT);
xml coding
<com.welcome.panelview.PanelViewWelcomeScreen
android:id="@+id/one"
android:layout_width="600px"
android:layout_height="312px"
android:layout_gravity="center"
android:layout_marginTop="10px"
android:background="@drawable/welcome" />
try above code...
Based on the other answers, here is how I got the numbers I needed in Python;
from decimal import Decimal
def gcd(a,b):
if b == 0:
return a
return gcd(b, a%b)
def closest_aspect_ratio(width, height):
g = gcd(width, height)
x = Decimal(str(float(width)/float(g)))
y = Decimal(str(float(height)/float(g)))
dec = Decimal(str(x/y))
return dict(x=x, y=y, dec=dec)
>>> closest_aspect_ratio(1024, 768)
{'y': Decimal('3.0'),
'x': Decimal('4.0'),
'dec': Decimal('1.333333333333333333333333333')}
You may also want to try two backslashes (\\")
to escape the escape character.
Speaking of the counter example - as given above, the counter will be shared between all functions that use the decorator:
def counter(func):
def wrapped(*args, **kws):
print 'Called #%i' % wrapped.count
wrapped.count += 1
return func(*args, **kws)
wrapped.count = 0
return wrapped
That way, your decorator can be reused for different functions (or used to decorate the same function multiple times: func_counter1 = counter(func); func_counter2 = counter(func)
), and the counter variable will remain private to each.
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
I know this topic is super old, but, in case if someone's looking for an answer, as me, I'm posting my solution.
This solution works IF you don't mind having some extra data at the beginning of your file.
Basically, the idea is to, if file is not existing, to create it and append current date at the first line.
Next, you can read the first line with fgets(fopen($file, 'r'))
, turn it into a DateTime
object or anything (you can obviously use it raw, unless you saved it in a weird format) and voila - you have your creation date! For example my script to refresh my log file every 30 days looks like this:
if (file_exists($logfile)) {
$now = new DateTime();
$date_created = fgets(fopen($logfile, 'r'));
if ($date_created == '') {
file_put_contents($logfile, date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
}
$date_created = new DateTime($date_created);
$expiry = $date_created->modify('+ 30 days');
if ($now >= $expiry) {
unlink($logfile);
}
}
The accepted answer has major drawback!
If you loaded your image that way your PictureBox will lock the image,so if you try to do any future operations on that image,you will get error message image used in another application!
This article show solution in VB
and This is C# implementation
FileStream fs = new System.IO.FileStream(@"Images\a.bmp", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(fs);
fs.Close();
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
netstat -nlp
should tell you the PID of what's listening on which port.
Stupid as it may sound but all "Provisioning Profiles" re-appear under "Organizer - Devices" once you connect a real device.
This does it for folder names:
def printFolderName(init_indent, rootFolder):
fname = rootFolder.split(os.sep)[-1]
root_levels = rootFolder.count(os.sep)
# os.walk treats dirs breadth-first, but files depth-first (go figure)
for root, dirs, files in os.walk(rootFolder):
# print the directories below the root
levels = root.count(os.sep) - root_levels
indent = ' '*(levels*2)
print init_indent + indent + root.split(os.sep)[-1]
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
If you are using netbeans go to tools-> java Platform, change jdk_home which points to c:/programfiles/java/jdk1_7 to c:programFiles(x86)/java/jdk1_6_21
if not editable find netbeans.cnf and make change as stated abouve for jdk_home. restart neatbeans and how it works I had the same problem , but i worked .
A primitive type cannot be null. So the solution is replace primitive type with primitive wrapper class in your tableName.java file. Such as:
@Column(nullable=true, name="client_os_id")
private Integer client_os_id;
public int getClient_os_id() {
return client_os_id;
}
public void setClient_os_id(int clientOsId) {
client_os_id = clientOsId;
}
reference http://en.wikipedia.org/wiki/Primitive_wrapper_class to find wrapper class of a primivite type.
I have what I believe is a better solution than the $('html, body')
hack.
It's not a one-liner, but the issue I had with $('html, body')
is that if you log $(window).scrollTop()
during the animation, you'll see that the value jumps all over the place, sometimes by hundreds of pixels (though I don't see anything like that happening visually). I needed the value to be predictable, so that I could cancel the animation if the user grabbed the scroll bar or twirled the mousewheel during the auto-scroll.
Here is a function will animate scrolling smoothly:
function animateScrollTop(target, duration) {
duration = duration || 16;
var scrollTopProxy = { value: $(window).scrollTop() };
if (scrollTopProxy.value != target) {
$(scrollTopProxy).animate(
{ value: target },
{ duration: duration, step: function (stepValue) {
var rounded = Math.round(stepValue);
$(window).scrollTop(rounded);
}
});
}
}
Below is a more complex version that will cancel the animation on user interaction, as well as refiring until the target value is reached, which is useful when trying to set the scrollTop instantaneously (e.g. simply calling $(window).scrollTop(1000)
— in my experience, this fails to work about 50% of the time.)
function animateScrollTop(target, duration) {
duration = duration || 16;
var $window = $(window);
var scrollTopProxy = { value: $window.scrollTop() };
var expectedScrollTop = scrollTopProxy.value;
if (scrollTopProxy.value != target) {
$(scrollTopProxy).animate(
{ value: target },
{
duration: duration,
step: function (stepValue) {
var roundedValue = Math.round(stepValue);
if ($window.scrollTop() !== expectedScrollTop) {
// The user has tried to scroll the page
$(scrollTopProxy).stop();
}
$window.scrollTop(roundedValue);
expectedScrollTop = roundedValue;
},
complete: function () {
if ($window.scrollTop() != target) {
setTimeout(function () {
animateScrollTop(target);
}, 16);
}
}
}
);
}
}
The following KIND of works and may do the tricky for you.
// in constructor of your app.ts with router and auth services injected
router.subscribe(path => {
if (!authService.isAuthorised(path)) //whatever your auth service needs
router.navigate(['/Login']);
});
Unfortunately this redirects later in the routing process than I'd like. The onActivate()
of the original target component is called before the redirect.
There is a @CanActivate
decorator you can use on the target component but this is a) not centralised and b) does not benefit from injected services.
It would be great if anyone can suggest a better way of centrally authorising a route before it is committed. I'm sure there must be a better way.
This is my current code (How would I change it to listen to the route change?):
import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
import {Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import { Todo } from './components/todo/todo';
import { About } from './components/about/about';
@Component({
selector: 'app'
})
@View({
template: `
<div class="container">
<nav>
<ul>
<li><a [router-link]="['/Home']">Todo</a></li>
<li><a [router-link]="['/About']">About</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
</div>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', component: Todo, as: 'Home' },
{ path: '/about', component: About, as: 'About' }
])
class AppComponent {
constructor(location: Location){
location.go('/');
}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'})]);
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
I would suggest looking at the javadoc for Thread class.
You have multiple mechanisms for thread manipulation.
Your main thread could join()
the three threads serially, and would then not proceed until all three are done.
Poll the thread state of the spawned threads at intervals.
Put all of the spawned threads into a separate ThreadGroup
and poll the activeCount()
on the ThreadGroup
and wait for it to get to 0.
Setup a custom callback or listener type of interface for inter-thread communication.
I'm sure there are plenty of other ways I'm still missing.
Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.
<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
This worked perfectly fine.
</xsl:if>
You can do it a number of ways, depending on the type of quotes you use:
echo "<a href='http://www.whatever.com/$param'>Click here</a>";
echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";
Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n
will be expanded to mean the new line character, it will just be the characters \
and n
in sequence.
You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.
On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.
When you do echo $array;
, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.
You might actually need
echo json_encode($array);
This should get you what you want.
EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
It's just hash which is associated with user in database or some other way. That token can be used to authenticate and then authorize a user access related contents of the application. To retrieve this token on client side login is required. After first time login you need to save retrieved token not any other data like session, session id because here everything is token to access other resources of application.
Token is used to assure the authenticity of the user.
UPDATES: In current time, We have more advanced token based technology called JWT (Json Web Token). This technology helps to use same token in multiple systems and we call it single sign-on.
Basically JSON Based Token contains information about user details and token expiry details. So that information can be used to further authenticate or reject the request if token is invalid or expired based on details.
Use the built-in MSDB.DBO.AGENT_DATETIME(20150119,0)
https://blog.sqlauthority.com/2015/03/13/sql-server-interesting-function-agent_datetime/
I found that any directory laying under system directive like /var
, /usr
, /etc
could not be mount under the container.
The directive should be at user's space -v
switch instructs docker daemon to mount local directory to the container, for example:
docker run -t -d -v /{local}/{path}:/{container}/{path} --name {container_name} {imagename}
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
Limiting only to Swagger related resources:
.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");
There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:
int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
array[i] = (int*)malloc(sizeof(int) * 50);
Of course, you can also declare the array as int* array[50]
and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.
It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
, then malloc a block of 50*50 ints or whatever and access using that L
macro, e.g.
#define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
int dim_x = 50;
int dim_y = 50;
int* array = malloc(dim_x*dim_y*sizeof(int));
int foo = L(array, 4, 6, dim_x);
But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.
$('input.myclass[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : ""); });
If you use different windows user, your SSH key and git settings will be independent.
If this is not an option for you, then your friend should add your SSH key to her Github account.
Although, previous solution will keep you pushing as yourself, but it will allow you to push into her repo. If you don't want this and work in different folder on the same pc, you can setup username and email locally inside a folder with git by removing -g
flag of the config command:
git config user.name her_username
git config user.email her_email
Alternatively, if you push over https
protocol, Github will prompt for username/password every time (unless you use a password manager).
Found an elegant way from MDN
var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
Or you can use the spread operator
feature of ES6:
let fruits = [ 'apple', 'banana'];
const moreFruits = [ 'orange', 'plum' ];
fruits.push(...moreFruits); // ["apple", "banana", "orange", "plum"]
The current spec says this regarding flex: 1 1 auto
:
Sizes the item based on the
width
/height
properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are eitherflex: auto
,flex: initial
, orflex: none
, any positive free space after the items have been sized will be distributed evenly to the items withflex: auto
.
http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common
It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0
(or any other smallish number).
I know that you can modify a javascript file when using Google Chrome.
Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.
Hope this helps!
This code corrects the issues that Levitikon had with their code: (adapted from: [1]: http://msdn.microsoft.com/en-us/library/system.data.datatablereader.getschematable.aspx)
public List<string> GetColumnNames(SqlDataReader r)
{
List<string> ColumnNames = new List<string>();
DataTable schemaTable = r.GetSchemaTable();
DataRow row = schemaTable.Rows[0];
foreach (DataColumn col in schemaTable.Columns)
{
if (col.ColumnName == "ColumnName")
{
ColumnNames.Add(row[col.Ordinal].ToString());
break;
}
}
return ColumnNames;
}
The reason for getting all of those useless column names and not the name of the column from your table... Is because your are getting the name of schema column (i.e. the column names for the Schema table)
NOTE: this seems to only return the name of the first column...
EDIT: corrected code that returns the name of all columns, but you cannot use a SqlDataReader to do it
public List<string> ExecuteColumnNamesReader(string command, List<SqlParameter> Params)
{
List<string> ColumnNames = new List<string>();
SqlDataAdapter da = new SqlDataAdapter();
string connection = ""; // your sql connection string
SqlCommand sqlComm = new SqlCommand(command, connection);
foreach (SqlParameter p in Params) { sqlComm.Parameters.Add(p); }
da.SelectCommand = sqlComm;
DataTable dt = new DataTable();
da.Fill(dt);
DataRow row = dt.Rows[0];
for (int ordinal = 0; ordinal < dt.Columns.Count; ordinal++)
{
string column_name = dt.Columns[ordinal].ColumnName;
ColumnNames.Add(column_name);
}
return ColumnNames; // you can then call .Contains("name") on the returned collection
}
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
I had this problem on my developent environment with Visual Studio.
What helped me was to Clean Solution
in Visual Studio and then do a rebuild.
No one has suggested using the ArrayIterator class:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
gets around the by reference stipulation of the OP.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
It contains the allocated size, 10
. The unassigned indexes will contain the default value which is 0
for int
.
Try adding this class in order to fix the issue:
.ellipsis {
text-overflow: ellipsis;
/* Required for text-overflow to do anything */
white-space: nowrap;
overflow: hidden;
}
Explained further in this link http://css-tricks.com/almanac/properties/t/text-overflow/
On the SubLogin Form I would expose a SetLocation method so that you can set it from your parent form:
public class SubLogin : Form
{
public void SetLocation(Point p)
{
this.Location = p;
}
}
Then, from your main form:
loginForm = new SubLogin();
Point p = //do math to get point
loginForm.SetLocation(p);
loginForm.Show();
Similar to this question.
In essence it means that the method Bar
will not modify non mutable member variables of Foo
.
If you are echo
ing to a browser, you can use <br/>
with your statement:
echo 'Will print a newline<br/>';
echo 'But this wont!';
I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.
You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh
You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.
Just as an update to @Patricia's comment in the accepted answer and @Fraser's comment for the original question, if you have access to CMake 3.11+ you can make use of CMake's FetchContent function.
CMake's FetchContent page uses googletest as an example!
I've provided a small modification of the accepted answer:
cmake_minimum_required(VERSION 3.11)
project(basic_test)
set(GTEST_VERSION 1.6.0 CACHE STRING "Google test version")
################################
# GTest
################################
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-${GTEST_VERSION})
FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
FetchContent_Populate(googletest)
add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()
enable_testing()
################################
# Unit Tests
################################
# Add test cpp file
add_executable(runUnitTests testgtest.cpp)
# Include directories
target_include_directories(runUnitTests
$<TARGET_PROPERTY:gtest,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:gtest_main,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>)
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest
gtest_main)
add_test(runUnitTests runUnitTests)
You can use the INTERFACE_SYSTEM_INCLUDE_DIRECTORIES
target property of the gtest and gtest_main targets as they are set in the google test CMakeLists.txt script.
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E>
with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.
As others suggested, the problem is when windows.h
is included before WinSock2.h
. Because windows.h
includes winsock.h
. You can not use both WinSock2.h
and winsock.h
.
Solutions:
Include WinSock2.h
before windows.h
. In the case of precompiled headers, you should solve it there. In the case of simple project, it is easy. However in big projects (especially when writing portable code, without precompiled headers) it can be very hard, because when your header with WinSock2.h
is included, windows.h
can be already included from some other header/implementation file.
Define WIN32_LEAN_AND_MEAN
before windows.h
or project wide. But it will exclude many other stuff you may need and you should include it by your own.
Define _WINSOCKAPI_
before windows.h
or project wide. But when you include WinSock2.h
you get macro redefinition warning.
Use windows.h
instead of WinSock2.h
when winsock.h
is enough for your project (in most cases it is). This will probably result in longer compilation time but solves any errors/warnings.
Here is an equivalent optional declaration in Swift:
var middleName: String?
This declaration creates a variable named middleName of type String. The question mark (?) after the String variable type indicates that the middleName variable can contain a value that can either be a String or nil. Anyone looking at this code immediately knows that middleName can be nil. It's self-documenting!
If you don't specify an initial value for an optional constant or variable (as shown above) the value is automatically set to nil for you. If you prefer, you can explicitly set the initial value to nil:
var middleName: String? = nil
for more detail for optional read below link
http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values
This should work:
$("label[for='comedyclubs']")
See also: Selectors/attributeEquals - jQuery JavaScript Library
Apache
, as usual, has a good answer from Apache Commons-Lang
in the form of
NumberUtils.isCreatable(String)
.
Handles null
s, no try
/catch
block required.
With [email protected] :
// declare
@mixin button( $bgcolor:blue ){
background:$bgcolor;
}
and use without value, button will be blue
//use
.my_button{
@include button();
}
and with value, button will be red
//use
.my_button{
@include button( red );
}
works with hexa too
Using @bill-shirley answer with a little addition
function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}
Usage:
$str = "Go placidly amidst the noise";
$hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
$strstr = hex_to_str($str);// Go placidly amidst the noise
+1 for TextMate on Mac OS X.
See also answers to this question. I recommend trying NetBeans if you're on Windows.
If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")
In this case you could do it like this way:
public BigInteger stringToBigInteger(String string){
byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
StringBuilder asciiString = new StringBuilder();
for(byte asciiCharacter:asciiCharacters){
asciiString.append(Byte.toString(asciiCharacter));
}
BigInteger bigInteger = new BigInteger(asciiString.toString());
return bigInteger;
}
I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.
just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:
<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female
in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.
You can change the JDK for Netbeans by modifying the config file:
netbeans.conf
file available under etc
folder inside the NetBeans installation. netbeans_jdkhome
variable to point to new JDK path, and then Right Click on Project go to -> Maven -> Update project ->select Force update project check box and click on Finish.
No, you can not do Insert/Update/Delete.
Functions only work with select
statements. And it has only READ-ONLY Database Access.
In addition:
Bit of a long shot, but on a lab a while back, we had a situation where a SQL Server appeared unresponsive, not because we had spiked the CPU or anything we could track within SQL Server, it appeared operational to all tests but connections failed under some load.
The issue turned out to be due to the volume of traffic against the server meant we were triggering the in built windows Syn Attack Flood Protection within Windows. Annoyingly when you hit this, there is no logged message within windows server, or within SQL - you only see the symtpoms which are connections failing to be made - this is because windows slows down on accepting the messages and let's a queue build. From the connection standpoint, the server appears to not respond when it should (it doesn't even acknowledge the message arrived)
http://msdn.microsoft.com/en-us/library/ee377084(v=bts.10).aspx
Scroll down to SynAttackProtect and you will see the default in windows server 2003 sp1 onwards was to enable this feature by default. It is a DDOS protection mechanism in effect, and the lack of logging that it is triggering makes it incredibly difficult to detect when your server does this.
It took 3 days within the MS lab before it was figured out.
You mentioned 100 conenctions, we had an app that constantly connected, ran queries and then disconnected, it did not hold the connections open. This meant that we had multiple threads on each machine connectiong doing this, 10 machines, multiple threads per machine, and it was considered enough different connections consistently being made / dropped to trigger the defense.
Whether you are at that level (since it is not a clearly defined threshold by MS) is hard to say.
Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.
In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64
equivalent of the int
input. float32
datatype is also available in GoLang
Code:
package main
import "fmt"
func main() {
var i int
fmt.Println("Enter an Integer input: ")
fmt.Scanf("%d", &i)
f := float64(i)
fmt.Printf("The float64 representation of %d is %f\n", i, f)
}
Solution:
>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000
If the mysql is hosted on aws , just uninstall the plugin. From the root user fire below
UNINSTALL PLUGIN validate_password;
loads of reading documentation on how to round numbers, many experts suggest writing your own rounding routines, as the 'canned' version provided with your language may not be precise enough, or contain errors. i imagine, however, they're talking many decimal places not just one, two, or three. with that in mind, here is my solution (although not EXACTLY as requested as my needs are to display dollars - the process is not much different, though).
sub asDollars($) {
my ($cost) = @_;
my $rv = 0;
my $negative = 0;
if ($cost =~ /^-/) {
$negative = 1;
$cost =~ s/^-//;
}
my @cost = split(/\./, $cost);
# let's get the first 3 digits of $cost[1]
my ($digit1, $digit2, $digit3) = split("", $cost[1]);
# now, is $digit3 >= 5?
# if yes, plus one to $digit2.
# is $digit2 > 9 now?
# if yes, $digit2 = 0, $digit1++
# is $digit1 > 9 now??
# if yes, $digit1 = 0, $cost[0]++
if ($digit3 >= 5) {
$digit3 = 0;
$digit2++;
if ($digit2 > 9) {
$digit2 = 0;
$digit1++;
if ($digit1 > 9) {
$digit1 = 0;
$cost[0]++;
}
}
}
$cost[1] = $digit1 . $digit2;
if ($digit1 ne "0" and $cost[1] < 10) { $cost[1] .= "0"; }
# and pretty up the left of decimal
if ($cost[0] > 999) { $cost[0] = commafied($cost[0]); }
$rv = join(".", @cost);
if ($negative) { $rv = "-" . $rv; }
return $rv;
}
sub commafied($) {
#*
# to insert commas before every 3rd number (from the right)
# positive or negative numbers
#*
my ($num) = @_; # the number to insert commas into!
my $negative = 0;
if ($num =~ /^-/) {
$negative = 1;
$num =~ s/^-//;
}
$num =~ s/^(0)*//; # strip LEADING zeros from given number!
$num =~ s/0/-/g; # convert zeros to dashes because ... computers!
if ($num) {
my @digits = reverse split("", $num);
$num = "";
for (my $i = 0; $i < @digits; $i += 3) {
$num .= $digits[$i];
if ($digits[$i+1]) { $num .= $digits[$i+1]; }
if ($digits[$i+2]) { $num .= $digits[$i+2]; }
if ($i < (@digits - 3)) { $num .= ","; }
if ($i >= @digits) { last; }
}
#$num =~ s/,$//;
$num = join("", reverse split("", $num));
$num =~ s/-/0/g;
}
if ($negative) { $num = "-" . $num; }
return $num; # a number with commas added
#usage: my $prettyNum = commafied(1234567890);
}
I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.
public class FileName
{
public string ThisFieldWorks {get;set;}
public string ThisFieldDoesNot;
}
In the case of Java:
If we use DataFrames
, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:
Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");
where e_id
is the column on which join is applied while sorted by salary in ASC.
Also, we can use Spark SQL as:
SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();
where
Suppose you have void method that prints many objects;
public static void print( Object... values){
for(Object c : values){
System.out.println(c);
}
}
Above example I used vararge as an argument that accepts values from 0 to N.
From comments: What if 2 strings and 5 integers ??
Answer:
print("string1","string2",1,2,3,4,5);
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
Components control views (html). They also communicate with other components and services to bring functionality to your app.
Modules consist of one or more components. They do not control any html. Your modules declare which components can be used by components belonging to other modules, which classes will be injected by the dependency injector and which component gets bootstrapped. Modules allow you to manage your components to bring modularity to your app.
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
Use btoa("yourstring")
more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs
Once gdb
starts, you can run the program using "r args".
So if you are running your code by:
$ executablefile arg1 arg2 arg3
Debug it on gdb
by:
$ gdb executablefile
(gdb) r arg1 arg2 arg3
I think it helps to think of the "else" as the word OTHERWISE.
so you would read it like this:
if (something is true)
{
// do stuff
}
otherwise if (some other thing is true)
{
// do some stuff
}
otherwise
{
// do some other stuff :)
}
Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>
. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx">
The resulting contents are :
Component1.html
<nav>
<a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
<router-outlet></router-outlet>
Component2.html
<a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ... </a>
<a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]"> In Two...Go to 4 ...</a>
<router-outlet name="nameThree"></router-outlet>
<router-outlet name="nameFour"></router-outlet>
The '/two'
represents the parent component and ['three']
and ['four']
represents the link to the respective children of component2
. Component3.html and Component4.html are the same as in the question.
router.module.ts
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree'
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
}
]
},];
No it is not possible. The only way that is possible is
static void Main(string[] args)
{
BaseClass myBaseObject = new DerivedClass();
DerivedClass myDerivedObject = myBaseObject as DerivedClass;
myDerivedObject.MyDerivedProperty = true;
}
How about
vim -O a a
That way you can edit a single file on your left and navigate the whole dir on your right... Just a thought, not the solution...
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
hash = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.
http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager
Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.
It depends where you put this initialisation.
If the array is static as in
char array[100] = {0};
int main(void)
{
...
}
then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.
If your array is auto, then it is another story.
int foo(void)
{
char array[100] = {0};
...
}
In this case at every call of the function foo you will have a hidden memset.
The code above is equivalent to
int foo(void)
{
char array[100];
memset(array, 0, sizeof(array));
....
}
and if you omit the initializer your array will contain random data (the data of the stack).
If your local array is declared static like in
int foo(void)
{
static char array[100] = {0};
...
}
then it is technically the same case as the first one.
Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
There is a function UTC()
that returns the milliseconds from the unix epoch.
I used Ofer's answer for a while and found it great in most cases. Unfortunately, due to inconsistencies between pandas's to_csv and prettytable's from_csv, I had to use prettytable in a different way.
One failure case is a dataframe containing commas:
pd.DataFrame({'A': [1, 2], 'B': ['a,', 'b']})
Prettytable raises an error of the form:
Error: Could not determine delimiter
The following function handles this case:
def format_for_print(df):
table = PrettyTable([''] + list(df.columns))
for row in df.itertuples():
table.add_row(row)
return str(table)
If you don't care about the index, use:
def format_for_print2(df):
table = PrettyTable(list(df.columns))
for row in df.itertuples():
table.add_row(row[1:])
return str(table)
double signof(double a) { return (a == 0) ? 0 : (a<0 ? -1 : 1); }
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
If you are working on windows, you can use pywin32
(old link: see update below).
I found an example here:
import win32com.client
wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
print usb.DeviceID
Update Apr 2020:
'pywin32' release versions from 218 and up can be found here at github. Current version 227.
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
Suppose: SqlConnection connectionObj = new SqlConnection()
for : connectionObj.ConnectionString -> use server name : (localdb)\\MSSQLLocalDB.
Note: Double back slash
for : App.config -> use server name : (localdb)\MSSQLLocalDB
Note: Single back slash
The following was rejected as an edit to tvanfosson's answer. I was asked to contribute it as my own answer. I used his suggestion and finished the implementation of a ConfigurationManager
wrapper. In principle I simply filled out the ...
in tvanfosson's answer.
No. Extension methods require an instance of an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static NameValueCollection AppSettings
{
get { return ConfigurationManager.AppSettings; }
}
public static ConnectionStringSettingsCollection ConnectionStrings
{
get { return ConfigurationManager.ConnectionStrings; }
}
public static object GetSection(string sectionName)
{
return ConfigurationManager.GetSection(sectionName);
}
public static Configuration OpenExeConfiguration(string exePath)
{
return ConfigurationManager.OpenExeConfiguration(exePath);
}
public static Configuration OpenMachineConfiguration()
{
return ConfigurationManager.OpenMachineConfiguration();
}
public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
{
return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
}
public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
{
return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
}
public static void RefreshSection(string sectionName)
{
ConfigurationManager.RefreshSection(sectionName);
}
}
I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...
You could just let Eclipse (plus one of the plugins discussed here) do the work for you.
Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export
simply from your IDE's context menu when browsing an SVN repository.
Advantages:
Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)
Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
If myDataGridView.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
Note that this will not delete the row form the database until you perform the delete in the database.
1. Set up your routes to accept data
{
path: 'some-route',
loadChildren:
() => import(
'./some-component/some-component.module'
).then(
m => m.SomeComponentModule
),
data: {
key: 'value',
...
},
}
2. Navigate to route:
From HTML:
<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>
Or from Typescript:
import {Router} from '@angular/router';
...
this.router.navigate(
[
'/some-component',
{
key: 'value',
...
}
]
);
3. Get data from route
import {ActivatedRoute} from '@angular/router';
...
this.value = this.route.snapshot.params['key'];
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/YourSubDirectory/yourprogram.exe");
Process.Start(new ProcessStartInfo(path));
Try the sp_foreachdb procedure.
The basic difference between all these annotations is as follows -
All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)
Models:
namespace Project.Models
{
public class EmployeeReferral : Person
{
public int EmployeeReferralId { get; set; }
//Company District
//List
[Required(ErrorMessage = "Required.")]
[Display(Name = "Employee District:")]
public int? DistrictId { get; set; }
public virtual District District { get; set; }
}
namespace Project.Models
{
public class District
{
public int? DistrictId { get; set; }
[Display(Name = "Employee District:")]
public string DistrictName { get; set; }
}
}
EmployeeReferral Controller:
namespace Project.Controllers
{
public class EmployeeReferralController : Controller
{
private ProjDbContext db = new ProjDbContext();
//
// GET: /EmployeeReferral/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
ViewBag.Districts = db.Districts;
return View();
}
View:
<td>
<div class="editor-label">
@Html.LabelFor(model => model.DistrictId, "District")
</div>
</td>
<td>
<div class="editor-field">
@*@Html.DropDownList("DistrictId", "----Select ---")*@
@Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
@Html.ValidationMessageFor(model => model.DistrictId)
</div>
</td>
Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.
check this fiddle
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
This fixed my issue AFTER ensuring my ports were all uniquely sorted out.
Two ways to implement a Caesar Cipher:
Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.
Option 2: Use a Map map each letter to a digit like this.
A - 0
B - 1
C - 2
etc...
With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.
Give your inputs names it will make it easier
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>
UPDATE:
If you give your button an id things can be even easier:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>
Javascript:
var button = document.getElementById("theButton"),
value = button.form.valueId.value;
button.onclick = function() {
foo(value);
}
A simple SQL example would be like this:
ALTER TABLE `<table_name>` ADD `<column_name>` INT(11) NULL DEFAULT NULL ;
Make sure you use back ticks `` in table name and column name
if use Inline CSS you use
<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>
Otherwise you can use class properties which related with a separate css file (styling your website) as like In CSS File
.imgSize {height:100px;width:100px;}
In HTML File
<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>
Sure there's an entity for tabs:
	
(The tab is ASCII character 9, or Unicode U+0009.)
However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre>
block, where literal tabs will be rendered as 8 spaces in a monospace font.
Here is a fast vectorized version of @Dimitri's solution if you have many values
to search for (values
can be multi-dimensional array):
#`values` should be sorted
def get_closest(array, values):
#make sure array is a numpy array
array = np.array(array)
# get insert positions
idxs = np.searchsorted(array, values, side="left")
# find indexes where previous index is closer
prev_idx_is_less = ((idxs == len(array))|(np.fabs(values - array[np.maximum(idxs-1, 0)]) < np.fabs(values - array[np.minimum(idxs, len(array)-1)])))
idxs[prev_idx_is_less] -= 1
return array[idxs]
Benchmarks
> 100 times faster than using a for
loop with @Demitri's solution`
>>> %timeit ar=get_closest(np.linspace(1, 1000, 100), np.random.randint(0, 1050, (1000, 1000)))
139 ms ± 4.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit ar=[find_nearest(np.linspace(1, 1000, 100), value) for value in np.random.randint(0, 1050, 1000*1000)]
took 21.4 seconds
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
You can use this function
public void delete()
{
File f = new File("E://implementation1/");
File[] files = f.listFiles();
for (File file : files) {
file.delete();
}
}
Check if you have a .git directory in your home folder and if you don't:
mkdir ~/.git
Solved the problem in my case.
Related to your question, you may want to consider limiting the amount of RAM SQL Server has access to if you are using it in a shared environment, i.e., on a server that hosts more than just SQL Server:
This will help alleviate SQL Server from consuming all the server's RAM.
You can enable the CURLOPT_VERBOSE
option:
curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
When CURLOPT_VERBOSE
is set, output is written to STDERR or the file specified using CURLOPT_STDERR
. The output is very informative.
You can also use tcpdump or wireshark to watch the network traffic.
For database :
USE db_name; SELECT @@character_set_database;
for i in range(10):
print(i, end = ' ')
You can provide any delimiter to the end field (space, comma etc.)
This is for Python 3
You can get a function for this directly form WordPress core files take a look here
http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/formatting.php#L2121
function human_time_diff( $from, $to = '' ) {
if ( empty( $to ) )
$to = time();
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s day', '%s days', $days ), $days );
} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s month', '%s months', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s year', '%s years', $years ), $years );
}
return $since;
}
Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.
I was looking for a solution to this and used the indirect one found on this page initially, but I found it quite long and clunky for what I was trying to do. After a bit of research, I found a more elegant solution (to my problem) using R1C1 notation - I think you can't mix different notation styles without using VBA though.
Depending on what you're trying to do with the self referenced cell, something like this example should get a cell to reference itself where the cell is F13:
Range("F13").FormulaR1C1 = "RC"
And you can then reference cells in relative positions to that cell such as - where your cell is F13 and you need to reference G12 from it.
Range("F13").FormulaR1C1 = "R[-1]C[1]"
You're essentially telling Excel to find F13 and then move down 1 row and up one column from that.
How this fit into my project was to apply a vlookup across a range where the lookup value was relative to each cell in the range without having to specify each lookup cell separately:
Sub Code()
Dim Range1 As Range
Set Range1 = Range("B18:B23")
Range1.Locked = False
Range1.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],DATABYCODE,2,FALSE),"""")"
Range1.Locked = True
End Sub
My lookup value is the cell to the left of each cell (column -1) in my DIM'd range and DATABYCODE is the named range I'm looking up against.
Hope that makes a little sense? Thought it was worth throwing into the mix as another way to approach the problem.
For me, I was trying to match up a regular indexed field in a child table, to a primary key in the parent table, and by default some MySQL frontend GUIs like Sequel Pro set the primary key as unsigned, so you have to make sure that the child table field is unsigned too (unless these fields might contain negative ints, then make sure they're both signed).
NewLine (\n) is 10 (0xA) and CarriageReturn (\r) is 13 (0xD).
Different operating systems picked different end of line representations for files. Windows uses CRLF (\r\n). Unix uses LF (\n). Older Mac OS versions use CR (\r), but OS X switched to the Unix character.
Here is a relatively useful FAQ.
There is a code solution too. I saw it in a training video. You can add a line to tell IE that the local file is safe. I tested on IE8 and it works. That line is <!-- saved from url=(0014)about:internet -->
For more details, please refer to https://msdn.microsoft.com/en-us/library/ms537628(v=vs.85).aspx
<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function () {
alert('hi');
});
</script>
</head>
<body>
</body>
</html>
I believe StringBuilder is faster if you have more than 4 strings you need to append together. Plus it can do some cool things like AppendLine.
Constant time solution, runs in O(8).
Store the state of the board as a binary number. The smallest bit (2^0) is the top left row of the board. Then it goes rightwards, then downwards.
I.E.
+-----------------+ | 2^0 | 2^1 | 2^2 | |-----------------| | 2^3 | 2^4 | 2^5 | |-----------------| | 2^6 | 2^7 | 2^8 | +-----------------+
Each player has their own binary number to represent the state (because tic-tac-toe) has 3 states (X, O & blank) so a single binary number won't work to represent the state of the board for multiple players.
For example, a board like:
+-----------+ | X | O | X | |-----------| | O | X | | |-----------| | | O | | +-----------+ 0 1 2 3 4 5 6 7 8 X: 1 0 1 0 1 0 0 0 0 O: 0 1 0 1 0 0 0 1 0
Notice that the bits for player X are disjoint from the bits for player O, this is obvious because X can't put a piece where O has a piece and vice versa.
To check whether a player has won, we need to compare all the positions covered by that player to a position we know is a win-position. In this case, the easiest way to do that would be by AND-gating the player-position and the win-position and seeing if the two are equal.
boolean isWinner(short X) {
for (int i = 0; i < 8; i++)
if ((X & winCombinations[i]) == winCombinations[i])
return true;
return false;
}
eg.
X: 111001010 W: 111000000 // win position, all same across first row. ------------ &: 111000000
Note: X & W = W
, so X is in a win state.
This is a constant time solution, it depends only on the number of win-positions, because applying AND-gate is a constant time operation and the number of win-positions is finite.
It also simplifies the task of enumerating all valid board states, their just all the numbers representable by 9 bits. But of course you need an extra condition to guarantee a number is a valid board state (eg. 0b111111111
is a valid 9-bit number, but it isn't a valid board state because X has just taken all the turns).
The number of possible win positions can be generated on the fly, but here they are anyways.
short[] winCombinations = new short[] {
// each row
0b000000111,
0b000111000,
0b111000000,
// each column
0b100100100,
0b010010010,
0b001001001,
// each diagonal
0b100010001,
0b001010100
};
To enumerate all board positions, you can run the following loop. Although I'll leave determining whether a number is a valid board state upto someone else.
NOTE: (2**9 - 1) = (2**8) + (2**7) + (2**6) + ... (2**1) + (2**0)
for (short X = 0; X < (Math.pow(2,9) - 1); X++)
System.out.println(isWinner(X));
It's actually very easy to handle using Scala f
interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html
Suppose we want to round till 2 decimal places:
scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198
scala> println(f"$sum%1.2f")
1.57
Use __LINE__
, but what is its type?
LINE The presumed line number (within the current source file) of the current source line (an integer constant).
As an integer constant, code can often assume the value is __LINE__ <= INT_MAX
and so the type is int
.
To print in C, printf()
needs the matching specifier: "%d"
. This is a far lesser concern in C++ with cout
.
Pedantic concern: If the line number exceeds INT_MAX
1 (somewhat conceivable with 16-bit int
), hopefully the compiler will produce a warning. Example:
format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]
Alternatively, code could force wider types to forestall such warnings.
printf("Not logical value at line number %ld\n", (long) __LINE__);
//or
#include <stdint.h>
printf("Not logical value at line number %jd\n", INTMAX_C(__LINE__));
Avoid printf()
To avoid all integer limitations: stringify. Code could directly print without a printf()
call: a nice thing to avoid in error handling2 .
#define xstr(a) str(a)
#define str(a) #a
fprintf(stderr, "Not logical value at line number %s\n", xstr(__LINE__));
fputs("Not logical value at line number " xstr(__LINE__) "\n", stderr);
1 Certainly poor programming practice to have such a large file, yet perhaps machine generated code may go high.
2 In debugging, sometimes code simply is not working as hoped. Calling complex functions like *printf()
can itself incur issues vs. a simple fputs()
.
1.Install-Package Microsoft.AspNet.WebApi.Cors
2 . Add this code in WebApiConfig.cs.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3. Add this
using System.Web.Http.Cors;
4. Add this code in Api Controller (HomeController.cs)
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
[HttpGet]
[Route("api/Home/test")]
public string test()
{
return "";
}
}
A couple of different ways to solve the problem:
Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.
static void Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return;
} else {
return;
}
Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method
static int Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return 1;
} else {
return 2;
}
}
Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:
static void Main(string[] args) {
Byte maxSize;
Queue queue = null;
if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
Environment.Exit(0);
}
queue = new Queue(){MaxSize = maxSize};
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}
Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)
static void Main(String[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize)) {
queue = new Queue(){MaxSize = maxSize};
} else {
Environment.Exit(0);
return;
}
} else {
Environment.Exit(0);
return;
}
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}
Step 1:Create a border.xml in Drawable folder
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
/>
<solid android:color="#ffffff"
/>
<stroke
android:width="2dip"
android:color="#000" />
</shape>
Step 2: Create a EditText in XML File
<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:hint="Enter Email"
android:padding="10dp"
android:layout_marginRight="25dp"
android:background="@drawable/border"
android:inputType="textEmailAddress"
android:singleLine="true" />
static
before a global variable means that this variable is not accessible from outside the compilation module where it is defined.
E.g. imagine that you want to access a variable in another module:
foo.c
int var; // a global variable that can be accessed from another module
// static int var; means that var is local to the module only.
...
bar.c
extern int var; // use the variable in foo.c
...
Now if you declare var
to be static you can't access it from anywhere but the module where foo.c
is compiled into.
Note, that a module is the current source file, plus all included files. i.e. you have to compile those files separately, then link them together.
You need to do two things:
async
before function.Start your function with return
.
var gulp = require('gulp');
gulp.task('message', async function() {
return console.log("HTTP Server Started");
});
Encountered this in Ubuntu for Windows, try running first
sudo apt-get update
sudo apt-get upgrade
then
sudo apt-get install npm
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.
I recently started playing with MQTT http://mqtt.org for Android as a way of doing what you're asking for (i.e. not SMS but data driven, almost immediate message delivery, scalable, not polling, etc.)
I have a blog post with background information on this in case it's helpful http://dalelane.co.uk/blog/?p=938
(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)
I just came across this, while looking for something else.
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
You can do something like:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
@Override
public void success(User[] users, HttpResponse response) {
}
}).execute();