Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Your scanf("%s", s);
is commented out. That means s is uninitialized, so when this line ln = strlen(s);
executes, you get a seg fault.
It always helps to initialize a pointer to NULL, and then test for null before using the pointer.
I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)
C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
struct sigaction act;
act.sa_handler = ouch;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
while(1) {
printf("Hello World!\n");
sleep(1);
}
}
segmentation fault arrives when you access memory which is not declared by the program. You can do this through pointers i.e through memory addresses. Or this may also be due to stackoverflow for eg:
void rec_func() {int q = 5; rec_func();}
int main() {rec_func();}
This call will keep on consuming stack memory until it's completely filled and thus finally stackoverflow happens. Note: it might not be visible in some competitive questions as it leads to timeouterror first but for those in which timeout doesn't happens its a hard time figuring out sigsemv.
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
PS: To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).
A segmentation fault or access violation occurs when a program attempts to access a memory location that is not exist, or attempts to access a memory location in a way that is not allowed.
/* "Array out of bounds" error
valid indices for array foo
are 0, 1, ... 999 */
int foo[1000];
for (int i = 0; i <= 1000 ; i++)
foo[i] = i;
Here i[1000] not exist, so segfault occurs.
Causes of segmentation fault:
it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
De-referencing NULL pointers – this is special-cased by memory management hardware.
Attempting to access a nonexistent memory address (outside process’s address space).
Attempting to access memory the program does not have rights to (such as kernel structures in process context).
Attempting to write read-only memory (such as code segment).
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
Before the problem arises, try to avoid it as much as possible:
Use appropriate tools for debugging. On Unix:
-fsanitize=address
flag.Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.
Allocate memory before using the pointer. If you don't allocate memory *point = 12
is undefined behavior.
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
Also your printf
is wrong. You need to dereference (*
) the pointer.
printf("%d", *ptr);
^
In my case the reason was having a class declared within another class within an extension.
extension classOrig {
class classChild {
class classGrandChild {
static let aVariable : String = "SomeValue";
}
}
}
This generated the error on my side. I had several frameworks in my project, yet it did not happen before.
You can only use
Object& return_Object();
if the object returned has a greater scope than the function. For example, you can use it if you have a class where it is encapsulated. If you create an object in your function, use pointers. If you want to modify an existing object, pass it as an argument.
class MyClass{
private:
Object myObj;
public:
Object& return_Object() {
return myObj;
}
Object* return_created_Object() {
return new Object();
}
bool modify_Object( Object& obj) {
// obj = myObj; return true; both possible
return obj.modifySomething() == true;
}
};
Updating the ulimit worked for my Kosaraju's SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.
For my MAC, I found out the possible maximum via :
$ ulimit -s -H
65532
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);
) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
You can only use date in input type="date"
as in format YYYY-MM-DD
I have implemented helper as formatDate
in NODE.js express-handlebars, don't need to be worry ... just use format as described in first line.
e.g:
< input type="date" id="date" name="date" class="form-control" value="{{formatDate invoice.date 'YYYY-MM-DD'}}" />
Check if a modal is open
$('.modal:visible').length && $('body').hasClass('modal-open')
To attach an event listener
$(document).on('show.bs.modal', '.modal', function () {
// run your validation... ( or shown.bs.modal )
});
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
#Windows
Another one reason - maybe your port has been excluded by some reasons.
So, try open CMD under admin rights and run :
net stop winnat
net start winnat
In my case it was enough.
Solution found here : https://medium.com/@Bartleby/ports-are-not-available-listen-tcp-0-0-0-0-3000-165892441b9d
start xampp (as administrator), (1) right click C:\xampp\xampp-control.exe, and run as administrator. (2) unistall service module and then install service module. (3) now try start the apache and mysql.
You can parse the geolocation through the addresses. Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
In my case:
I am getting 400 bad request because I set content-type
wrongly. I changed content type then able to get response successfully.
Before (Issue):
ClientResponse response = Client.create().resource(requestUrl).queryParam("noOfDates", String.valueOf(limit))
.header(SecurityConstants.AUTHORIZATION, formatedToken).
header("Content-Type", "\"application/json\"").get(ClientResponse.class);
After (Fixed):
ClientResponse response = Client.create().resource(requestUrl).queryParam("noOfDates", String.valueOf(limit))
.header(SecurityConstants.AUTHORIZATION, formatedToken).
header("Content-Type", "\"application/x-www-form-urlencoded\"").get(ClientResponse.class);
Use jquery to apply class to all tr unobtrusively.
$(”table td”).addClass(”right-align-class");
Use enhanced filters on td in case you want to select a particular td.
See jquery
Very late, but I guess many people will still land here through "Google Airlines". A moderm approach is to use WebRTC that doesn't require server support.
https://hacking.ventures/local-ip-discovery-with-html5-webrtc-security-and-privacy-risk/
Next code is a copy&paste from http://net.ipcalf.com/
// NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({iceServers:[]});
if (window.mozRTCPeerConnection) { // FF needs a channel/stream to proceed
rtc.createDataChannel('', {reliable:false});
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP(evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
document.getElementById('list').textContent = displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) { // c.f. http://tools.ietf.org/html/rfc4566#page-39
if (~line.indexOf("a=candidate")) { // http://tools.ietf.org/html/rfc4566#section-5.13
var parts = line.split(' '), // http://tools.ietf.org/html/rfc5245#section-15.1
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) { // http://tools.ietf.org/html/rfc4566#section-5.7
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})(); else {
document.getElementById('list').innerHTML = "<code>ifconfig | grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.
You need to break;
, throw
, goto
, or return
from each of your case labels. In a loop you may also continue
.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
}
The only time this isn't true is when the case labels are stacked like this:
case "SearchBooks": // no code inbetween case labels.
case "SearchAuthors":
// handle both of these cases the same way.
break;
<script type="text/javascript">
if(jQuery('input[id=input_id]').is(':checked')){
// Your Statment
}else{
// Your Statment
}
OR
if(jQuery('input[name=input_name]').is(':checked')){
// Your Statment
}else{
// Your Statment
}
</script>
Code taken from here : http://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html
There is one more difference of using the app and listening to http server is when you want to setup for https server
To setup for https, you need the code below:
var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
console.log('Https App started');
});
The app from express will return http server only, you cannot set it in express, so you will need to use the https server command
var express = require('express');
var app = express();
app.listen(1234);
$dir = dirname($file) . DIRECTORY_SEPARATOR;
I made https://www.npmjs.com/package/jsx-control-statements to make it a bit easier, basically it allows you to define <If>
conditionals as tags and then compiles them into ternary ifs so that the code inside the <If>
only gets executed if the condition is true.
Another small point: If you used the import some_module as sm
syntax, then you have to re-load the module with its aliased name (sm
in this example):
>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works
It works because the stack has not been altered (yet) since a was put there.
Call a few other functions (which are also calling other functions) before accessing a
again and you will probably not be so lucky anymore... ;-)
$('div#someID').datepicker({
onSelect: function(dateText, inst) { alert(dateText); }
});
you must bind it to input element only
can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
});
An easier way to do it is to use data-ng-init like this:
<select data-ng-init="somethingHere = options[0]" data-ng-model="somethingHere" data-ng-options="option.name for option in options"></select>
The main difference here is that you would need to include data-ng-model
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
Basically this error comes when npm server is not started.
So at first check the npm server status, if it's not running then start npm with command npm start
and you can see in terminal:
Loading dependency graph done.
Now npm is started and run your app in another terminal with command
react-native run-android
New JS allows this:
const str = 'This is my string';
Array.from(str).forEach(alert);
A simple client-side pagination example where data is fetched only once at page loading.
// dummy data_x000D_
const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
{ "req_no": 2, "title": "test2" },_x000D_
{ "req_no": 3, "title": "test3" },_x000D_
{ "req_no": 4, "title": "test4" },_x000D_
{ "req_no": 5, "title": "test5" },_x000D_
{ "req_no": 6, "title": "test6" },_x000D_
{ "req_no": 7, "title": "test7" },_x000D_
{ "req_no": 8, "title": "test8" },_x000D_
{ "req_no": 9, "title": "test9" },_x000D_
{ "req_no": 10, "title": "test10" },_x000D_
{ "req_no": 11, "title": "test11" },_x000D_
{ "req_no": 12, "title": "test12" },_x000D_
{ "req_no": 13, "title": "test13" },_x000D_
{ "req_no": 14, "title": "test14" },_x000D_
{ "req_no": 15, "title": "test15" },_x000D_
{ "req_no": 16, "title": "test16" },_x000D_
{ "req_no": 17, "title": "test17" },_x000D_
{ "req_no": 18, "title": "test18" },_x000D_
{ "req_no": 19, "title": "test19" },_x000D_
{ "req_no": 20, "title": "test20" },_x000D_
{ "req_no": 21, "title": "test21" },_x000D_
{ "req_no": 22, "title": "test22" },_x000D_
{ "req_no": 23, "title": "test23" },_x000D_
{ "req_no": 24, "title": "test24" },_x000D_
{ "req_no": 25, "title": "test25" },_x000D_
{ "req_no": 26, "title": "test26" }];_x000D_
_x000D_
// on page load collect data to load pagination as well as table_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
// At a time maximum allowed pages to be shown in pagination div_x000D_
const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
// hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
function hide_from_beginning(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.nextSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// hide pages from pagination ending if more than pagination_visible_pages_x000D_
function hide_from_end(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.previousSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// load data and style for active page_x000D_
function active_page(element, rows, req_per_page) {_x000D_
var current_page = document.getElementsByClassName('active');_x000D_
var next_link = document.getElementById('next_link');_x000D_
var prev_link = document.getElementById('prev_link');_x000D_
var next_tab = current_page[0].nextSibling; _x000D_
var prev_tab = current_page[0].previousSibling;_x000D_
current_page[0].className = current_page[0].className.replace("active", "");_x000D_
if (element === "next") {_x000D_
if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
next_tab.previousSibling.className += " active";_x000D_
next_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
next_tab.className += " active"_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_tab.style.display === "none") {_x000D_
next_tab.style.display = "block";_x000D_
hide_from_beginning(prev_link.nextSibling)_x000D_
}_x000D_
}_x000D_
} else if (element === "prev") {_x000D_
if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
prev_tab.nextSibling.className += " active";_x000D_
prev_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
prev_tab.className += " active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (prev_tab.style.display === "none") {_x000D_
prev_tab.style.display = "block";_x000D_
hide_from_end(next_link.previousSibling)_x000D_
}_x000D_
}_x000D_
} else {_x000D_
element.className += "active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Render the table's row in table request-table_x000D_
function render_table_rows(rows, req_per_page, page_no) {_x000D_
const response = JSON.parse(window.atob(rows));_x000D_
const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
$('#request-table').empty()_x000D_
$('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
resp.forEach(function (element, index) {_x000D_
if (Object.keys(element).length > 0) {_x000D_
const { req_no, title } = element;_x000D_
const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
$('#request-table').append(td)_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Pagination logic implementation_x000D_
function pagination(data, myarr) {_x000D_
const all_data = window.btoa(JSON.stringify(myarr));_x000D_
$(".pagination").empty();_x000D_
if (data.req_per_page !== 'ALL') {_x000D_
let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>«</a>` +_x000D_
`<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
if (total_page < pagination_visible_pages) {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= total_page; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
} else {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
}_x000D_
pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>»</a>`;_x000D_
$(".pagination").append(pager);_x000D_
} else {_x000D_
render_table_rows(all_data, myarr.length, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
//calling pagination function_x000D_
pagination(data, myarr);_x000D_
_x000D_
_x000D_
// trigger when requests per page dropdown changes_x000D_
function filter_requests() {_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
pagination(data, myarr);_x000D_
}
_x000D_
.box {_x000D_
float: left;_x000D_
padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
margin: 5px 0px 0px 0px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
color: black;_x000D_
float: left;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
transition: background-color .3s;_x000D_
border: 1px solid #ddd;_x000D_
margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<table id="request-table">_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
<div class="box options">_x000D_
<label>Requests Per Page: </label>_x000D_
<select id="req_per_page" onchange="filter_requests()">_x000D_
<option>5</option>_x000D_
<option>10</option>_x000D_
<option>ALL</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="box pagination">_x000D_
</div>_x000D_
</div>
_x000D_
The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.
>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
del x[7]
IndexError: list assignment index out of range
The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.
>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
del x[4]
IndexError: list assignment index out of range
The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.
>>> x = [1, 2, 3]
>>> x.pop(2)
3
>>> x
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x.pop(4)
IndexError: pop index out of range
See collections.deque for more details.
To make certain file types OPEN on your computer, instead of Chrome Downloading...
You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.
Now the file type will always OPEN using your default program.
To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads
Hope this helps.. :-)
Visual Instructions found here:
If you have the need to use other libraries in projects --typescript-- not just in projects - angle - you can look for tds's (TypeScript Declaration File) that are depares and that have information of methods, types, functions, etc. , which can be used by TypeScript, usually without the need for import. declare var is the last resource
npm install @types/lib-name --save-dev
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery objects in order to help differentiate. There is nothing magic about this practice – it just helps some people keep track of what different variables contain.
I use a similar technique to lazyload images, but can't help but notice that Javascript doesn't access the browser cache on first loading.
My example:
I have a rotating banner on my homepage with 4 images the slider wait 2 seconds, than the javascript loads the next image, waits 2 seconds, etc.
These images have unique urls that change whenever I modify them, so they get caching headers that will cache in the browser for a year.
max-age: 31536000, public
Now when I open Chrome Devtools and make sure de 'Disable cache' option is not active and load the page for the first time (after clearing the cache) all images get fetch and have a 200 status. After a full cycle of all images in the banner the network requests stop and the cached images are used.
Now when I do a regular refresh or go to a subpage and click back, the images that are in the cache seems to be ignored. I would expect to see a grey message "from disk cache" in the Network tab of Chrome devtools. In instead I see the requests pass by every two seconds with a Green status circle instead of gray, I see data being transferred, so it I get the impression the cache is not accessed at all from javascript. It simply fetches the image each time the page gets loaded.
So each request to the homepage triggers 4 requests regardless of the caching policy of the image.
Considering the above together and the new http2 standard most webservers and browsers now support, I think it's better to stop using lazyloading since http2 will load all images nearly simultaneously.
If this is a bug in Chrome Devtools it really surprises my nobody noticed this yet. ;)
If this is true, using lazyloading only increases bandwith usage.
Please correct me if I'm wrong. :)
HashMap <Integer,Integer> hm = new HashMap<Integer,Integer>();
Set<Integer> keys = hm.keySet(); //get all keys
for(Integer i: keys)
{
System.out.println(hm.get(i));
}
While searching this very question I discovered this example in the documentation.
QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);
Mutatis mutandis for your particular action of course.
Along with this note.
It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.
It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()
You can easily achieve this by using this code.
SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)
Or simply:
\dt
to show tables
\d+ <table name>
to describe a table
Edit: Works using the psql command line client
Use tolist()
:
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
Use webdriverwait with ExpectedCondition in try catch block with for loop EX: for python
for i in range(4):
try:
element = WebDriverWait(driver, 120).until( \
EC.presence_of_element_located((By.XPATH, 'xpath')))
element.click()
break
except StaleElementReferenceException:
print "exception "
Below code will provide you with all the click events on given selector:
jQuery(selector).data('events').click
You can iterate over it using each or for ex. check the length for validation like:
jQuery(selector).data('events').click.length
Thought it would help someone. :)
In my case, it was an accidental double escaping.
this works:
SelectedPath = @"C:\Program Files\My Company\My product";
this doesn't:
SelectedPath = @"C:\\Program Files\\My Company\\My product";
After a wild goose chase with tons of Google searches and burteforce attempts, I think I found how to solve this problem.
Steps undertaken to solve the problem:
Install ggplot with the dependencies argument to install.packages set to TRUE
install.packages("ggplot2",dependencies = TRUE)
The above step still does NOT include the Rcpp dependency so that has to be manually installed using the following command
install.packages("Rcpp")
However, while the above command successfully downloads Rcpp, for some reason, it fails to explode the ZIP file and install it in my R's library folder citing the following error:
package ‘Rcpp’ successfully unpacked and MD5 sums checked Warning in install.packages : unable to move temporary installation ‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\file27b8ef47b6d\Rcpp’ to ‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\Rcpp’
The downloaded binary packages are in C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages
C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages\Rcpp_0.12.3.zip
This led to successful installation of Rcpp in my R\R-3.2.3\library folder, thereby ensuring that Rcpp is now available when I attempt to load the library for ggplot2. I could not do this step in the past because my previous installation of R would throw error stating that Rcpp cannot be imported. However, the same command worked after I uninstalled and reinstalled R, which is ODD.
install.packages("C:/Users/MY_USER_ID/AppData/Local/Temp/Rtmp25XQ0S/downloaded_packages/Rcpp_0.12.3.zip", repos = NULL, type = "win.binary") package ‘Rcpp’ successfully unpacked and MD5 sums checked`
I was finally able to load the ggplot2 library successfully.
library(ggplot2)
You can use the excecl command
int execl(const char *path, const char *arg, ...);
Like shown here
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) {
return execl ("/bin/pwd", "pwd", NULL);
}
The second argument will be the name of the process as it will appear in the process table.
Alternatively, you can use the getcwd() function to get the current working directory:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255
int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';
if(getcwd(wd, MAX-1) == NULL) {
printf ("Can not get current working directory\n");
}
else {
printf("%s\n", wd);
}
return 0;
}
Got to android/app/build.gradle
and search for
buildTypes {
....
}
You might have something like
buildTypes {
debug {
...
}
release {
...
}
customBuildType {
...
}
}
Chose the buildType
you want to start and then start the App the following
react-native run-android --variant=[buildType] --appIdSuffix '[buildType]'
So,
react-native run-android --variant=debug --appIdSuffix 'debug'
According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts:
2.3.1. Debugging on the entire script
$ bash -x script1.sh
...
There is now a full-fledged debugger for Bash, available at SourceForge. These debugging features are available in most modern versions of Bash, starting from 3.x.
2.3.2. Debugging on part(s) of the script
set -x # Activate debugging from here w set +x # Stop debugging from here
...
Table 2-1. Overview of set debugging options
Short | Long notation | Result
-------+---------------+--------------------------------------------------------------
set -f | set -o noglob | Disable file name generation using metacharacters (globbing).
set -v | set -o verbose| Prints shell input lines as they are read.
set -x | set -o xtrace | Print command traces before executing command.
...
Alternatively, these modes can be specified in the script itself, by adding the desired options to the first line shell declaration. Options can be combined, as is usually the case with UNIX commands:
#!/bin/bash -xv
another direct & simpler answer would be
let url = new URLSearchParams(location.search)
let key = 'some_key'
return url.has(key)
? location.href.replace(new RegExp(`[?&]${key}=${url.get(key)}`), '')
: location.href
I have used this below:
^(\+|00)[0-9]{1,3}[0-9]{4,14}(?:x.+)?$
The format +CCC.NNNNNNNNNNxEEEE or 00CCC.NNNNNNNNNNxEEEE
Phone number must start with '+' or '00' for an international call. where C is the 1–3 digit country code,
N is up to 14 digits,
and E is the (optional) extension.
The leading plus sign and the dot following the country code are required. The literal “x” character is required only if an extension is provided.
You may try this:
Cookie::queue($name, $value, $minutes);
This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentation on Laravel
website.
Update (Retrieving A Cookie Value
):
$value = Cookie::get('name');
Note: If you set a cookie in the current request then you'll be able to retrieve it on the next subsequent request.
svn checkout --force svn://repo website.dir
then
svn revert -R website.dir
Will check out on top of existing files in website.dir, but not overwrite them. Then the revert will overwrite them. This way you do not need to take the site down to complete it.
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
This is not possible by native CSS. You'll have to use background images and some javascript tricks.
Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want. All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config. Example with nginx-rtmp-module:
rtmp {
server {
listen 1935; # Listen on standard RTMP port
chunk_size 4000;
application show {
live on;
# Turn on HLS
hls on;
hls_path /mnt/hls/;
hls_fragment 3;
hls_playlist_length 60;
# disable consuming the stream from nginx as rtmp
deny play all;
}
}
}
server {
listen 8080;
location /hls {
# Disable cache
add_header Cache-Control no-cache;
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Access-Control-Allow-Headers' 'Range';
# allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /mnt/;
}
}
After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.
In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Streaming</title>
<link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
<source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
var player = videojs('#player');
</script>
</body>
</html>
You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.
Nope, BeautifulSoup, by itself, does not support XPath expressions.
An alternative library, lxml, does support XPath 1.0. It has a BeautifulSoup compatible mode where it'll try and parse broken HTML the way Soup does. However, the default lxml HTML parser does just as good a job of parsing broken HTML, and I believe is faster.
Once you've parsed your document into an lxml tree, you can use the .xpath()
method to search for elements.
try:
# Python 2
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
from lxml import etree
url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)
There is also a dedicated lxml.html()
module with additional functionality.
Note that in the above example I passed the response
object directly to lxml
, as having the parser read directly from the stream is more efficient than reading the response into a large string first. To do the same with the requests
library, you want to set stream=True
and pass in the response.raw
object after enabling transparent transport decompression:
import lxml.html
import requests
url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)
Of possible interest to you is the CSS Selector support; the CSSSelector
class translates CSS statements into XPath expressions, making your search for td.empformbody
that much easier:
from lxml.cssselect import CSSSelector
td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
# Do something with these table cells.
Coming full circle: BeautifulSoup itself does have very complete CSS selector support:
for cell in soup.select('table#foobar td.empformbody'):
# Do something with these table cells.
Please note that e.which, e.keyCode and e.charCode are deprecated: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
I prefer e.key:
document.querySelector("input").addEventListener("keypress", function (e) {
var allowedChars = '0123456789.';
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey = e.key.length === 1 && !contains(allowedChars, e.key)
|| e.key === '.' && contains(e.target.value, '.');
invalidKey && e.preventDefault();});
This function doesn't interfere with control codes in Firefox (Backspace, Tab, etc) by checking the string length: e.key.length === 1
.
It also prevents duplicate dots at the beginning and between the digits: e.key === '.' && contains(e.target.value, '.')
Unfortunately, it doesn't prevent multiple dots at the end: 234....
It seems there is no way to cope with it.
This work for me:
$data = '<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/></data>';
$doc = new SimpleXMLElement($data);
$segarr = $doc->seg;
$count = count($segarr);
$j = 0;
for ($i = 0; $i < $count; $i++) {
if ($segarr[$j]['id'] == 'A12') {
unset($segarr[$j]);
$j = $j - 1;
}
$j = $j + 1;
}
echo $doc->asXml();
I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):
\begin{itemize}[leftmargin=0cm]
\item Foo
\item Bar
\end{itemize}
Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)
[attr.disabled]="valid == true ? true : null"
You have to use null
to remove attr from html element.
$('mainCheckBox').click(function(){
if($(this).prop('checked')){
$('Id or Class of checkbox').prop('checked', true);
}else{
$('Id or Class of checkbox').prop('checked', false);
}
});
for line in f
reads all file to a memory, and that can be a problem.
My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:
with open("blablabla.txt", "r") as fl_in:
while True:
line = fl_in.readline()
if not line:
break
line = line.strip()
# do what You want
Such unexpected problems can appear when you copy the code from a web page or email and the text contains unprintable characters like individual CR or LF and non-breaking spaces.
I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse
class to show/hide divs and Bootstrap's "Collapse Event".
What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div>
based on, lets say, menu buttons on a navbar
. Below is a simple solution to this. The anchor tags (<a>
) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-
All that the JavaScript does is makes all the other <div>
hide using
$(".main-container.collapse").not($(this)).collapse('hide');
when the loaded <div>
is displayed by checking the Collapse event shown.bs.collapse
. Here's the Bootstrap documentation on Collapse Event.
Note: main-container
is just a custom class.
Here it goes-
$(".main-container.collapse").on('shown.bs.collapse', function () { _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
$(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
To achieve "Run as Administrator" functionality I implemented the flag:
-ExecutionPolicy Bypass
Which only seems to take effect when executing Powershell files. So I dropped my command into .ps1 file, run it with -ExecutionPolicy Bypass, and now my scheduled task is behaving as expected.
Program: Powershell.exe
Add Arguments: -ExecutionPolicy Bypass -File C:\pscommandFile.ps1
If you don't have .NET 5.0, extend the DateTime class to include week number.
public static class Extension {
public static int Week(this DateTime date) {
var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
}
It is funny that a lot of answers here from not knowing the languages. This is especially true for C/C++ programmers who have opened and old FORTRAN 77 code and discuss the weaknesses.
I suppose that the speed issue is mostly a question between C/C++ and Fortran. In a Huge code, it always depends on the programmer. There are some features of the language that Fortran outperforms and some features which C does. So, in 2011, no one can really say which one is faster.
About the language itself, Fortran nowadays supports Full OOP features and it is fully backward compatible. I have used the Fortran 2003 thoroughly and I would say it was just delightful to use it. In some aspects, Fortran 2003 is still behind C++ but let's look at the usage. Fortran is mostly used for Numerical Computation, and nobody uses fancy C++ OOP features because of speed reasons. In high performance computing, C++ has almost no place to go(have a look at the MPI standard and you'll see that C++ has been deprecated!).
Nowadays, you can simply do mixed language programming with Fortran and C/C++. There are even interfaces for GTK+ in Fortran. There are free compilers (gfortran, g95) and many excellent commercial ones.
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).
Combination of two previous answers:
var selected = [];
$('#checkboxes input:checked').each(function() {
selected.push($(this).attr('name'));
});
As other have already said, debugger;
is the way to go.
I wrote a small script that you can use from the command line in a browser to set and remove breakpoint right before function call:
http://andrijac.github.io/blog/2014/01/31/javascript-breakpoint/
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
Perfect example is as below:
try:
#x = Hello + 20
x = 10 + 20
except:
print 'I am in except block'
x = 20 + 30
else:
print 'I am in else block'
x += 1
finally:
print 'Finally x = %s' %(x)
Simple workaround I used just now while in a similar situation:
Copy of Sheet1
) into the original worksheet.'Copy of Sheet1'!
with an empty string (i.e. blank).Note: if your sheet name lacks spaces you won't need to use the single quote/apostrophe (').
Your cell references are now copied without being altered.
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0]
, "E" is str[1]
, the first "L" is str[2]
and so on.
I have Done through git bash:
(use "git checkout -- <file>..." to discard changes in working directory)
Response.Cookies
contains the cookies that will be sent back to the browser. If you want to know whether a cookie exists, you should probably look into Request.Cookies
.
Anyway, to see if a cookie exists, you can check Cookies.Get(string)
. However, if you use this method on the Response object and the cookie doesn't exist, then that cookie will be created.
See MSDN Reference for HttpCookieCollection.Get
Method (String)
A modification to @igorsales answer
class Object
def deep_symbolize_keys
return self.inject({}){|memo,(k,v)| memo[k.to_sym] = v.deep_symbolize_keys; memo} if self.is_a? Hash
return self.inject([]){|memo,v | memo << v.deep_symbolize_keys; memo} if self.is_a? Array
return self
end
end
I believe you want bgcolor. Something like this:
document.getElementById("button").bgcolor="#ffffff";
Here are a couple of demos that might help:
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Since Google introduced Android Support Library v7 21.0.0, you can use RecyclerView to scroll items horizontally. The RecyclerView widget is a more advanced and flexible version of ListView.
To use RecyclerView, just add dependency:
com.android.support:recyclerview-v7:23.0.1
Here is a sample:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
MyAdapter adapter = new MyAdapter(myDataset);
recyclerView.setAdapter(adapter);
}
}
More info about RecyclerView:
try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');
Use pandas and the json library:
import pandas as pd
import json
filepath = "inputfile.csv"
output_path = "outputfile.json"
df = pd.read_csv(filepath)
# Create a multiline json
json_list = json.loads(df.to_json(orient = "records"))
with open(output_path, 'w') as f:
for item in json_list:
f.write("%s\n" % item)
This is similar to @Simon Perepelitsa's answer in pure js, but a bit simpler, as it puts one event listener on the document element and checks if the focused element is a number input:
document.addEventListener("wheel", function(event){
if(document.activeElement.type === "number"){
document.activeElement.blur();
}
});
If you want to turn off the value scrolling behaviour on some fields, but not others just do this instead:
document.addEventListener("wheel", function(event){
if(document.activeElement.type === "number" &&
document.activeElement.classList.contains("noscroll"))
{
document.activeElement.blur();
}
});
with this:
<input type="number" class="noscroll"/>
If an input has the noscroll class it wont change on scroll, otherwise everything stays the same.
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
Just came across this and I've implemented Nathan's solution:
add the line (changing the values as required):
export JAVA_OPTS="-Xms512M -Xmx1024M"
to /usr/share/tomcat7/bin/setenv.sh
If that file doesn't exists then create it and
chown root:root it
chmod 755 it
And then restart tomcat and check it with
ps aux | grep logging
Which should just pick up the instance and show the java parms
As @cryptoboy said - check what pip/python version you have installed
demon@UbuntuHP:~$ pip -V
demon@UbuntuHP:~$ pip2 -V
demon@UbuntuHP:~$ pip3 -V
and then check for no-needed libraries in your .local/lib/ folder.
I did backup of settings when I was migrating to newer Kubuntu and in had .local/lib/python2.7/ folder in my home directory. Installed python 3.6. I just removed the old folder and now everything works great!
Minor update on top of Karthik Bose's answer - you can configure git globally, to affect all of your workspaces to behave that way:
git config --global push.default upstream
Greek would need UTF-8 on N column types: aß? ;)
Use range() instead, like the following :
for i in range(len(words)):
...
I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log()
arguments and doesn't give an access to the original function.
Here's my version:
(function (logger) {_x000D_
console.old = console.log;_x000D_
console.log = function () {_x000D_
var output = "", arg, i;_x000D_
_x000D_
for (i = 0; i < arguments.length; i++) {_x000D_
arg = arguments[i];_x000D_
output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
if (_x000D_
typeof arg === "object" &&_x000D_
typeof JSON === "object" &&_x000D_
typeof JSON.stringify === "function"_x000D_
) {_x000D_
output += JSON.stringify(arg); _x000D_
} else {_x000D_
output += arg; _x000D_
}_x000D_
_x000D_
output += "</span> ";_x000D_
}_x000D_
_x000D_
logger.innerHTML += output + "<br>";_x000D_
console.old.apply(undefined, arguments);_x000D_
};_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old()
.
Here's a minified version of the script above to paste inline, just for you:
<script>
!function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span> ";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
(document.body);
</script>
Replace document.body
in the parentheses with whatever element you wish to log into.
Basing my answer on assumption that user just wanted to literaaly convert an int
to char
, for example
Input:
int i = 5;
Output:
char c = '5'
This has been already answered above, however if the integer value i > 10
, then need to use char array
.
char[] c = String.valueOf(i).toCharArray();
It seems like what you want is http://msdn.microsoft.com/en-us/library/ms186323.aspx.
In your example it would be (starts with):
set @isExpress = (CharIndex('Express Edition', @edition) = 1)
Or contains
set @isExpress = (CharIndex('Express Edition', @edition) >= 1)
Popen.communicate
will set the returncode
attribute when it's done(*). Here's the relevant documentation section:
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasn’t terminated yet.
A negative value -N indicates that the child was terminated by signal N (Unix only).
So you can just do (I didn't test it but it should work):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait
.
This requires changes to the frontend JS and the headers sent from the backend.
Frontend
Remove "mode":"no-cors"
in the fetch options.
fetch(
"http://example.com/api/docs",
{
// mode: "no-cors",
method: "GET"
}
)
.then(response => response.text())
.then(data => console.log(data))
Backend
When your server responds to the request, include the CORS headers specifying the origin from where the request is coming. If you don't care about the origin, specify the *
wildcard.
The raw response should include a header like this.
Access-Control-Allow-Origin: *
In some cases when the element is not interactable, sendKeys()
doesn't work and you're likely to encounter an ElementNotInteractableException
.
In such cases, you can opt to execute javascript that sets the values and then can post back.
Example:
url = 'https://www.your_url.com/'
driver = Chrome(executable_path="./chromedriver")
driver.get(url)
username = 'your_username'
password = 'your_password'
#Setting the value of email input field
driver.execute_script(f'var element = document.getElementById("email"); element.value = "{username}";')
#Setting the value of password input field
driver.execute_script(f'var element = document.getElementById("password"); element.value = "{password}";')
#Submitting the form or click the login button also
driver.execute_script(f'document.getElementsByClassName("login_form")[0].submit();')
print(driver.page_source)
Reference:
https://www.quora.com/How-do-I-resolve-the-ElementNotInteractableException-in-Selenium-WebDriver
My favorite is git log -p <filename>
, which will give you a history of all the commits of the given file as well as the diffs for each commit.
I would suggest using the Python Launcher for Windows utility that was introduced into Python 3.3. You can manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.
Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py,
.pyw
, .pyc
, and .pyo
files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX
comments at the beginning of your Python scripts.
In my case I was using ClassName
.
getComputedStyle( document.getElementsByClassName(this_id)) //error
It will also work without 2nd argument " "
.
Here is my complete running code :
function changeFontSize(target) {
var minmax = document.getElementById("minmax");
var computedStyle = window.getComputedStyle
? getComputedStyle(minmax) // Standards
: minmax.currentStyle; // Old IE
var fontSize;
if (computedStyle) { // This will be true on nearly all browsers
fontSize = parseFloat(computedStyle && computedStyle.fontSize);
if (target == "sizePlus") {
if(fontSize<20){
fontSize += 5;
}
} else if (target == "sizeMinus") {
if(fontSize>15){
fontSize -= 5;
}
}
minmax.style.fontSize = fontSize + "px";
}
}
onclick= "changeFontSize(this.id)"
Let suppose few things first
num = 55
Integer to perform bitwise operations (set, get, clear, toggle).
n = 4
0 based bit position to perform bitwise operations.
nth
bit of num right shift num
, n
times. Then perform bitwise AND &
with 1.bit = (num >> n) & 1;
How it works?
0011 0111 (55 in decimal)
>> 4 (right shift 4 times)
-----------------
0000 0011
& 0000 0001 (1 in decimal)
-----------------
=> 0000 0001 (final result)
n
times. Then perform bitwise OR |
operation with num
.num |= (1 << n); // Equivalent to; num = (1 << n) | num;
How it works?
0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
0001 0000
| 0011 0111 (55 in decimal)
-----------------
=> 0001 0000 (final result)
n
times i.e. 1 << n
.~ (1 << n)
.&
operation with the above result and num
. The above three steps together can be written as num & (~ (1 << n))
;num &= (~(1 << n)); // Equivalent to; num = num & (~(1 << n));
How it works?
0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
~ 0001 0000
-----------------
1110 1111
& 0011 0111 (55 in decimal)
-----------------
=> 0010 0111 (final result)
To toggle a bit we use bitwise XOR ^
operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.
Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.
num ^= (1 << n); // Equivalent to; num = num ^ (1 << n);
How it works?
0 ^ 1 => 1
. 1 ^ 1 => 0
. 0000 0001 (1 in decimal)
<< 4 (left shift 4 times)
-----------------
0001 0000
^ 0011 0111 (55 in decimal)
-----------------
=> 0010 0111 (final result)
Recommended reading - Bitwise operator exercises
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source: W3Schools
Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions
Try this:
body{ height: 100%; }
#content {
min-height: 500px;
height: 100%;
}
#footer {
height: 100px;
clear: both !important;
}
The div
element below the content div must have clear:both
.
To Convert file path in String to NSURL, observe the following code
var filePathUrl = NSURL.fileURLWithPath(path)
If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx
use context.Database.BeginTransaction.
using (var context = new BloggingContext()) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { context.Database.ExecuteSqlCommand( @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'" ); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); //Required according to MSDN article throw; //Not in MSDN article, but recommended so the exception still bubbles up } } }
If you update to Bootstrap 3 (BS3), they've exposed a lot of Javascript events that are nice to tie your desired functionality into. In BS3, this code will give all of your dropdown menus the animation effect you are looking for:
// Add slideDown animation to Bootstrap dropdown when expanding.
$('.dropdown').on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// Add slideUp animation to Bootstrap dropdown when collapsing.
$('.dropdown').on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
You can read about BS3 events here and specifically about the dropdown events here.
A version of crossdomain.xml used to be packaged with the HTML5 Boilerplate which is the product of many years of iterative development and combined community knowledge. However, it has since been deleted from the repository. I've copied it verbatim here, and included a link to the commit where it was deleted below.
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!-- Read this: https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>
<!-- Least restrictive policy: -->
<!--
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
-->
</cross-domain-policy>
Deleted in #1881
https://github.com/h5bp/html5-boilerplate/commit/58a2ba81d250301e7b5e3da28ae4c1b42d91b2c2
For those who are looking for the quick one-liner:
plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()])
Or if you are using Latex as the axis text formatter, you have to add one backslash '\'
plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()])
$date = '2014-02-25';
date('D', strtotime($date));
For Java (not php, not javascript, not anyother):
txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")
If you need apache Listen port other than 80, you should add next file under ubuntu
"/etc/apache2/ports.conf"
the list of Listen ports
Listen 80
Listen 81
Listen 82
After you have to go on your Virtual hosts conf file and define next
<VirtualHost *:80>
#...v host 1
</VirtualHost>
<VirtualHost *:81>
#...host 2
</VirtualHost>
<VirtualHost *:82>
#...host 3
</VirtualHost>
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.
Klocwork has a static analysis tool for C#: http://www.klocwork.com
I was able to use nginx to handle the 301 redirect to the aws signin page.
Go to your nginx conf folder (in my case it's /etc/nginx/sites-available
in which I create a symlink to /etc/nginx/sites-enabled
for the enabled conf files).
Then add a redirect path
server {
listen 80;
server_name aws.example.com;
return 301 https://myaccount.signin.aws.amazon.com/console;
}
If you are using nginx, you will most likely have additional server blocks (virtualhosts in apache terminology) to handle your zone apex (example.com) or however you have it setup. Make sure that you have one of them set to be your default server.
server {
listen 80 default_server;
server_name example.com;
# rest of config ...
}
In Route 53, add an A record
for aws.example.com
and set the value to the same IP used for your zone apex.
Note:The cause of the quotes is that when data moves from excel to clipboard it is fully complying with CSV standards which include quoting values that include tabs, new lines etc (and double-quote characters are replaced with two double-quote characters )
So another approach, especially as in OP's case when tabs/new lines are due to the formula, is to use alternate characters for tabs and hard returns. I use ascii Unit Separator =char(31) for tabs and ascii Record Separator =char(30) for new lines.
Then pasting into text editor will not involve the extra CSV rules and you can do a quick search and replace to convert them back again.
If the tabs/new lines are embedded in the data, you can do a search and replace in excel to convert them.
Whether using formula or changing the data, the key to choosing delimiters is never use characters that can be in the actual data. This is why I recommend the low level ascii characters.
You could use something like this to give your button a value:
<?php
if (isset($_POST['submit'])) {
$aSubmitVal = array_keys($_POST['submit'])[0];
echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
<input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>
This will give you the string "SomeValue" as a result
As said elsewhere on here, proguard is good, but what might not be known is that there is also a third-party maven plugin for it here http://pyx4me.com/pyx4me-maven-plugins/proguard-maven-plugin/...I've used them both together and they're very good.
fearless_fool has a great answer for older versions. I just wanted to add that you need to make sure you have all the columns listed. So if you have 3 columns, you need to make sure select acts on 3 columns.
Example: I have 3 columns but I only want to insert 2 columns worth of data. Assume I don't care about the first column because it's a standard integer id. I could do the following...
INSERT INTO 'tablename'
SELECT NULL AS 'column1', 'data1' AS 'column2', 'data2' AS 'column3'
UNION SELECT NULL, 'data3', 'data4'
UNION SELECT NULL, 'data5', 'data6'
UNION SELECT NULL, 'data7', 'data8'
Note: Remember the "select ... union" statement will lose the ordering. (From AG1)
Checking the file extension is not considered best practice. The preferred method of accomplishing this task is by checking the files MIME type.
From PHP:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
The above example will output something similar to which you should be checking.
text/html
image/gif
application/vnd.ms-excel
Although MIME types can also be tricked (edit the first few bytes of a file and modify the magic numbers), it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.
To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn_tagset...
CC: conjunction, coordinating
& 'n and both but either et for less minus neither nor or plus so
therefore times v. versus vs. whether yet
CD: numeral, cardinal
mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
fifteen 271,124 dozen quintillion DM2,000 ...
DT: determiner
all an another any both del each either every half la many much nary
neither no some such that the them these this those
EX: existential there
there
IN: preposition or conjunction, subordinating
astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...
JJ: adjective or numeral, ordinal
third ill-mannered pre-war regrettable oiled calamitous first separable
ectoplasmic battery-powered participatory fourth still-to-be-named
multilingual multi-disciplinary ...
JJR: adjective, comparative
bleaker braver breezier briefer brighter brisker broader bumper busier
calmer cheaper choosier cleaner clearer closer colder commoner costlier
cozier creamier crunchier cuter ...
JJS: adjective, superlative
calmest cheapest choicest classiest cleanest clearest closest commonest
corniest costliest crassest creepiest crudest cutest darkest deadliest
dearest deepest densest dinkiest ...
LS: list item marker
A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
SP-44007 Second Third Three Two * a b c d first five four one six three
two
MD: modal auxiliary
can cannot could couldn't dare may might must need ought shall should
shouldn't will would
NN: noun, common, singular or mass
common-carrier cabbage knuckle-duster Casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...
NNP: noun, proper, singular
Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
Shannon A.K.C. Meltex Liverpool ...
NNS: noun, common, plural
undergraduates scotches bric-a-brac products bodyguards facets coasts
divestitures storehouses designs clubs fragrances averages
subjectivists apprehensions muses factory-jobs ...
PDT: pre-determiner
all both half many quite such sure this
POS: genitive marker
' 's
PRP: pronoun, personal
hers herself him himself hisself it itself me myself one oneself ours
ourselves ownself self she thee theirs them themselves they thou thy us
PRP$: pronoun, possessive
her his mine my our ours their thy your
RB: adverb
occasionally unabatingly maddeningly adventurously professedly
stirringly prominently technologically magisterially predominately
swiftly fiscally pitilessly ...
RBR: adverb, comparative
further gloomier grander graver greater grimmer harder harsher
healthier heavier higher however larger later leaner lengthier less-
perfectly lesser lonelier longer louder lower more ...
RBS: adverb, superlative
best biggest bluntest earliest farthest first furthest hardest
heartiest highest largest least less most nearest second tightest worst
RP: particle
aboard about across along apart around aside at away back before behind
by crop down ever fast for forth from go high i.e. in into just later
low more off on open out over per pie raising start teeth that through
under unto up up-pp upon whole with you
TO: "to" as preposition or infinitive marker
to
UH: interjection
Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
man baby diddle hush sonuvabitch ...
VB: verb, base form
ask assemble assess assign assume atone attention avoid bake balkanize
bank begin behold believe bend benefit bevel beware bless boil bomb
boost brace break bring broil brush build ...
VBD: verb, past tense
dipped pleaded swiped regummed soaked tidied convened halted registered
cushioned exacted snubbed strode aimed adopted belied figgered
speculated wore appreciated contemplated ...
VBG: verb, present participle or gerund
telegraphing stirring focusing angering judging stalling lactating
hankerin' alleging veering capping approaching traveling besieging
encrypting interrupting erasing wincing ...
VBN: verb, past participle
multihulled dilapidated aerosolized chaired languished panelized used
experimented flourished imitated reunifed factored condensed sheared
unsettled primed dubbed desired ...
VBP: verb, present tense, not 3rd person singular
predominate wrap resort sue twist spill cure lengthen brush terminate
appear tend stray glisten obtain comprise detest tease attract
emphasize mold postpone sever return wag ...
VBZ: verb, present tense, 3rd person singular
bases reconstructs marks mixes displeases seals carps weaves snatches
slumps stretches authorizes smolders pictures emerges stockpiles
seduces fizzes uses bolsters slaps speaks pleads ...
WDT: WH-determiner
that what whatever which whichever
WP: WH-pronoun
that what whatever whatsoever which who whom whosoever
WRB: Wh-adverb
how however whence whenever where whereby whereever wherein whereof why
Url.Action("Evil", model)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
mysqldump -h [host] -p -u [user] [database name] > filename.sql
Example in localhost
mysqldump -h localhost -p -u root cookbook > cookbook.sql
In the end I went with eAccelerator - the speed boost, the smaller memory footprint and the fact that is was very easy to install swayed me. It also has a nice web-based front end to clear the cache and provide some stats.
The fact that its not maintained anymore is not an issue for me - it works, and that's all I care about. In the future, if it breaks PHP6 (or whatever), then I'll re-evaluate my decision and probably go with APC simply because its been adopted by the PHP developers (so should be even easier to install)
Add an abstraction layer, for example, a YAML file like in this project https://github.com/larytet/dockerfile-generator which looks like
centos7:
base: centos:centos7
packager: rpm
install:
- $build_essential_centos
- rpm-build
run:
- $get_release
env:
- $environment_vars
A short Python script/make can generate all Dockerfiles from the configuration file.
I had a similar problem and found that if you remove the size definition, it works for some reason.
Remove:
<size
android:width="60dp"
android:height="40dp" />
from the shape.
Let me know if this works!
The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>
you have to reason in terms of hased password:
store the password as md5('bob123');
when bob is register to your app
$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');
then, when bob is logging-in:
$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';
obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql
I was missing modal-dialog
that's why my close modal wasn't working properly.
Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
And on the handler method:
private void WorkerDoWork(int value, string text) {
...
}
<table width="400px">
<tr>
<td width="100px"></td>
<td width="100px"></td>
<td width="100px"></td>
<td width="100px"></td>
</tr>
</table>
For variable number of columns use %
<table width="100%">
<tr>
<td width="(100/x)%"></td>
</tr>
</table>
where 'x' is number of columns
It would work giving the #container div width:80%
(any width less than the main content and have given in %, so that it manages well from both left and right) and giving margin:0px auto;
or margin:0 auto;
(both work fine).
I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__
module, it will be accessible as if a global from any other module that includes __builtin__
-- which is all of them, by default.
a.py contains
print foo
b.py contains
import __builtin__
__builtin__.foo = 1
import a
The result is that "1" is printed.
Edit: The __builtin__
module is available as the local symbol __builtins__
-- that's the reason for the discrepancy between two of these answers. Also note that __builtin__
has been renamed to builtins
in python3.
You just need to set background and give previous.xml file in background of button in your layout file.
<Button
android:id="@+id/button1"
android:background="@drawable/previous"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
and done.Edit Following is previous.xml file in drawable directory
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;
/* Write an application that prompts the user for a String that contains at least
* five letters and at least five digits. Continuously re-prompt the user until a
* valid String is entered. Display a message indicating whether the user was
* successful or did not enter enough digits, letters, or both.
*/
public class FiveLettersAndDigits {
private static String readIn() { // read input from stdin
StringBuilder sb = new StringBuilder();
int c = 0;
try { // do not use try-with-resources. We don't want to close the stdin stream
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((c = reader.read()) != 0) { // read all characters until null
// We don't want new lines, although we must consume them.
if (c != 13 && c != 10) {
sb.append((char) c);
} else {
break; // break on new line (or else the loop won't terminate)
}
}
// reader.readLine(); // get the trailing new line
} catch (IOException ex) {
System.err.println("Failed to read user input!");
ex.printStackTrace(System.err);
}
return sb.toString().trim();
}
/**
* Check the given input against a pattern
*
* @return the number of matches
*/
private static int getitemCount(String input, String pattern) {
int count = 0;
try {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
while (m.find()) { // count the number of times the pattern matches
count++;
}
} catch (PatternSyntaxException ex) {
System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
ex.printStackTrace(System.err);
}
return count;
}
private static String reprompt() {
System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");
String in = readIn();
return in;
}
public static void main(String[] args) {
int letters = 0, digits = 0;
String in = null;
System.out.print("Please enter five letters and five digits in any order: ");
in = readIn();
while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
// count the letters and numbers. If there are enough, this loop won't happen again.
letters = getitemCount(in, "[A-Za-z]");
digits = getitemCount(in, "[0-9]");
if (letters < 5 || digits < 5) {
in = reprompt(); // reset in case we need to go around again.
}
} else {
in = reprompt();
}
}
}
}
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
$('form[name="frmSave"]')
is correct. You mentioned you thought this would get all children with the name frmsave
inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');
$('form[name="frmSave"]')
literally means find all forms with the name frmSave
, because there is no combinator involved.
One possible could be like this,
HTML
<div class="box-left-mini">
<div class="front">this div is infront</div>
<div class="behind">
this div is behind
</div>
</div>
CSS
.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
background-color:lightgreen;
}
.behind{
background-color:grey;
position:absolute;
width:100%;
height:100%;
top:0;
z-index:-1;
}
But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.
use this command:
git pull --allow-unrelated-histories <nick name of repository> <branch name>
like:
git pull --allow-unrelated-histories origin master
this error occurs when projects don't have any common ancestor.
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
I feel you should be using the Consumer interface instead of Function<T, R>
.
A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)
In your case, you can create a consumer elsewhere in your code like this:
Consumer<Integer> myFunction = x -> {
System.out.println("processing value: " + x);
.... do some more things with "x" which returns nothing...
}
Then you can replace your myForEach
code with below snippet:
public static void myForEach(List<Integer> list, Consumer<Integer> myFunction)
{
list.forEach(x->myFunction.accept(x));
}
You treat myFunction as a first-class object.
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
BK-Trees, or Burkhard-Keller Trees are a tree-based data structure which can be used to quickly find near-matches to a string.
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
This is one of those things that can be difficult to search for if you don't already know where to look.
[
is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.
There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.
[
is equivalent to the test
command, except that [
requires ]
as its last argument, and test
does not.
Assuming the bash documentation is installed on your system, if you type info bash
and search for 'test'
or '['
(the apostrophes are part of the search), you'll find the documentation for the [
command, also known as the test
command. If you use man bash
instead of info bash
, search for ^ *test
(the word test
at the beginning of a line, following some number of spaces).
Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne
, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, !=
is the string inequality operator.
You can also find bash documentation on the web.
test
and [
)-ne
is under "arg1 OP arg2")test
The official definition of the test
command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).
This line of yours:
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
Requires an @
symbol before %
like this:
<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>
I did find this somewhere. Can't remember where though... probably on StackOverflow :)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Now you may see trash icon and DELETE PROJECT button.
The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.
If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.
The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.
You can use a BehaviorSubject
within a facade service then subscribe to that subject in any component and when an event happens to trigger a change in data call .next()
on it. Make sure to close out those subscriptions within the on destroy lifecycle hook.
data-api.facade.ts
@Injectable({
providedIn: 'root'
})
export class DataApiFacade {
currentTabIndex: BehaviorSubject<number> = new BehaviorSubject(0);
}
some.component.ts
constructor(private dataApiFacade: DataApiFacade){}
ngOnInit(): void {
this.dataApiFacade.currentTabIndex
.pipe(takeUntil(this.destroy$))
.subscribe(value => {
if (value) {
this.currentTabIndex = value;
}
});
}
setTabView(event: MatTabChangeEvent) {
this.dataApiFacade.currentTabIndex.next(event.index);
}
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.complete();
}
Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
$headers = array(
'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
will not work.. use $(window)
instead
$(window).on('shown.bs.modal', function() {
$('#code').modal('show');
alert('shown');
});
$(window).on('hidden.bs.modal', function() {
$('#code').modal('hide');
alert('hidden');
});
Here is three ways that you can easily copy files with single line of code!
Java7:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Appache Commons IO:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Guava :
private static void copyFileUsingGuava(File source,File dest) throws IOException{
Files.copy(source,dest);
}
Whilst you can of course use the base64
module, you can also to use the codecs
module (referred to in your error message) for binary encodings (meaning non-standard & non-text encodings).
For example:
import codecs
my_bytes = b"Hello World!"
codecs.encode(my_bytes, "base64")
codecs.encode(my_bytes, "hex")
codecs.encode(my_bytes, "zip")
codecs.encode(my_bytes, "bz2")
This can come in useful for large data as you can chain them to get compressed and json-serializable values:
my_large_bytes = my_bytes * 10000
codecs.decode(
codecs.encode(
codecs.encode(
my_large_bytes,
"zip"
),
"base64"),
"utf8"
)
Refs:
A good explanation of how BFS computes shortest paths, accompanied by the most efficient simple BFS algorithm of which I'm aware and also by working code, is provided in the following peer-reviewed paper:
https://queue.acm.org/detail.cfm?id=3424304
The paper explains how BFS computes a shortest-paths tree represented by per-vertex parent pointers, and how to recover a particular shortest path between any two vertices from the parent pointers. The explanation of BFS takes three forms: prose, pseudocode, and a working C program.
The paper also describes "Efficient BFS" (E-BFS), a simple variant of classic textbook BFS that improves its efficiency. In the asymptotic analysis, running time improves from Theta(V+E) to Omega(V). In words: classic BFS always runs in time proportional to the number of vertices plus the number of edges, whereas E-BFS sometimes runs in time proportional to the number of vertices alone, which can be much smaller. In practice E-BFS can be much faster, depending on the input graph. E-BFS sometimes offers no advantage over classic BFS but it's never much slower.
Remarkably, despites its simplicity E-BFS appears not to be widely known.
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
This Code is for New Java Learners:
private String textDataFromFile;
public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {
BufferedReader bufferReader = new BufferedReader (new InputStreamReader(myInputStream));
StringBuilder stringBuilder = new StringBuilder();
String eachStringLine;
while((eachStringLine=bufferReader.readLine()) != null){
stringBuilder.append(eachStringLine).append("\n");
}
textDataFromFile = stringBuilder.toString();
return textDataFromFile;
}
There is no built-in way. You can have MyClass implement the IClonable
interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.
For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.
Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.
As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your .vimrc
):
filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
The help files take a bit of time to get used to, but the more you read, the better Vim gets:
:help smartindent
Even better, you can embed these settings in your source for portability:
:help auto-setting
To see your current settings:
:set all
As graywh points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:
:help C-indenting
$('#tableId').on('draw.dt', function() {
//This will get called when data table data gets redrawn to the table.
});
An idempotent operation produces the result in the same state even if you call it more than once, provided you pass in the same parameters.
I have struggled with the matplotlib trimming methods, so I've now just made a function to do this via a bash
call to ImageMagick
's mogrify command, which works well and gets all extra white space off the figure's edge. This requires that you are using UNIX/Linux, are using the bash
shell, and have ImageMagick
installed.
Just throw a call to this after your savefig()
call.
def autocrop_img(filename):
'''Call ImageMagick mogrify from bash to autocrop image'''
import subprocess
import os
cwd, img_name = os.path.split(filename)
bashcmd = 'mogrify -trim %s' % img_name
process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)
If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:
mkdir %windir%\Sun\Java\Deployment
Create a file deployment.config with the content:
deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE
Create a file deployment.properties
deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites
Create a file exception.sites
http://example1.com
http://example2.com/path/to/specific/directory/
Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in
You can try adding ANDROID_PATH
export ANDROID_HOME=/Users/<username>/Library/Android/sdk/
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
If you don’t want to mutate your data, consider this function...
renameProp = (oldProp, newProp, { [oldProp]: old, ...others }) => ({
[newProp]: old,
...others
})
A thorough explanation by Yazeed Bzadough https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
Here is a typescript friendly version:
// These generics are inferred, do not pass them in.
export const renameKey = <
OldKey extends keyof T,
NewKey extends string,
T extends Record<string, unknown>
>(
oldKey: OldKey,
newKey: NewKey extends keyof T ? never : NewKey,
userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
const { [oldKey]: value, ...common } = userObject
return {
...common,
...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
}
}
It will prevent you from clobbering an existing key or renaming it to the same thing
In Windows, you can follow these steps which worked for me.
git config --system core.longpaths true
This will allow accessing long paths globally
And now you can clone the repository with no issues with long paths
my_list = [1,2,3,4,5]
len(my_list)
# 5
The same works for tuples:
my_tuple = (1,2,3,4,5)
len(my_tuple)
# 5
And strings, which are really just arrays of characters:
my_string = 'hello world'
len(my_string)
# 11
It was intentionally done this way so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public .length()
method, instead you can just check the len()
of anything that implements the 'magic' __len__()
method.
Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length()
method while another type uses a .length
property, while yet another uses .count()
. Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.
The functional nature of len()
also lends itself well to functional styles of programming.
lengths = map(len, list_of_containers)
With [email protected] or later you can install types with:
npm install -D @types/jasmine
Then import the types automatically using the types
option in tsconfig.json
:
"types": ["jasmine"],
This solution does not require import {} from 'jasmine';
in each spec file.
There is another option that hasn't been explored here: declaring Xerces dependencies in Maven as optional:
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>...</version>
<optional>true</optional>
</dependency>
Basically what this does is to force all dependents to declare their version of Xerces or their project won't compile. If they want to override this dependency, they are welcome to do so, but then they will own the potential problem.
This creates a strong incentive for downstream projects to:
Not all developers keep track of newly introduced dependencies (e.g. with mvn dependency:tree
). This approach will immediately bring the matter to their attention.
It works quite well at our organization. Before its introduction, we used to live in the same hell the OP is describing.
That 'u' is part of the external representation of the string, meaning it's a Unicode string as opposed to a byte string. It's not in the string, it's part of the type.
As an example, you can create a new Unicode string literal by using the same synax. For instance:
>>> sandwich = u"smörgås"
>>> sandwich
u'sm\xf6rg\xe5s'
This creates a new Unicode string whose value is the Swedish word for sandwich. You can see that the non-English characters are represented by their Unicode code points, ö is \xf6
and å is \xe5
. The 'u' prefix appears just like in your example to signify that this string holds Unicode text.
To get rid of those, you need to encode the Unicode string into some byte-oriented representation, such as UTF-8. You can do that with e.g.:
>>> sandwich.encode("utf-8")
'sm\xc3\xb6rg\xc3\xa5s'
Here, we get a new string without the prefix 'u', since this is a byte string. It contains the bytes representing the characters of the Unicode string, with the Swedish characters resulting in multiple bytes due to the wonders of the UTF-8 encoding.
SubProcess module:
http://docs.python.org/dev/library/subprocess.html#using-the-subprocess-module
import subprocess
subprocess.Popen("script2.py 1", shell=True)
With this, you can also redirect stdin, stdout, and stderr.
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
In the case you need to remove line breaks from the begin or end of the string, you may use this:
UPDATE table
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );
Have in mind that the hat ^
means the begin of the string and the dollar sign $
means the end of the string.
Hope it help someone.
Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.
You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.
See below sample code that returns the browser name and browser version.
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
Browser browser = userAgent.getBrowser();
String browserName = browser.getName();
//or
// String browserName = browser.getGroup().getName();
Version browserVersion = userAgent.getBrowserVersion();
System.out.println("The user is using browser " + browserName + " - version " + browserVersion);
Did you remember to include the closing brace in main?
#include <iostream>
#include "Attack.h"
using namespace std;
int main()
{
Attack attackObj;
attackObj.printShiz();
}
3 steps:
Ex:
@font-face {_x000D_
font-family: 'Open Sans';_x000D_
font-style: italic;_x000D_
font-weight: 400;_x000D_
src: local('Open Sans Italic'), local('OpenSans-Italic'), url(http://fonts.gstatic.com/s/opensans/v14/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2) format('woff2');_x000D_
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;_x000D_
}
_x000D_
Look at src: -> url. Download http://fonts.gstatic.com/s/opensans/v14/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2 and save to fonts directory. After that change url to all your downloaded file. Now it will be look like
@font-face {_x000D_
font-family: 'Open Sans';_x000D_
font-style: italic;_x000D_
font-weight: 400;_x000D_
src: local('Open Sans Italic'), local('OpenSans-Italic'), url(fonts/xjAJXh38I15wypJXxuGMBvZraR2Tg8w2lzm7kLNL0-w.woff2) format('woff2');_x000D_
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;_x000D_
}
_x000D_
** Download all fonts contain .css file Hope it will help u
The NVARCHAR2 datatype was introduced by Oracle for databases that want to use Unicode for some columns while keeping another character set for the rest of the database (which uses VARCHAR2). The NVARCHAR2 is a Unicode-only datatype.
One reason you may want to use NVARCHAR2 might be that your DB uses a non-Unicode character set and you still want to be able to store Unicode data for some columns without changing the primary character set. Another reason might be that you want to use two Unicode character set (AL32UTF8 for data that comes mostly from western Europe, AL16UTF16 for data that comes mostly from Asia for example) because different character sets won't store the same data equally efficiently.
Both columns in your example (Unicode VARCHAR2(10 CHAR)
and NVARCHAR2(10)
) would be able to store the same data, however the byte storage will be different. Some strings may be stored more efficiently in one or the other.
Note also that some features won't work with NVARCHAR2, see this SO question:
A good approach is to use a mixin to control stroke colour and fill colour. My svgs are used as icons.
@mixin icon($color, $hoverColor) {
svg {
fill: $color;
circle, line, path {
fill: $color
}
&:hover {
fill: $hoverColor;
circle, line, path {
fill: $hoverColor;
}
}
}
}
You can then do the following in your scss:
.container {
@include icon(white, blue);
}
Server 2008:
When in SSMS connected to server1.DB1 and try:
SELECT * FROM
[server2].[DB2].[dbo].[table1]
as others noted, if it doesn't work it's because the server isn't linked.
I get the error:
Could not find server DB2 in sys.servers. Verify that the correct server name was specified. If necessary, execute stored procedure sp_addlinkedserver to add the server to sys.servers.
To add the server:
reference: To add server using sp_addlinkedserver Link: [1]: To add server using sp_addlinkedserver
To see what is in your sys.servers just query it:
SELECT * FROM [sys].[servers]
You need to fix your include_path
system variable to point to the correct location.
To fix it edit the php.ini
file. In that file you will find a line that says, "include_path = ...
". (You can find out what the location of php.ini by running phpinfo()
on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR
" to read "C:\xampplite\php\pear
". Make sure to leave the semi-colons before and/or after the line in place.
Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.
I currently use Corona for business applications with great success. As far as games go, I'm under the impression that it doesn't provide the performance that some of the other cross-platform development engines do. It is worth noting that Carlos (founder of Ansca Mobile/Corona SDK) has started another company on a competing engine; Lanica Platino Engine for Appcelerator Titanium. While I haven't worked with this personally, it does look promising. Keep in mind, however, that it comes with a $999/yr price tag.
All that said, I have been researching Moai for a little while now (since I am already familiar with Lua syntax) and it does seem promising. The fact that it can compile for multiple platforms, not limited to mobile environments, is appealing.
Multimedia Fusion 2 is also a worth contender, considering the complexity of games produced and the performance realized from them. Vincere Totus Astrum (http://gamesare.com) comes to mind.
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
cmd (command):
netdom renamecomputer %COMPUTERNAME% /Newname "NEW-NAME"
powershell (windows 2008/2012):
netdom renamecomputer "$env:COMPUTERNAME" /Newname "NEW-NAME"
after that, you need to reboot your computer.
Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet()
method gives you a Set of all the keys in the Map.
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key: map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
Also, your 1st for-loop looks odd to me: -
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
You are iterating over your list, and assigning each element to the same reference - map
, which will overwrite all the previous values.. All you will be having is the last map in your list.
EDIT: -
You can also use entrySet
if you want both key and value for your map. That would be better bet for you: -
Map<String, Integer> map = new HashMap<String, Integer>();
for(Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design
one more time. For now, as the code stands, it is very difficult to understand what its trying to do.
for 50% element
width: 50%;
display: block;
float: right;
margin-right: 25%;
You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:
# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful
On Ubuntu/Debian you can configure headers in the file
/etc/apache2/conf-enabled/security.conf
#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"
#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"
Note: This is the bottom part of the file. Only the last three entries are CSP settings.
The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.
Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.
While you're at it you could take a look at the other header settings and install mod_security
Further reading:
https://developers.google.com/web/fundamentals/security/csp/
var ticket = FormsAuthentication.Decrypt(
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket.Expired)
{
throw new InvalidOperationException("Ticket expired.");
}
IPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));
The following function splits the string and returns the name and extension no matter how many dots there are in the extension. It returns an empty string for the extension if there is none. Names that start with dots and/or white space work also.
function basext(name) {
name = name.trim()
const match = name.match(/^(\.+)/)
let prefix = ''
if (match) {
prefix = match[0]
name = name.replace(prefix, '')
}
const index = name.indexOf('.')
const ext = name.substring(index + 1)
const base = name.substring(0, index) || ext
return [prefix + base, base === ext ? '' : ext]
}
const [base, ext] = basext('hello.txt')
Look at git stash to put all of your local changes into a "stash file" and revert to the last commit. At that point, you can apply your stashed changes, or discard them.
This has happened to me. My issue was caused when I didn't mount Docker file system correctly, so I configured the Disk Image Location and re-bind File sharing mount, and this now worked correctly. For reference, I use Docker Desktop in Windows.
thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
I got same problem... and I did it.
My code before:
<link rel="stylesheet" href="../css/style.default.css" type="text/css" />
And the problem solved after I changed my code into this:
<link rel="stylesheet" href="css/style.default.css" type="text/css" />
So I think "href=../"
is not allowed, because I don't have problem when I use "../"
in "src=../"
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
You can be more precise with CSS background-origin:
background-origin: content-box;
This will make image respect the padding of the box.
Add Beyond Compare as your difftool in Git and add an alias for diffdir as:
git config --global alias.diffdir = "difftool --dir-diff --tool=bc3 --no-prompt"
Get the gitdiff as:
git diffdir 4bc7ba80edf6 7f566710c7
Reference: Compare entire directories w git difftool + Beyond Compare
I you have the char '9'
, it will store its ASCII code, so to get the int value, you have 2 ways
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
or
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
And it fact, this works also :
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
You store the 9
code, which corresponds to a horizontal tab
(you can see when print as String
, bu you can also use it as int
as you see above
If you are using a Stored Procedure:
ALTER PROCEDURE <Name>
(
@PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + @PartialName + '%'
If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!
cmd /c start iexplore "http://your/url.html"
cmd /c means executing a command and then exit.
You can learn the functions of your switches by typing in your command prompt
anycmd /?
I had to do something like this just now. I ended up doing:
function newWaitImg(id) {
var img = {
"id" : id,
"state" : "on",
"hide" : function () {
$(this.id).hide();
this.state = "off";
},
"show" : function () {
$(this.id).show();
this.state = "on";
},
"toggle" : function () {
if (this.state == "on") {
this.hide();
} else {
this.show();
}
}
};
};
.
.
.
var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the inverse cumulative distribution function (inv_cdf
- inverse of the cdf
), also known as the quantile function or the percent-point function for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943
Which can be simplified for the standard normal distribution (mu = 0
and sigma = 1
):
NormalDist().inv_cdf(0.95)
# 1.6448536269514715
If you have multiple applications on heroku and want to add changes to a particular application, run the following command : heroku git:remote -a appname and then run the following. 1) git add . 2)git commit -m "changes" 3)git push heroku master