I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.
<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);
This is the Matcher used:
(?<!EXCEPTION)(\.js)
What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
As documented in /usr/src/linux/Documentation/block/switching-sched.txt
, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.
# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq
Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:
noop
is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resourcesdeadline
is a lightweight scheduler which tries to put a hard limit on latencycfq
tries to maintain system-wide fairness of I/O bandwidthThe default was anticipatory
for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq
became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory
has a long history of being tunable for best performance on these workloads, and deadline
very quickly passes all requests through to the underlying device.
chmod a+x
modifies the argument's mode while chmod 755
sets it. Try both variants on something that has full or no permissions and you will notice the difference.
//Calling
[self showMessage:@"There is no internet connection for this device"
withTitle:@"Error"];
//Method
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
If you want to use this alert in NSObject class you should use like:
-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
}];
});
}
If you want to act as the enumeration rolls you should yield each item.
public static class EnumerableExtensions
{
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (var item in enumeration)
{
action(item);
yield return item;
}
}
}
Take note that if you have multiple versions of Python installed on your computer, you may have a few versions of pip associated with each.
Depending on your associations, you might need to be very cautious of what pip command you use:
pip3 list
Worked for me, where I'm running Python3.4. Simply using pip list
returned the error The program 'pip' is currently not installed. You can install it by typing: sudo apt-get install python-pip
.
It's as simple as the one below, and works like a charm.
My solution perfectly answers your question: How to make JQuery-AJAX request synchronous
Set ajax to synchronous before the ajax call, and then reset it after your ajax call:
$.ajaxSetup({async: false});
$ajax({ajax call....});
$.ajaxSetup({async: true});
In your case it would look like this:
$.ajaxSetup({async: false});
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
if(arr == "Successful") {
return true;
} else {
return false;
}
}
});
$.ajaxSetup({async: true});
I hope it helps :)
Check out the Node js modules wiki page. They have listed all the templating engines supporting node.js.
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
My way of doing it:
from time import time
def printTime(start):
end = time()
duration = end - start
if duration < 60:
return "used: " + str(round(duration, 2)) + "s."
else:
mins = int(duration / 60)
secs = round(duration % 60, 2)
if mins < 60:
return "used: " + str(mins) + "m " + str(secs) + "s."
else:
hours = int(duration / 3600)
mins = mins % 60
return "used: " + str(hours) + "h " + str(mins) + "m " + str(secs) + "s."
Set a variable as start = time()
before execute the function/loops, and printTime(start)
right after the block.
and you got the answer.
Update 2018
You should be able to just set it using CSS like this..
.dropdown-menu {
min-width:???px;
}
This works in both Bootstrap 3 and Bootstrap 4.0.0 (demo).
A no extra CSS option in Bootstrap 4 is using the sizing utils to change the width. For example, here the w-100 (width:100%) class is used for the dropdown menu to fill the width of it's parent....
<ul class="dropdown-menu w-100">
<li><a class="nav-link" href="#">Choice1</a></li>
<li><a class="nav-link" href="#">Choice2</a></li>
<li><a class="nav-link" href="#">Choice3</a></li>
</ul>
In Ruby 2.1 and higher you can do
{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4
is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:
https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.
Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin
https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr
contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.
In my case I had bone-headedly used commas as separators. To use your example I did this:
a.out: vertex.o, edge.o, elist.o, main.o, vlist.o, enode.o, vnode.o
g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
Changing it to the equivalent of
a.out: vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
fixed it.
Based on Arthur Halma's answer, I did the following that works correctly with Apple's, Android & iOS mail.
define("EMAIL_DOMAIN", "yourdomain.com");
public function send_email_html($to, $from, $subject, $html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$uniqid = md5(uniqid(time()));
$boundary = "--==_mimepart_".$uniqid;
$headers = "From: ".$from."\n".
'Reply-to: '.$from."\n".
'Return-Path: '.$from."\n".
'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
'Mime-Version: 1.0'."\n".
'Content-Type: multipart/related;'."\n".
' boundary='.$boundary.";\n".
' charset=UTF-8'."\n".
'X-Mailer: PHP/' . phpversion();
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'UTF-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if (file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
mail($to, $subject, $multipart, $headers);
}
A couple of other scenarios where background-image
should be used:
img
, the image leaks out of the rounded corners.Try Like this.
tv1.setText(" " + Integer.toString(X[i]) + "\n" + "+" + " " + Integer.toString(Y[i]));
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
$computer,$Speed,$Regcheck
will create an array, and run out-file
ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:
"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
Your question is missing most of the necessary information, so I'm going to make some assumptions:
The answer would be:
=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")
COUNTBLANK
tells you how many cells are unfilled or set to "".
IF
lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<>
means "not equal to".
The equation says that if the number of blank cells in the range F16:G16
(your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank(""
).
When you copy this equation to new cells in column H other than H16
, it will update the row references so the proper rows for the credit and debit amounts are looked at.
CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15
, would report blank, which is treated like a 0 in this case.
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
You can use argv[0] and analyze the PATH environment variable. Look at : A sample of a program that can find itself
No, these defines are compiler dependent. What you can do, use your own set of defines, and set them on the Makefile. See this thread for more info.
You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.
example:
string str2 = "_";
string strData = "bla_bla_blabla_bla_";
size_t pos = 0,pos2;
while ((pos = strData.find(str2, pos)) < strData.length())
{
printf("\n%d", pos);
pos += str2.length();
}
Or just do that:
var app = req.app
inside the Middleware you are using for these routes. Like that:
router.use( (req,res,next) => {
app = req.app;
next();
});
In case you develop applications for Android you should try out the TimingLogger
class.
Take a look at these articles describing the usage of the TimingLogger
helper class:
Key input is a predefined event. You can catch events by attaching event_sequence
(s) to event_handle
(s) by using one or multiple of the existing binding methods(bind
, bind_class
, tag_bind
, bind_all
). In order to do that:
event_handle
methodevent_sequence
) that fits your case from an events listWhen an event happens, all of those binding methods implicitly calls the event_handle
method while passing an Event
object, which includes information about specifics of the event that happened, as the argument.
In order to detect the key input, one could first catch all the '<KeyPress>'
or '<KeyRelease>'
events and then find out the particular key used by making use of event.keysym
attribute.
Below is an example using bind
to catch both '<KeyPress>'
and '<KeyRelease>'
events on a particular widget(root
):
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def event_handle(event):
# Replace the window's title with event.type: input key
root.title("{}: {}".format(str(event.type), event.keysym))
if __name__ == '__main__':
root = tk.Tk()
event_sequence = '<KeyPress>'
root.bind(event_sequence, event_handle)
root.bind('<KeyRelease>', event_handle)
root.mainloop()
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
you should try:
request.url
It suppose to work always, even on localhost (just did it).
I thought about using the (ngModelChange) method, then thought about the FormBuilder method, and finally settled on a variation of Method 3. This saves decorating the template with extra attributes and automatically picks up changes to the model - reducing the possibility of forgetting something with Method 1 or 2.
Simplifying Method 3 a bit...
oldPerson = JSON.parse(JSON.stringify(this.person));
ngDoCheck(): void {
if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
this.doSomething();
this.oldPerson = JSON.parse(JSON.stringify(this.person));
}
}
You could add a timeout to only call doSomething() after x number of milliseconds to simulate debounce.
oldPerson = JSON.parse(JSON.stringify(this.person));
ngDoCheck(): void {
if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
if (timeOut) clearTimeout(timeOut);
let timeOut = setTimeout(this.doSomething(), 2000);
this.oldPerson = JSON.parse(JSON.stringify(this.person));
}
}
I think this is what the OP really wants:
array = -1:0.1:10
for i=1:numel(array)
disp(array(i))
end
Using netbeans New Entity Classes from Database with a mysql auto_increment column, creates you an attribute with the following hibernate.hbm.xml: id is auto increment
Another way of hiding the container div when a click happens in a not children element;
$(document).on('click', function(e) {
if(!$.contains($('.yourContainer').get(0), e.target)) {
$('.yourContainer').hide();
}
});
urllib
is a standard library, you do not have to install it. Simply import urllib
Short
echo pathinfo(__FILE__)['filename']; // since php 5.2
In Spring you can escape the html from JSP pages generated by <form>
tags. This closes off a lot avenues for XSS attacks, and can be done automatically in three ways:
For the entire application in the web.xml
file:
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
For all forms on a given page in the file itself:
<spring:htmlEscape defaultHtmlEscape="true" />
For each form:
<form:input path="someFormField" htmlEscape="true" />
All content in src/test/resources
is copied into target/test-classes
folder. So to get file from test resources during maven build you have to load it from test-classes
folder, like that:
Paths.get(
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
).resolve(
Paths.get("somefile")
).toFile()
Break down:
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
- give you URI to target/test-classes
.resolve(Paths.get("somefile"))
- resolves someFile
to target/test-classes
folder.Original anwser is taken from this
Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.
$("#button_1, #button_2").on("click", function(e) {
e.preventDefault();
$.ajax({type: "POST",
url: "/pages/test/",
data: { id: $(this).val(), access_token: $("#access_token").val() },
success:function(result) {
alert('ok');
},
error:function(result) {
alert('error');
}
});
});
You need to escape it. (Using Python 3 print function):
>>> print("The boy said \"Hello!\" to the girl")
The boy said "Hello!" to the girl
>>> print('Her name\'s Jenny.')
Her name's Jenny.
See the python page for string literals.
dude do like this
case R.id.someValue :
case R.id.someOtherValue :
//do stuff
This is same as using OR operator between two values Because of this case operator isn't there in switch case
I always use an autonumber or identity field.
I worked for a client who had used SSN as a primary key and then because of HIPAA regulations was forced to change to a "MemberID" and it caused a ton of problems when updating the foreign keys in related tables. Sticking to a consistent standard of an identity column has helped me avoid a similar problem in all of my projects.
To click the "ok" button in an alert box:
driver.switchTo().alert().accept();
FWIW, git rebase interactive now has a "reword" option, which makes this much less painful!
If you need generate numbers with intervals, it can be just like that:
Integer[] arr = new Integer[((int) (Math.random() * (16 - 30) + 30))];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));`
The result:
[1, 10, 2, 4, 9, 8, 7, 13, 18, 17, 5, 21, 12, 16, 23, 20, 6, 0, 22, 14, 24, 15, 3, 11, 19]
Note:
If you need that the zero does not leave you could put an "if"
Ok, I have another solution for one specific case: if you use WINDOWS 10, and you updated it recently (with Anniversary Update package) you need to follow the steps below:
Windows Event Viewer
- press Win+R and type: eventvwr
, then press ENTER.Windows Event Viewer
click on Windows Logs
-> Application
.IIS-W3SVC-WP
in middle window.The Module DLL >>path-to-DLL<< failed to load. The data is the error.
Control Panel
-> Program and Features
and depending on which dll cannot be load you need to repair another module:
rewrite.dll
- find IIS URL Rewrite Module 2 and click Change
->Repair
aspnetcore.dll
- find Microsoft .NET Core 1.0.0 - VS 2015 Tooling ... and click Change
->Repair
.Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)
public String CleanStringToLettersNumbers(String data)
{
var result = String.Empty;
foreach (var item in data)
{
var c = '_';
if ((int)item >= 97 && (int)item <= 122 ||
(int)item >= 65 && (int)item <= 90 ||
(int)item >= 48 && (int)item <= 57 ||
(int)item == 32)
{
c = item;
}
result = result + c;
}
return result;
}
For those interested, here's an alternative to invoking Array.join:
var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);
The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply() for more information.
The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.
Ok, there are a bunch of ways you can do that. Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
As for your regexp I guess it should be
^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}
But in general the presumption is not correct because one might enter something like ++44 20 1234 56789 or +44 (0) 1234 567890 it is better to do something like this
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) { return true; }
this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.
As per the DOM structure you can use below code:
var x = document.getElementById('mySelect');
var txt = "";
var val = "";
for (var i = 0; i < x.length; i++) {
txt +=x[i].text + ",";
val +=x[i].value + ",";
}
just type ./a in the shell
DBeaver Community Edition (dbeaver.io) makes it trivial to connect to a database, then import a CSV file for upload to a PostgreSQL database. It also makes it easy to issue queries, retrieve data, and download result sets to CSV, JSON, SQL, or other common data formats.
It is a FOSS multi-platform database tool for SQL programmers, DBAs and analysts that supports all popular databases: MySQL, PostgreSQL, SQLite, Oracle, DB2, SQL Server, Sybase, MS Access, Teradata, Firebird, Hive, Presto, etc. It's a viable FOSS competitor to TOAD for Postgres, TOAD for SQL Server, or Toad for Oracle.
I have no affiliation with DBeaver. I love the price (FREE!) and full functionality, but I wish they would open up this DBeaver/Eclipse application more and make it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the $199 annual subscription just to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, (only to find that DBeaver has probably disabled the ability to add third-party widgets to the DBeaver Community Edition.)
Can DBeaver power users who are Java developers provide some insight about the steps to create analytics widgets to add into the Community Edition of DBeaver?
Dockerfile
is good if you only have one docker file (per-directory). You can use whatever standard you want if you need multiple docker files in the same directory -
if you have a good reason. In a recent project there were AWS docker files and local dev environment files because the environments differed enough:
Dockerfile
Dockerfile.aws
As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:
var _ = require('underscore');
Happy coding!
SELECT
hat,
shoe,
boat,
0 as placeholder
FROM
objects
And '' as placeholder
for strings.
The /
operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.
I have found a solution in Python that is working well !
from math import atan2,degrees
def GetAngleOfLineBetweenTwoPoints(p1, p2):
return degrees(atan2(p2 - p1, 1))
print GetAngleOfLineBetweenTwoPoints(1,3)
As Alexander Jank mentioned <base href="http://www.example.com/default/">
is great. When using sub-domains e.g. default.example.com
base works great, because the JS and CSS loads from the said sub-domain and is accessible to both default.example.com
and example.com/default
When using the root path, and your JS and CSS files are located in example.com/css
, or example.com/js
, then the subdomain has no access and the root of the subdomain is not accessible, except using the base.
Parsing string with moment.js.
const date = '1231231231231' //Example String date
const parsed = moment(+date);
SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').
Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.
If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:
let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';
If ther's a where
statement in your query and/or trying to insert
a value and/or an update
of value which is string use single quote(') for these values like:
let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";
//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error
let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';
//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.
If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:
let query = 'select is, name from accounts where name = \'John\'';
Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:
let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith
//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";
//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';
If need further clearance do follow quotes in JavaScript
One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):
div ul:not(:first-child) {
background-color: #900;
}
If you need to support legacy browsers, or if you are hindered by the :not
selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:
Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:
div ul {
background-color: #900; /* applies to every ul */
}
div ul:first-child {
background-color: transparent; /* limits the scope of the previous rule */
}
When limiting the scope use the default value for each CSS attribute that you are setting.
var size = 0;
var darray = new Array();
function createTable(){
darray[size] = new Array();
darray[size][0] = $("#chqdate").val();
darray[size][1]= $("#chqNo").val();
darray[size][2] = $("#chqNarration").val() ;
darray[size][3]= $("#chqAmount").val();
darray[size][4]= $("#chqMode").val();
}
increase size var after your function.
You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.
You can also use the cdata
package, which uses the concept of (transformation) control table:
# data
wide <- read.table(text="Code Country 1950 1951 1952 1953 1954
AFG Afghanistan 20,249 21,352 22,532 23,557 24,555
ALB Albania 8,097 8,986 10,058 11,123 12,246", header=TRUE, check.names=FALSE)
library(cdata)
# build control table
drec <- data.frame(
Year=as.character(1950:1954),
Value=as.character(1950:1954),
stringsAsFactors=FALSE
)
drec <- cdata::rowrecs_to_blocks_spec(drec, recordKeys=c("Code", "Country"))
# apply control table
cdata::layout_by(drec, wide)
I am currently exploring that package and find it quite accessible. It is designed for much more complicated transformations and includes the backtransformation. There is a tutorial available.
Procedure to get Python Working in XCode 7
Step 1: Setup your Project with a External Build System
Step 1.1: Edit the Project Scheme
Step 2: Specify Python as the executable for the project (shift-command-g) the path should be /usr/bin/python
Step 3: Specify your custom working directory
Step 4: Specify your command line arguments to be the name of your python file. (in this example "test.py")
Step 5: Thankfully thats it!
(debugging can't be added until OSX supports a python debugger?)
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationYour hack of decrementing the count at the end is exactly that -- a hack.
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
Personally, I think in this case, C-style code is perfectly acceptable:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
Edit: Of course, C++ will also let you do something a bit similar:
int main() {
std::ifstream myfile("textexample.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
}
The error:
'int' object has no attribute '__getitem__'
means that you're attempting to apply the index operator []
on an int, not a list. So is col
not a list, even when it should be? Let's start from that.
Look here:
col = [[0 for col in range(5)] for row in range(6)]
Use a different variable name inside, looks like the list comprehension overwrites the col
variable during iteration. (Not during the iteration when you set col
, but during the following ones.)
If you take a look at the result of valeur <= 0.6
, you can see what’s causing this ambiguity:
>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)
So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?
That’s exactly what numpy.any
and numpy.all
do. The former requires at least one true value, the latter requires that all values are true:
>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False
Another way to do it if you "own" the module is to use module_function
.
module UsefulThings
def a
puts "aaay"
end
module_function :a
def b
puts "beee"
end
end
def test
UsefulThings.a
UsefulThings.b # Fails! Not a module method
end
test
You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.
from scipy.stats import linregress
import numpy as np
x = np.array([1,2,3,4,5,6])
y = np.array([2,3,5,6,7,8])
p3 = np.polyfit(x,y,3) # 3rd degree polynomial, you can change it to any degree you want
xp = np.linspace(1,6,6) # 6 means the length of the line
poly_arr = np.polyval(p3,xp)
poly_list = [round(num, 3) for num in list(poly_arr)]
slope, intercept, r_value, p_value, std_err = linregress(x, poly_list)
print(r_value**2)
This is what DocumentFragment
was meant for.
var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);
Instead of using Key_press event you may use Key_down event. You can find this as below
after double clicking here it will automatically this code
private void textbox1_KeyDown(object sender, KeyEventArgs e)
{
}
Problem solved now use as you want.
private void textbox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(" Enter pressed ");
}
}
Try This
$current_file_name = $_SERVER['PHP_SELF'];
echo $current_file_name;
Try Integer.parseInt()
to do this.....
public boolean chkInt(final int[] array){
int key = false;
for (Integer i : array){
try{
Integer.parseInt(i);
key = true;
return key;
}catch(NumberFormatException ex){
key = false;
return key;
}
}
}
class PagesController extends BaseController {
protected $layout = 'layouts.master';
public function index()
{
$this->layout->title = "Home page";
$this->layout->content = View::make('pages/index');
}
}
At the Blade Template file, REMEMBER to use @ in front the variable.
...
<title>{{ $title or '' }}</title>
...
@yield('content')
...
You need to include the getters and setters for all the fields that have been defined in the model Test
class --
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);
Scale down method:
public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
boolean filter) {
float ratio = Math.min(
(float) maxImageSize / realImage.getWidth(),
(float) maxImageSize / realImage.getHeight());
int width = Math.round((float) ratio * realImage.getWidth());
int height = Math.round((float) ratio * realImage.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
height, filter);
return newBitmap;
}
Yes, you can use Type.InvokeMember()
:
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj
doesn't have a property called Name
, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
Split-Path $MyInvocation.MyCommand.Path -Parent
This is working in IE 11 with Bootstrap 4.3. While the other answers were not working in IE11 in my case.
<div class="row mx-auto justify-content-center align-items-center flex-column ">
<div class="col-6">Something </div>
</div>
This is what I do to retain type info:
class Helper {
public static createRaw<T>(TCreator: { new (): T; }, data: any): T
{
return Object.assign(new TCreator(), data);
}
public static create<T>(TCreator: { new (): T; }, data: T): T
{
return this.createRaw(TCreator, data);
}
}
...
it('create helper', () => {
class A {
public data: string;
}
class B {
public data: string;
public getData(): string {
return this.data;
}
}
var str = "foobar";
var a1 = Helper.create<A>(A, {data: str});
expect(a1 instanceof A).toBeTruthy();
expect(a1.data).toBe(str);
var a2 = Helper.create(A, {data: str});
expect(a2 instanceof A).toBeTruthy();
expect(a2.data).toBe(str);
var b1 = Helper.createRaw(B, {data: str});
expect(b1 instanceof B).toBeTruthy();
expect(b1.data).toBe(str);
expect(b1.getData()).toBe(str);
});
Using dep.exe you can list out all the nested dependencies of an entire folder. Combined with unix tools like grep or awk, it can help you to solve your problem
$ dep | awk '{ print $1 " " $2; print $4 " " $5 }' | awk '{ if (length(versions[$1]) == 0) versions[$1] = $2; if (versions[$1] != $2) errors[$1] = $1; } END{ for(e in errors) print e } '
System.Web.Http
This obscure command line runs dep.exe then pipes the output twice to awk to
$ dep myproject/bin | grep -i System\.Web\.Http
MyProject-1.0.0.0 >> System.Web.Http.Web-5.2.3.0 2 ( FooLib-1.0.0.0 )
MyProject-1.0.0.0 >> System.Web.Http.Web-4.0.0.0 2 ( BarLib-1.0.0.0 )
FooLib-1.0.0.0 > System.Web.Http.Web-5.2.3.0 1
BarLib-1.0.0.0 > System.Web.Http.Web-4.0.0.0 1
In this example, the tool would show you that System.Web.Http 5.2.3 comes from your dependency to FooLib whereas the version 4.0.0 comes from BarLib.
Then you have the choice between
If you don't have a unix type shell you'll need to download one before being able to run awk
and grep
. Try one of the following
<?php
header("Location: your url");
exit;
?>
Here is a screenshot:
????????
If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:
df['a']= 'col' + df['a'].str[:]
This approach allows prepend, append, and subset string of df
.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.
By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:
class << self
private
def method_name
...
end
end
class << self
opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.
From the documentation (MySQL 8) :
Type | Maximum length -----------+------------------------------------- TINYTEXT | 255 (2 8−1) bytes TEXT | 65,535 (216−1) bytes = 64 KiB MEDIUMTEXT | 16,777,215 (224−1) bytes = 16 MiB LONGTEXT | 4,294,967,295 (232−1) bytes = 4 GiB
Note that the number of characters that can be stored in your column will depend on the character encoding.
I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.
Spring Boot - Environment @Autowired throws NullPointerException
You may actually mean hovering the element by not clicking, right?
jQuery('#id').click(function()
{
// execute on click
}).hover(function()
{
// execute on hover
});
Clarify your question then we'll be able to understand better.
Simply if an element isn't being clicked on, do a setInterval
to continue the process until clicked.
var checkClick = setInterval(function()
{
// do something when the element hasn't been clicked yet
}, 2000); // every 2 seconds
jQuery('#id').click(function()
{
clearInterval(checkClick); // this is optional, but it will
// clear the interval once the element
// has been clicked on
// do something else
})
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
FWIW, if you'd like to just allow requests directed to any hostname/ip then you can set your binding like so:
<binding protocol="http" bindingInformation="*:80:*" />
I use this binding so that I can load a VM with IE6 and then debug my application.
EDIT: While using IIS Express to debug, the default location for this option's config file is
C:\Users\{User}\Documents\IISExpress\config\applicationhost.config
for an array of objects, I used something like this, while following the custom method for php < 5.4:
$jsArray=array();
//transaction is an array of the class transaction
//which implements the method to_json
foreach($transactions as $tran)
{
$jsArray[]=$tran->to_json();
}
echo json_encode($jsArray);
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
I know this is late, but this is how I normally do it,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");
For me this error was simply because boost wasn't installed so on ubuntu:
sudo apt install build-essential libboost-system-dev libboost-thread-dev libboost-program-options-dev libboost-test-dev
convert Collection into string as comma seperated in Java 8
listOfString object contains ["A","B","C" ,"D"] elements-
listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))
Output is :- 'A','B','C','D'
And Convert Strings Array to List in Java 8
String string[] ={"A","B","C","D"};
List<String> listOfString = Stream.of(string).collect(Collectors.toList());
Start each row with \"-\" to create bullet list.
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).
So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.
You can use StreamReader.ReadToEnd()
,
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.
The group_concat supports its own order by clause
http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/
So you should be able to write:
SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage)
FROM table_views GROUP BY client_id
With ES6 supported also duplicate string
var allLongestStrings = arrayOfStrings => {
let maxLng = Math.max(...arrayOfStrings.map( elem => elem.length))
return arrayOfStrings.filter(elem => elem.length === maxLng)
}
let arrayOfStrings = ["aba", "aa", "ad", "vcd","aba"]
console.log(allLongestStrings(arrayOfStrings))
all u need to do that is set tJAVA_HOME and JDK_HOME environment variables paths for this go my computer properties set path with name JAVA_HOME and JDK_HOME C:\Program Files\Java\jdk1.8.0_25
2018 Update - Might be helpful for future readers:
I am not sure when this was originally introduced in Chrome. But another (easy) way this can be done now in Chrome is via console commands.
For example: (in chrome console type)
getEventListeners($0)
Whereas $0 is the selected element in the DOM.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#0_-_4
From my understanding of the code provided above, it loads the file and does map operation and saves it back. There is no operation that requires shuffle. Also, there is no operation that requires data to be brought to the driver hence tuning anything related to shuffle or driver may have no impact. The driver does have issues when there are too many tasks but this was only till spark 2.0.2 version. There can be two things which are going wrong.
or run suexec and never have to change permissions again.
You mean something like IPhone checkboxes? Try Thomas Reynolds' iOS Checkboxes script:
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() { $(':checkbox').iphoneStyle(); });
Results:
I too was struggling with nested views in Angular.
Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.
Here is an example application that uses multiple levels of views nesting
app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'partials/view1.html',
controller: 'view1.MainController'
})
.state('view1.nestedViews', {
url: '/view1',
views: {
'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
}
})
.state('view2', {
url: '/view2',
})
.state('view3', {
url: '/view3',
})
.state('view4', {
url: '/view4',
});
});
As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.
$this->db->select('count(id) as rows');
$this->db->from('table_name');
$this->db->where('active',1);
$query = $this->db->get();
foreach($query->result() as $r)
{
return $r->rows;
}
You can try this method that is developed by Chucai Yi and Yingli Tian.
They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:
Note: to make the result more robust, you can further merge adjacent boxes together.
Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.
With this, you can get recognized texts like:
If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.
jpanel1.setVisible(false);
Adding a tag to your page will not control the UI in the Internet Control Panel (the dialog that appears when you selection Tools -> Options). If you're looking at your homepage which could be google.com, msn.com, about:blank or example.com, the Internet Control Panel has no way of knowing what the contents of your page may be, and it will not download it in the background.
Have a look at this document on MSDN which discussed compatibility mode and how to turn it off for your site.
function distRandom(){
do{
x=random(DISTRIBUTION_DOMAIN);
}while(random(DISTRIBUTION_RANGE)>=distributionFunction(x));
return x;
}
You can read it, but you can't set it. value="123"
will be ignored, so it won't have a value until you click on it and pick a file.
Even then, the value will likely be mangled with something like c:\fakepath\
to keep the details of the user's filesystem private.
I think you need to push a revert commit. So pull
from github again, including the commit you want to revert, then use git revert
and push the result.
If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset
: git push origin :master
.
From the AWS documentation:
Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.
Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.
Array.prototype.getIndex = function (obj) {
for (var i = 0; i < this.length; i++) {
if (this[i][Id] == obj.Id) {
return i;
}
}
return -1;
}
List.getIndex(obj);
Just wanted to add this because none of the above solutions worked if target link is directory with spaces in it's name. If target link is a directory and it has space then even escaping space with \ doesn't render the link on Github. Only solution worked for me is using %20
for each space.
e.g.: if directory structure is this
Top_dir
|-----README.md
|-----Cur_dir1
|----Dir A
|----README.md
|----Dir B
|----README.md
To make link to Dir A
in README.md present in Top_dir
you can do this:
[Dir 1](Cur_dir1/Dir%20A)
I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again
if npm version is < 5 then use npm cache clean --force
npm install -g @angular/cli@latest
and created a new project file and create a new angular project.
I use the code I found @.w3resources
The code takes care of
month being less than 12,
days being less than 32
even works with leap years. While Using in my project for leap year I modify the code like
if ((lyear==false) && (dd>=29))
{
alert('Invalid date format!');
return false;
}
if ((lyear==false) && (dd>=29))
{
alert('not a Leap year February cannot have more than 28days');
return false;
}
Rather than throwing the generic "Invalid date format" error which does not make much sense to the user. I modify the rest of the code to provide valid error message like month cannot be more than 12, days cannot be more than 31 etc.,
The problem with using Regular expression is it is difficult to identify exactly what went wrong. It either gives a True or a false-Without any reason why it failed. We have to write multiple regular expressions to sort this problem.
I think this is the most elegant, as it also does not try to move ..
:
mv /source/path/{.[!.],}* /destination/path
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf()
and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject
while passing your string to JSONObject
constructor as input
JSONObject
notation is represented by braces i.e {}
JSONArray
notation is represented by square brackets i.e []
3.) Retrieve JSONArray
from JSONObject
(created at 2nd step) using "interests"
as index.
4.) Traverse JASONArray
using loops upto the length of array provided by length()
function
5.) Retrieve your JSONObjects
from JSONArray
using getJSONObject(index)
function
6.) Fetch the data from JSONObject
using index '"interestKey"'.
Note : JSON
parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes ("
) like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser
to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key
so in those cases when you are not sure about the presence of value so use optString
, optInt
, optBoolean
etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
Get an optional string associated with a key. It returns the defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e ""
if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
This method was working as of December 2020
As suggested by qbolec, the above steps can be done by using this snippet:
<input id=username type="text" placeholder="github username or repo link">
<button onclick="fetch(`https://api.github.com/users/${username.value.replace(/^.*com[/]([^/]*).*$/,'$1')}/events/public`).then(e=> e.json()).then(e => [...new Set([].concat.apply([],e.filter(x => x.type==='PushEvent').map(x => x.payload.commits.map(c => c.author.email)))).values()]).then(x => results.innerText = x)">GO</button>
<div id=results></div>
_x000D_
Source: Matthew Ferree @ Sourcecon
I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.
handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.
EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.
Generate random colors;
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
and call it for each record;
function getRandomColorEachEmployee(count) {
var data =[];
for (var i = 0; i < count; i++) {
data.push(getRandomColor());
}
return data;
}
finally set colors;
var data = {
labels: jsonData.employees, // your labels
datasets: [{
data: jsonData.approvedRatios, // your data
backgroundColor: getRandomColorEachEmployee(jsonData.employees.length)
}]
};
$(".container > #first");
or
$(".container").children("#first");
or since IDs should be unique within a single document:
$("#first");
The last one is of course the fastest.
Since you're saying that you don't know their ID top couple of the upper selectors (where #first
is written), can be changed to:
$(".container > div");
$(".container").children("div");
The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.
If you also need to filter out only those child DIV
elements that define ID attribute you'd write selectors down this way:
$(".container > div[id]");
$(".container").children("div[id]");
Add the following code to attach click handler to any of your preferred selector:
// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
// if you need element's ID
var divID = this.id;
cache your element if you intend to use it multiple times
var clickedDiv = $(this);
// add CSS class to it
clickedDiv.addClass("add-some-class");
// do other stuff that needs to be done
});
I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.
I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:
$(".container > div[id]").each(function(){
var context = $(this);
// get menu parent element: Sub: Show Grid
// maybe I'm not appending to the correct element here but you should know
context.appendTo(context.parent().parent());
context.text("Show #" + this.id);
context.attr("href", "");
context.click(function(evt){
evt.preventDefault();
$(this).toggleClass("showgrid");
})
});
the last thee context
usages could be combined into a single chained one:
context.text(...).attr(...).click(...);
You can always get the underlaying DOM element from the jQuery result set.
$(...).get(0)
// or
$(...)[0]
will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.
But when I used .each()
function and provided an anonymous function that will be called on each element in the set, this
keyword actually refers to the DOM element.
$(...).each(function(){
var DOMelement = this;
var jQueryElement = $(this);
...
});
I hope this clears some things for your.
This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.
Bloch then describes how to make your classes immutable, by following 5 simple rules:
final
).final
.private
. For more details I highly recommend picking up a copy of the book.
There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.
You can directly run the code here : https://www.compilejava.net/
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
Demo1.Demo1(Main_Array);
// THE POINTER Main_Array IS NOT PASSED TO Demo1
// A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1
System.out.println("Main_Array = "+Arrays.toString(Main_Array));
// outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
// Since Main_Array points to the original location,
// I cannot access the results of Demo1 , Demo2 when they are void.
// I can use array clone method in Demo1 to get the required result,
// but it would be faster if Demo1 returned the result to main
}
}
public class Demo1
{
public static void Demo1(int A[])
{
int B[] = new int[A.length];
System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Demo2.Demo2(A,B);
System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
A = B;
// A was pointing to location of Main_Array, now it points to location of B
// Main_Array pointer still keeps pointing to the original location in void main
System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// Hence to access this result from main, I have to return it to main
}
}
public class Demo2
{
public static void Demo2(int AAA[],int BBB[])
{
BBB[0] = 9999;
// BBB points to the same location as B in Demo1, so whatever I do
// with BBB, I am manipulating the location. Since B points to the
// same location, I can access the results from B
}
}
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
You can do something similar to this:
// Get the parent to attatch the element into
var parent = document.getElementsByTagName("ul")[0];
// Create element with random id
var element = document.createElement("li");
element.id = "li-"+Math.floor(Math.random()*9999);
// Add event listener
element.addEventListener("click", EVENT_FN);
// Add to parent
parent.appendChild(element);
from re import search
from functools import wraps
def is_match(_lambda, pattern):
def wrapper(f):
@wraps(f)
def wrapped(self, *f_args, **f_kwargs):
if callable(_lambda) and search(pattern, (_lambda(self) or '')):
f(self, *f_args, **f_kwargs)
return wrapped
return wrapper
class MyTest(object):
def __init__(self):
self.name = 'foo'
self.surname = 'bar'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'foo')
def my_rule(self):
print 'my_rule : ok'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'bar')
def my_rule2(self):
print 'my_rule2 : ok'
test = MyTest()
test.my_rule()
test.my_rule2()
ouput: my_rule2 : ok
find using an attribute in any tag
<th class="team" data-sort="team">Team</th>
soup.find_all(attrs={"class": "team"})
<th data-sort="team">Team</th>
soup.find_all(attrs={"data-sort": "team"})
The R.* classes are generated dynamically. I leave the "Build automatically" option on in the Project menu so that mine R.* classes are always up-to-date.
Additionally, when creating new Activities, I copy and rename old ones, especially if they are similar to the new Activity that I need because Eclipse renames everything for you.
Otherwise, as others have said, the File->New->Class command works well and will build your file for you including templates for required methods based on your class, its inheritance and interfaces.
Be careful where you set WORKDIR
because it can affect the continuous integration flow. For example, setting it to /home/circleci/project
will cause error something like .ssh
or whatever is the remote circleci is doing at setup time.
You may try using ellipsis by adding the following in CSS:
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631
You can use COLLATE NOCASE
in your SELECT
query:
SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE
Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase
in the column definition (the other options are binary
(the default) and rtrim
; see here). You can specify collate nocase
when you create an index as well. For example:
create table Test ( Text_Value text collate nocase ); insert into Test values ('A'); insert into Test values ('b'); insert into Test values ('C'); create index Test_Text_Value_Index on Test (Text_Value collate nocase);
Expressions involving Test.Text_Value
should now be case insensitive. For example:
sqlite> select Text_Value from Test where Text_Value = 'B'; Text_Value ---------------- b sqlite> select Text_Value from Test order by Text_Value; Text_Value ---------------- A b C sqlite> select Text_Value from Test order by Text_Value desc; Text_Value ---------------- C b A
The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain
SQL command, e.g.:
sqlite> explain select Text_Value from Test where Text_Value = 'b'; addr opcode p1 p2 p3 ---------------- -------------- ---------- ---------- --------------------------------- 0 Goto 0 16 1 Integer 0 0 2 OpenRead 1 3 keyinfo(1,NOCASE) 3 SetNumColumns 1 2 4 String8 0 0 b 5 IsNull -1 14 6 MakeRecord 1 0 a 7 MemStore 0 0 8 MoveGe 1 14 9 MemLoad 0 0 10 IdxGE 1 14 + 11 Column 1 0 12 Callback 1 0 13 Next 1 9 14 Close 1 0 15 Halt 0 0 16 Transaction 0 0 17 VerifyCookie 0 4 18 Goto 0 1 19 Noop 0 0
you could use redis with the lightning fast node_redis client. It even has built-in pubsub semantics.
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.
Example:
When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.
When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus
It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.
import config.logging_settings # pylint: disable=W0611
That was simple and is specific for that line.
You can and should use the more readable form:
import config.logging_settings # pylint: disable=unused-import
When a new user is created in ORACLE, an empty work area for tables and views is also automatically created. That work area is called a 'Schema'. Because of the tightly coupled relationship between users and schemas, the terms are often used synonymously. SQL Developer will, by default, show the empty schema that belongs to the user you connected with if it is indeed empty.
However, if you click to expand the part of the tree titled 'Other Users', you'll see other users/schemas that your user has access to. In there, you may find the tables and views you are seeking if you select the correct user/schema. An object only lives in the schema that owns it.
Still, it would be nice if the application allowed us to pick our desired schema closer to the root of the tree instead of forcing us to go searching for it. Other answers have offered workarounds such as:
In the end, I searched and found another free tool that seems to solve this particular usability issue called DBeaver.
It's all a bit confusing because the word schema is overloaded. Schema could also be used to describe the database of your application. To get more clarity, read more about the term schema as it is used in the ORACLE context.
Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.
What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):
C#
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
VB
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.
On Windows, start up Command Prompt (cmd.exe) or PowerShell (powershell.exe). To do this quickly, open a Run Command window by pressing Windows Key + R. In the Run Command window, type "cmd.exe" to launch Command Prompt; However, to start PowerShell instead, then type "powershell". If you are connecting your Android device to your computer using a USB cable, then you will need to check whether your device is communicating with adb
by entering the command below:
# adb devices -l
Next, pull (copy) the file from your Android device over to Windows. This can be accomplished by entering the following command:
# adb pull /sdcard/log.txt %HOME%\Desktop\log.txt
Optionally, you may enter this command instead:
# adb pull /sdcard/log.txt C:\Users\admin\Desktop\log.txt
Another interesting solution is PhantomJS. It's a headless WebKit scriptable with JavaScript or CoffeeScript.
One of the use case is screen capture : you can programmatically capture web contents, including SVG and Canvas and/or Create web site screenshots with thumbnail preview.
The best entry point is the screen capture wiki page.
Here is a good example for polar clock (from RaphaelJS):
>phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png
Do you want to render a page to a PDF ?
> phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf
Without telling us what language this dll/assembly is from, we can only guess.
So how about .NET Reflector
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
Edited
If things were as they SHOULD be, you could do this via the "Accept" attribute.
http://www.webmasterworld.com/forum21/6310.htm
However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.
The following older post has some information that could help you with alternatives.
AFAIK you still need an <input type="file">
element, then you can use some of the stuff from quirksmode to style it up
Encountered a similar error, this how I resolved it:
Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below.
Right click an import jar file and select Exclude Dependency
4. Initiate maven clean install and run your project. Good luck!
To get the user email, you have to log in the user with his Facebook account using the email
permission. Use for that the Facebook PHP SDK (see on github) as following.
First check if the user is already logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he his not, you can display the login link asking for the email
permission :
if (!$user) {
$args = array('scope' => 'email');
echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}
When he is logged in the email can be found in the $user_profile
array.
Hope that helps !
If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.
For example the following won't work, DocumentRoot "X:/webroot"
But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)
Using FreeBSD ed
and avoid ed
's "no match" error in case there is no include
statement in a file to be processed:
teststr='
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
'
# using FreeBSD ed
# to avoid ed's "no match" error, see
# *emphasized text*http://codesnippets.joyent.com/posts/show/11917
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
H
,g/# *include/u\
u\
i\
#include "newfile.h"\
.
,p
q
EOF
It is not at all obvious why one would want to concatenate the (decimal) "ascii values". What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.
>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05']
>>> ["".join("%d" % ord(c) for c in s) for s in tests]
['104105', '72105', '7273', '104105']
Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.
>>> ["".join("%03d" % ord(c) for c in s) for s in tests]
['104105', '072105', '072073', '010041000005']
>>> [" ".join("%d" % ord(c) for c in s) for s in tests]
['104 105', '72 105', '72 73', '10 41 0 5']
>>> ["".join("%02x" % ord(c) for c in s) for s in tests]
['6869', '4869', '4849', '0a290005']
>>>
Note no such problems.
In your ASPX page you've got the list like this:
<asp:CheckBoxList ID="YrChkBox" runat="server"
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />
In your code behind aspx.cs page, you have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the CheckBoxList items only when it's not a postback.
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
}
}
protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Create the list to store.
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in YrChkBox.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
else
{
// Item is not selected, do something else.
}
}
// Join the string together using the ; delimiter.
String YrStr = String.Join(";", YrStrList.ToArray());
// Write to the page the value.
Response.Write(String.Concat("Selected Items: ", YrStr));
}
Ensure you use the if (!IsPostBack) { }
condition because if you load it every page refresh, it's actually destroying the data.
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
You need to remove the part that says data:image/png;base64,
at the beginning of the image data. The actual base64 data comes after that.
Just strip everything up to and including base64,
(before calling base64_decode()
on the data) and you'll be fine.
Or use this for an English (or mix it up for custom) format:
StringFormat='{}{0:dd/MM/yyyy}'
Since I do troubleshooting everyday as a part of my job, here is what I would like to do:
Since it's SQL Server 2008 R2, you can run SQLDiag which comes as a part of the product. You can refer books online for more details. In brief, capture Server Side trace and blocker script.
Once trace is captured, look for "Attention" event. That would be the spid which has received the error. If you filter by SPID, you would see RPC:Completed event before "Attention". Check the time over there. Is that time 30 seconds? If yes, then client waited for 30 second to get response from SQL and got "timed out" [This is client setting as SQL would never stop and connection]
Now, check if the query which was running really should take 30 seconds?
If yes then tune the query or increase the timeout setting from the client.
If no then this query must be waiting for some resources (blocked)
At this point go back to Blocker Script and check the time frame when "Attention" came
Above is assuming that issue is with SQL Server not network related!
Here is a Typescript implementation that supports webp. This is based on the JavaScript answer by Vitim.us.
interface Mime {
mime: string;
pattern: (number | undefined)[];
}
// tslint:disable number-literal-format
// tslint:disable no-magic-numbers
const imageMimes: Mime[] = [
{
mime: 'image/png',
pattern: [0x89, 0x50, 0x4e, 0x47]
},
{
mime: 'image/jpeg',
pattern: [0xff, 0xd8, 0xff]
},
{
mime: 'image/gif',
pattern: [0x47, 0x49, 0x46, 0x38]
},
{
mime: 'image/webp',
pattern: [0x52, 0x49, 0x46, 0x46, undefined, undefined, undefined, undefined, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50],
}
// You can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern
];
// tslint:enable no-magic-numbers
// tslint:enable number-literal-format
function isMime(bytes: Uint8Array, mime: Mime): boolean {
return mime.pattern.every((p, i) => !p || bytes[i] === p);
}
function validateImageMimeType(file: File, callback: (b: boolean) => void) {
const numBytesNeeded = Math.max(...imageMimes.map(m => m.pattern.length));
const blob = file.slice(0, numBytesNeeded); // Read the needed bytes of the file
const fileReader = new FileReader();
fileReader.onloadend = e => {
if (!e || !fileReader.result) return;
const bytes = new Uint8Array(fileReader.result as ArrayBuffer);
const valid = imageMimes.some(mime => isMime(bytes, mime));
callback(valid);
};
fileReader.readAsArrayBuffer(blob);
}
// When selecting a file on the input
fileInput.onchange = () => {
const file = fileInput.files && fileInput.files[0];
if (!file) return;
validateImageMimeType(file, valid => {
if (!valid) {
alert('Not a valid image file.');
}
});
};
<input type="file" id="fileInput">
_x000D_
In your Post
model add two accessor methods like this:
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
Now every time you use these properties from your model to show a date these will be presented differently, just the date without the time, for example:
$post = Post::find(1);
echo $post->created_at; // only Y-m-d formatted date will be displayed
So you don't need to change the original type in the database. to change the type
in your database you need to change it to Date
from Timestamp
and you need to do it from your migration (If your using at all) or directly into your database if you are not using migration. The timestamps()
method adds these fields (using Migration) and to change these fields during the migration you need to remove the timestamps()
method and use date()
instead, for example:
$table->date('created_at');
$table->date('updated_at');
Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):
java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>
Original answer follows.
Try this:
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp
Two points here:
runjdwp
option.You cannot install an unsigned application on a phone. You can only use it to test with an emulator. If you still want to go ahead, you can try self-signing the application.
Also, since you are installing the application from an SD card, I hope you have the necessary permissions set. Do go through stackoverflow.com and look at questions regarding installation of applications from an SD card - there have been many and they have been asked before.
Hope that helps.
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
I just type following keywords in the opened terminal;
See details in the below image. (VSCode version 1.19.1 - windows 10 OS)
It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)
On Excel for Mac 2011, the newline had to be a \r
instead of an \n
So
"\"first line\rsecond line\""
would show up as a cell with 2 lines
I had the same issue trying to specify the relative file path for a database connected to a Windows Forms application. I was able to resolve the issue by following the directions for adding a data source to Windows Forms from Microsoft (e.g., for connecting an Access database).
By using this method, Visual Studio will set the relative file paths to your database for you instead of trying to set it manually. If your database is external to your application, it will create a copy of the database and add it to your application in the proper location. Although you can manually alter you connection string in App.config and/or Settings.settings or within one of your scripts, I've found this method to be error prone. Instead, I've found it best to follow the Microsoft instructions, in general.
Think about statically typed language, things on prototype
are static and things on this
are instance related.
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
No such file or directory
can be also raised if you are trying to put a file argument to Popen
with double-quotes.
For example:
call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']
In this case, you need to remove double-quotes.
call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser
function expects a function in its third argument, which is bound to the name next
. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser
is done (unless a user could not be found).
There's nothing special about the name next
in this example; we could have named it anything.
In the query design:
Note:
If you don't sort, the field will be removed by access. So, make sure you've unchecked show and sorted the column.
One option is to use numba
and the @jit
or @njit
decorator. I also made one or two little tweaks to your code (at least in Python 3, "list" is a keyword that shouldn't be used for a variable name):
@njit
def njit_product(lst):
p = lst[0] # first element
for i in lst[1:]: # loop over remaining elements
p *= i
return p
For timing purposes, you need to run once to compile the function first using numba. In general, the function will be compiled the first time it is called, and then called from memory after that (faster).
njit_product([1, 2]) # execute once to compile
Now when you execute your code, it will run with the compiled version of the function. I timed them using a Jupyter notebook and the %timeit
magic function:
product(b) # yours
# 32.7 µs ± 510 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
njit_product(b)
# 92.9 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Note that on my machine, running Python 3.5, the native Python for
loop was actually the fastest. There may be a trick here when it comes to measuring numba-decorated performance with Jupyter notebooks and the %timeit
magic function. I am not sure that the timings above are correct, so I recommend trying it out on your system and seeing if numba gives you a performance boost.
From MSDN: SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
You are using SELECT query, thus you get -1
try
states.split()
it returns the list
['Alaska',
'Alabama',
'Arkansas',
'American',
'Samoa',
'Arizona',
'California',
'Colorado']
and this returns the random element of the list
import random
random.choice(states.split())
split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example
states.split('Ari')
returns
['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']
Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here
I see you are probably new to python, so I'd give you some advice how to use python's great documentation
Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language
I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this
def bubblesort(array):
for i in range(len(array)-1):
for j in range(len(array)-1-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return(array)
print(bubblesort([3,1,6,2,5,4]))
I believe Enterprise Architect can do that.
To save your work and exit press Esc and then :wq (w for write and q for quit).
Alternatively, you could both save and exit by pressing Esc and then :x
To set another editor run export EDITOR=myFavoriteEdior
on your terminal, where myFavoriteEdior
can be vi
, gedit
, subl
(for sublime) etc.
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
I have done this by this way
$sql = new Sql($this->adapter);
$select = $sql->select();
$select->from('mock_paper');
$select->columns(array(
'is_section'
));
$select->where(array('exam_id = ?' => $exam_id,'level_id = ?' => $level_id))->limit(1);
$sqlstring = $sql->buildSqlString($select);
echo $sqlstring;
die();
Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string
Output of this code will be: Veeru,Nikhil,Ashish,Paritosh
instead of output of list [Veeru,Nikhil,Ashish,Paritosh]
String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");
List_name = myNameList.toString().replace("[", "")
.replace("]", "").replace(", ", ",");
This question still seems relevant, and the answer seems to be a moving target.
On my debian system (buster):
> update-java-alternatives -l
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
However, if you actually go look there, you'll see there are multiple directories and symbolic links placed there by the package system to simplify future maintenance.
The actual directory is java-11-openjdk-amd64
, with another symlink of default-java
. There is also an openjdk-11
directory, but it appears to only contain a source.zip file.
Given this, for Debian ONLY, I would guess the best value to use is /usr/lib/jvm/default-java
, as this should always be valid, even if you decide to install a totally different version of java, or even switch vendors.
The normal reason to want to know the path is because some application wants it, and you probably don't want that app to break because you did an upgrade that changed version numbers.
Starting from API 21, the GridLayout now supports the weight like LinearLayout. For details please see the link below:
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).
No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.