I think this is the easiest way
<!-- Submit Button-->
<button
mat-raised-button
color="primary"
[disabled]="!f.valid"
>
Submit
</button>
What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.
x1 <= C <= x2
and
y1 <= C <= y2
Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test
x1 <= y2 && y1 <= x2
The simpliest way is to drop database phpmyadmin and run sql/create_tables.sql script. Just login to mysql console and:
DROP DATABASE phpmyadmin;
\. {your path to pma}/sql/reate_tables.sql
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
To get a NumPy array, you should use the values
attribute:
In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']); df
A B
a 1 4
b 2 5
c 3 6
In [2]: df.index.values
Out[2]: array(['a', 'b', 'c'], dtype=object)
This accesses how the data is already stored, so there's no need for a conversion.
Note: This attribute is also available for many other pandas' objects.
In [3]: df['A'].values
Out[3]: Out[16]: array([1, 2, 3])
To get the index as a list, call tolist
:
In [4]: df.index.tolist()
Out[4]: ['a', 'b', 'c']
And similarly, for columns.
Previous poster is right. You cannot return multiple values from a C# method. However, you do have a couple of options:
The pros and cons here are often hard to figure out. If you return a structure, make sure it's small because structs are value type and passed on the stack. If you return an instance of a class, there are some design patterns here that you might want to use to avoid causing problems - members of classes can be modified because C# passes objects by reference (you don't have ByVal like you did in VB).
Finally you can use output parameters but I would limit the use of this to scenarios when you only have a couple (like 3 or less) of parameters - otherwise things get ugly and hard to maintain. Also, the use of output parameters can be an inhibitor to agility because your method signature will have to change every time you need to add something to the return value whereas returning a struct or class instance you can add members without modifying the method signature.
From an architectural standpoint I would recommend against using key-value pairs or dictionaries. I find this style of coding requires "secret knowledge" in code that consumes the method. It must know ahead of time what the keys are going to be and what the values mean and if the developer working on the internal implementation changes the way the dictionary or KVP is created, it could easily create a failure cascade throughout the entire application.
this is the correct answer
$('#theid').css('display') == 'none'
You can also use following line to find if it is display block or none
$('.deal_details').is(':visible')
I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read()
returns a byte
object rather than string.
You might try to feed it into a StringIO
object, or even do a str(response)
.
I made a really dumb mistake and forgot to define name
attributes for inputs in my html file.
So instead of
<input type="password" class="form-control" id="password">
I have this.
<input type="password" class="form-control" id="password" name="password">
Now request.body
is populated like this: { password: 'hhiiii' }
Named pipes is a windows system for inter-process communication. In the case of SQL server, if the server is on the same machine as the client, then it is possible to use named pipes to tranfer the data, as opposed to TCP/IP.
url ='http://www.test.com/page/TEST2'.split('/')[4]
print url
Output: TEST2
.
Try this:
$(document).ready( function () {
$('#example').dataTable({
"order": []
});
});
this will solve your problem.
copy your table to a new table without identity column.
select columns into newtable from yourtable
add an identity column to newtable with new seed and make it as a primary key
ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
My solution is simple, don't look at the error notification in Build - Run tasks (which should be Execution failed for task ':app:compileDebugJavaWithJavac')
Just fix all errors in the Java Compiler section below it.
If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .
May be you want this (oop in javascript)
function box(color)
{
this.color=color;
}
var box1=new box('red');
var box2=new box('white');
Hitting ctrl + c once(wait for traceback), then hitting ctrl+c again did the trick for me :)
A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.
Background: a "stable" sorting algorithm keeps the items with the same sorting key in order. Suppose we have a list of 5-letter words:
peach
straw
apple
spork
If we sort the list by just the first letter of each word then a stable-sort would produce:
apple
peach
straw
spork
In an unstable sort algorithm, straw
or spork
may be interchanged, but in a stable one, they stay in the same relative positions (that is, since straw
appears before spork
in the input, it also appears before spork
in the output).
We could sort the list of words using this algorithm: stable sorting by column 5, then 4, then 3, then 2, then 1. In the end, it will be correctly sorted. Convince yourself of that. (by the way, that algorithm is called radix sort)
Now to answer your question, suppose we have a list of first and last names. We are asked to sort "by last name, then by first". We could first sort (stable or unstable) by the first name, then stable sort by the last name. After these sorts, the list is primarily sorted by the last name. However, where last names are the same, the first names are sorted.
You can't stack unstable sorts in the same fashion.
You want:
DECLARE @times int
SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'
You also don't need the 'as' clause.
Look at http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/
var https = require('https');
/**
* HOW TO Make an HTTP Call - GET
*/
// options for GET
var optionsget = {
host : 'graph.facebook.com', // here only the domain name
// (no http/https !)
port : 443,
path : '/youscada', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
/**
* HOW TO Make an HTTP Call - POST
*/
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
"message" : "The web of things is approaching, let do some tests to be ready!",
"name" : "Test message posted with node.js",
"caption" : "Some tests with node.js",
"link" : "http://www.youscada.com",
"description" : "this is a description",
"picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
"actions" : [ {
"name" : "youSCADA",
"link" : "http://www.youscada.com"
} ]
});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};
// the post options
var optionspost = {
host : 'graph.facebook.com',
port : 443,
path : '/youscada/feed?access_token=your_api_key',
method : 'POST',
headers : postheaders
};
console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');
// do the POST call
var reqPost = https.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('POST result:\n');
process.stdout.write(d);
console.info('\n\nPOST completed');
});
});
// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
});
/**
* Get Message - GET
*/
// options for GET
var optionsgetmsg = {
host : 'graph.facebook.com', // here only the domain name
// (no http/https !)
port : 443,
path : '/youscada/feed?access_token=you_api_key', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsgetmsg);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsgetmsg, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('GET result after POST:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
Review your first line. Your stack trace is clearly not from the code you've pasted here, so I don't know precisely what you've done.
>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
What you wanted was set([1, 2, 3, 4])
.
>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
The "not callable" exception means you were doing something like set()()
- attempting to call a set
instance.
Even though they are separate windows but the request you send from Postman, it's details should be available in network tab of developer tools. Just make sure you are not sending any other http traffic during that time, just for clarity.
Another easy way to find out if a variable is either list or tuple or generally check variable type would be :
def islist(obj):
if ("list" in str(type(obj)) ): return True
else : return False
The data type TEXT is old and should not be used anymore, it is a pain to select data out of a TEXT column.
ntext, text, and image (Transact-SQL)
ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
you need to use TEXTPTR (Transact-SQL) to retrieve the text data.
Also see this article on Handling The Text Data Type.
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
@Autowired
public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
@Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
To add on to the answers above, here is a code sample
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
This would give a compilation error:
Error 12 Cannot convert null to 'Test' because it is a non-nullable value type
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
MacOS: composer is available on brew now (Tested on Php7+):
brew install composer
Install instructions on the Composer Docs page are quite to the point otherwise.
Create a function in app.js
/*Function to get the app root folder*/
var appRootFolder = function(dir,level){
var arr = dir.split('\\');
arr.splice(arr.length - level,level);
var rootFolder = arr.join('\\');
return rootFolder;
}
// view engine setup
app.set('views', path.join(appRootFolder(__dirname,1),'views'));
std::string
is not Plain Old Data(POD), and its raw size is not the most relevant thing ever. For example, if you pass in a string which is above the length of SSO and allocated on the heap, I would expect the copy constructor to not copy the SSO storage.
The reason this is recommended is because inval
is constructed from the argument expression, and thus is always moved or copied as appropriate- there is no performance loss, assuming that you need ownership of the argument. If you don't, a const
reference could still be the better way to go.
Both the answers provided above work fine.
One tiny addition to JB Jansen's answer - in the main readdir()
loop I'd add this:
if (dir->d_type == DT_REG)
{
printf("%s\n", dir->d_name);
}
Just checking if it's really file, not (sym)link, directory, or whatever.
NOTE: more about struct dirent
in libc
documentation.
Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!
Here are a few possibilities that don't parse the output of ls
and that are 100% safe regarding files with spaces and funny symbols in their name. All of them will populate an array randf
with a list of random files. This array is easily printed with printf '%s\n' "${randf[@]}"
if needed.
This one will possibly output the same file several times, and N
needs to be known in advance. Here I chose N=42.
a=( * )
randf=( "${a[RANDOM%${#a[@]}]"{1..42}"}" )
This feature is not very well documented.
If N is not known in advance, but you really liked the previous possibility, you can use eval
. But it's evil, and you must really make sure that N
doesn't come directly from user input without being thoroughly checked!
N=42
a=( * )
eval randf=( \"\${a[RANDOM%\${#a[@]}]\"\{1..$N\}\"}\" )
I personally dislike eval
and hence this answer!
The same using a more straightforward method (a loop):
N=42
a=( * )
randf=()
for((i=0;i<N;++i)); do
randf+=( "${a[RANDOM%${#a[@]}]}" )
done
If you don't want to possibly have several times the same file:
N=42
a=( * )
randf=()
for((i=0;i<N && ${#a[@]};++i)); do
((j=RANDOM%${#a[@]}))
randf+=( "${a[j]}" )
a=( "${a[@]:0:j}" "${a[@]:j+1}" )
done
Note. This is a late answer to an old post, but the accepted answer links to an external page that shows terrible bash practice, and the other answer is not much better as it also parses the output of ls
. A comment to the accepted answer points to an excellent answer by Lhunath which obviously shows good practice, but doesn't exactly answer the OP.
Mixaz's above answer worked for me. However I had issues installing the package because of PGP check failures. Installing it by skipping the signature worked, you could try this :
yaourt --m-arg "--skipchecksums --skippgpcheck" -Sb <your-package>
eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:
Why does it release 50.5mb in particular - what is the amount that is released based on?
What it's based on is, ultimately, a whole series of coincidences inside Python and malloc
that are very hard to predict.
First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.
Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE
, etc.
If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk
or equivalent to shrink the data segment (very rare nowadays), or you've used munmap
or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED
for a MADV_FREE
segment that you immediately unmap.)
But most programs don't directly allocate things out of memory pages; they use a malloc
-style allocator. When you call free
, the allocator can only release pages to the OS if you just happen to be free
ing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.
CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc
. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.
So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString
object, and the string buffer).
If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)
If you do deallocate a block of object storage, to know whether this causes a free
call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloc
ed region, and even then, it may not happen.)
If you do free
a malloc
ed region, to know whether this causes an munmap
or equivalent (or brk
), you have to know the internal state of the malloc
, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc
within an mmap
segment, and even then, it may not happen.)
So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc
unmap 50.5mb worth of pages when you did those one or more free
calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc
, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.
So, the only useful answer to the question is "Because."
Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.
And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap
the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).
window.opener
refers to the window that called window.open( ... )
to open the window from which it's calledwindow.parent
refers to the parent of a window in a <frame>
or <iframe>
window.top
refers to the top-most window from a window nested in one or more layers of <iframe>
sub-windowsThose will be null
(or maybe undefined
) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)
In Android file system, "system.img" and "userdata.img" are VMS Alpha executable. "system.img" and "userdata.img" have the contents of /system and /data directory on root file system. They are mapped on NAND devices with yaffs2 file system. Now, yaffs2 image file can not be mounted on linux PC. If you can, maybe you got some rom that not packed in yaffs2 file system. You can check those rom file by execute the command:
file <system.img/userdata.img>
If it show "VMS Alpha executable" then you can use "unyaffs" to extract it.
This is usually caused by truncation (the incoming value is too large to fit in the destination column). Unfortunately SSIS will not tell you the name of the offending column. I use a third-party component to get this information: http://naseermuhammed.wordpress.com/tips-tricks/getting-error-column-name-in-ssis/
0 */6 * * *
crontab every 6 hours is a commonly used cron schedule.
Have you tried adding the absolute directory of go to your 'path'?
export PATH=$PATH:/directory/to/go/
The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.
Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)
Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.
You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).
You can do it this way:
(Edit: Considering that you're waiting for a response json
with dataType: 'json'
)
.NET
public JsonResult Edit(EditPostViewModel data)
{
if(ModelState.IsValid)
{
// Save
return Json(new { Ok = true } );
}
return Json(new { Ok = false } );
}
JS:
success: function (data) {
if (data.Ok) {
alert('success');
}
else {
alert('problem');
}
},
If you need I can also explain how to do it by returning a error 500, and get the error in the event error (ajax). But in your case this may be an option
in my project there is one requirement that we have make dynamic screen like Alignment of Dashboard while loading, it should display on an entire page and should get adjust dynamically, if user is maximizing or resizing the browser’s window. For this I have created url and used iframe to open one of the dynamic report which is written in cognos BI.In jsp we have to embed BI report. I have used iframe to embed this report in jsp. following code is working in my case.
<iframe src= ${cognosUrl} onload="this.style.height=(this.contentDocument.body.scrollHeight+30) +'px';" scrolling="no" style="width: 100%; min-height: 900px; border: none; overflow: hidden; height: 30px;"></iframe>
The same as in JavaScript, using Array.prototype.indexOf():
console.log(channelArray.indexOf('three') > -1);
Or using ECMAScript 2016 Array.prototype.includes():
console.log(channelArray.includes('three'));
Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example
const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]
Reference
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource
will give you a URL which can be used to retrieve an InputStream
.
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
Edit: classpath
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
I solve it!
First off all, you should add these:
defaultConfig {
multiDexEnabled true
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
After, you should click Build in top bar of Android Studio:
Build > Build Bundle(s) / APK(s) > Build APK(s)
Finally, you have an app-debug.apk file in:
app > build > outputs > apk > debug > app-debug.apk
Note: apk, debug, app-debug.apk files created automatically in outputs file by Android Studio.
If you are using pgAdmin3, expand 'Sequences,' right click on a sequence, go to 'Properties,' and in the 'Definition' tab change 'Current value' to whatever value you want. There is no need for a query.
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
>>> def func(a, *args, **kwargs):
... print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
...
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}
>>> def anotherfunct(beta, *args):
... print 'beta %s, args %s' % (beta, args)
...
>>> def func(a, *args, **kwargs):
... anotherfunct(a, *args)
...
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>>
Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.
Here is the JSONP I wrote to share with everyone:
the page to send req
http://c64.tw/r20/eqDiv/fr64.html
please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt
or embedded the code in your page:
function callbackForJsonp(resp) {
var elemDivResp = $("#idForDivResp");
elemDivResp.empty();
try {
elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
elemDivResp.append(" = " + resp.ans + "<br/>");
elemDivResp.append(" = " + resp.ans2 + "<br/>");
} catch (e) {
alert("callbackForJsonp=" + e);
}
}
$(document).ready(function() {
var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";
$(document.body).prepend("post to " + testUrl + "<br/><br/>");
$("#idForBtnToGo").click(function() {
$.ajax({
url : testUrl,
type : "POST",
data : {
f1 : $("#idForF1").val(),
f2 : $("#idForF2").val(),
op : "add"
},
dataType : "jsonp",
crossDomain : true,
//jsonpCallback : "callbackForJsonp",
success : callbackForJsonp,
//success : function(resp) {
//console.log("Yes, you success");
//callbackForJsonp(resp);
//},
error : function(XMLHttpRequest, status, err) {
console.log(XMLHttpRequest.status + "\n" + err);
//alert(XMLHttpRequest.status + "\n" + err);
}
});
});
});
On Windows you can use CRT debug heap.
Is there any standard or procedure one should follow to ensure there is no memory leak in the program.
Yeah, don't use manual memory management (if you ever call delete
or delete[]
manually, then you're doing it wrong). Use RAII and smart pointers, limit heap allocations to the absolute minimum (most of the time, automatic variables will suffice).
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
For those coming across this question more recently, .values
is deprecated as of Sequelize 3.0.0. Use .get()
instead to get the plain javascript object. So the above code would change to:
var nodedata = node.get({ plain: true });
Sequelize docs here
Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.
If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.
Parse a filename from the fully qualified path name (e.g., c:\temp\my.bat) to any component (e.g., File.ext).
Single line of code:
For %%A in ("C:\Folder1\Folder2\File.ext") do (echo %%~fA)
You can change out "C:\Folder1\Folder2\File.ext" for any full path and change "%%~fA" for any of the other options you will find by running "for /?" at the command prompt.
Elaborated Code
set "filename=C:\Folder1\Folder2\File.ext"
For %%A in ("%filename%") do (
echo full path: %%~fA
echo drive: %%~dA
echo path: %%~pA
echo file name only: %%~nA
echo extension only: %%~xA
echo expanded path with short names: %%~sA
echo attributes: %%~aA
echo date and time: %%~tA
echo size: %%~zA
echo drive + path: %%~dpA
echo name.ext: %%~nxA
echo full path + short name: %%~fsA)
Standalone Batch Script
Save as C:\cmd\ParseFn.cmd.
Add C:\cmd to your PATH environment variable and use it to store all of you reusable batch scripts.
@echo off
@echo ::___________________________________________________________________::
@echo :: ::
@echo :: ParseFn ::
@echo :: ::
@echo :: Chris Advena ::
@echo ::___________________________________________________________________::
@echo.
::
:: Process arguements
::
if "%~1%"=="/?" goto help
if "%~1%"=="" goto help
if "%~2%"=="/?" goto help
if "%~2%"=="" (
echo !!! Error: ParseFn requires two inputs. !!!
goto help)
set in=%~1%
set out=%~2%
:: echo "%in:~3,1%" "%in:~0,1%"
if "%in:~3,1%"=="" (
if "%in:~0,1%"=="/" (
set in=%~2%
set out=%~1%)
)
::
:: Parse filename
::
set "ret="
For %%A in ("%in%") do (
if "%out%"=="/f" (set ret=%%~fA)
if "%out%"=="/d" (set ret=%%~dA)
if "%out%"=="/p" (set ret=%%~pA)
if "%out%"=="/n" (set ret=%%~nA)
if "%out%"=="/x" (set ret=%%~xA)
if "%out%"=="/s" (set ret=%%~sA)
if "%out%"=="/a" (set ret=%%~aA)
if "%out%"=="/t" (set ret=%%~tA)
if "%out%"=="/z" (set ret=%%~zA)
if "%out%"=="/dp" (set ret=%%~dpA)
if "%out%"=="/nx" (set ret=%%~nxA)
if "%out%"=="/fs" (set ret=%%~fsA)
)
echo ParseFn result: %ret%
echo.
goto end
:help
@echo off
:: @echo ::___________________________________________________________________::
:: @echo :: ::
:: @echo :: ParseFn Help ::
:: @echo :: ::
:: @echo :: Chris Advena ::
:: @echo ::___________________________________________________________________::
@echo.
@echo ParseFn parses a fully qualified path name (e.g., c:\temp\my.bat)
@echo into the requested component, such as drive, path, filename,
@echo extenstion, etc.
@echo.
@echo Syntax: /switch filename
@echo where,
@echo filename is a fully qualified path name including drive,
@echo folder(s), file name, and extension
@echo.
@echo Select only one switch:
@echo /f - fully qualified path name
@echo /d - drive letter only
@echo /p - path only
@echo /n - file name only
@echo /x - extension only
@echo /s - expanded path contains short names only
@echo /a - attributes of file
@echo /t - date/time of file
@echo /z - size of file
@echo /dp - drive + path
@echo /nx - file name + extension
@echo /fs - full path + short name
@echo.
:end
:: @echo ::___________________________________________________________________::
:: @echo :: ::
:: @echo :: ParseFn finished ::
:: @echo ::___________________________________________________________________::
:: @echo.
In [58]: price = 1 *9
In [59]: price
Out[59]: 9
When you really want to write an i-test for a spring data repository you can do it like this:
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {
@Autowired
private WebBookingRepository repository;
@Test
public void testSaveAndFindAll() {
WebBooking webBooking = new WebBooking();
webBooking.setUuid("some uuid");
webBooking.setItems(Arrays.asList(new WebBookingItem()));
repository.save(webBooking);
Iterable<WebBooking> findAll = repository.findAll();
assertThat(findAll).hasSize(1);
webBooking.setId(1L);
assertThat(findAll).containsOnly(webBooking);
}
}
To follow this example you have to use these dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
You can make it a non-submitting button (<button type="button">
) and hook something like window.location = 'http://where.you.want/to/go'
into its onclick handler. This does not work without javascript enabled though.
Or you can make it a submit button, and do a redirect on the server, although this obviously requires some kind of server-side logic, but the upside is that is doesn't require javascript.
(actually, forget the second solution - if you can't use a form, the submit button is out)
Actually, this has nothing to do with the usual Windows / Unix \r\n
vs \n
issue. The TELNET procotol itself defines \r\n
as the end-of-line sequence, independently of the operating system. See RFC854.
Reimeus is right, you see this because of in.close in your chooseCave(). Also, this is wrong.
if (playAgain == "yes") {
play = true;
}
You should use equals instead of "==".
if (playAgain.equals("yes")) {
play = true;
}
public enum Colors
{
Red = 10,
Blue = 20,
Green = 30,
Yellow = 40,
}
comboBox1.DataSource = Enum.GetValues(typeof(Colors));
Full Source...Binding an enum to Combobox
You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.
On the view(html file)
<div id="target"> </div>
<button (click)="scroll()">Button</button>
on the .ts
file,
scroll() {
document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}
Had the same problem.
Fixed by adding the dependency
classpath 'com.google.gms:google-services:3.0.0'
to the root build.gradle
.
https://firebase.google.com/docs/android/setup#manually_add_firebase
I am using Windows 7. The below solution works for me!!
**Open** the file JavaC.sublime-build and replace all the code in the file with the code below:
{
"cmd": ["javac", "$file_name","&&","java", "$file_base_name"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
**"path": "C:\\Program Files\\Java\\jdk1.6.0\\bin\\",**
"selector": "source.java",
"shell": true
}
Remember to replace "C:\Program Files\Java\jdk1.6.0\bin\" with the path where you put your jdk. And make sure to add the path of you java JDK to the environment variable "PATH". Refer to bunnyDrug's post to set up the environment variable. Best!!
One use-case is that you have named (some of) your columns with some prefix, and you want the columns sorted with those prefixes all together and in some particular order (not alphabetical).
For example, you might start all of your features with Ft_
, labels with Lbl_
, etc, and you want all unprefixed columns first, then all features, then the label. You can do this with the following function (I will note a possible efficiency problem using sum
to reduce lists, but this isn't an issue unless you have a LOT of columns, which I do not):
def sortedcols(df, groups = ['Ft_', 'Lbl_'] ):
return df[ sum([list(filter(re.compile(r).search, list(df.columns).copy())) for r in (lambda l: ['^(?!(%s))' % '|'.join(l)] + ['^%s' % i for i in l ] )(groups) ], []) ]
I would like to add a new pure javascript
way to do this, which in my opinion is much cleaner, by using the fetch()
API. This a modern way to implements network requests. In your case, since you already have a form element
we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest
.
I found the solution.
Variable value should be C:\Users\dipanwita.neogy\Anaconda3\Scripts
With PHP 7.0+ now here you can do the following:
$dateString = substr($millseconds_go_here,0,10);
$drawDate = new \DateTime(Date('Y-m-d H:i',$dateString));
$drawDate->setTimezone(new \DateTimeZone('UTC'));
This does the following in order:
Date()
can handle the date.DateTime()
can then allow you to modify the time zone you are in, but ensure that date_default_timezone_set("Timezone");
is set before you use DateTime()
functions and classes.DateTime()
classes or functions are used.Apple has changed the interface.
The team ID could be found via this link: https://developer.apple.com/account/#/membership
I have tried to create an image to explain this in the most simple words
1) Authentication means "Are you who you say you are?"
2) Authorization means "Should you be able to do what you are trying to do?".
This is also described in the image below.
I have tried to explain it in the best terms possible, and created an image of the same.
See what I often do to obtain numbers after the decimal point in python 3:
a=1.22
dec=str(a).split('.')
dec= int(dec[1])
In XML, to manage margins between items of a RecyclerView, I am doing in this way, operating on these attributes of detail layout (I am using a RelativeLayout):
of course it is also very important to set these attributes:
Here follows a complete example, this is the layout for the list of items:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:name="blah.ui.meetings.MeetingEventFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginVertical="2dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.meetings.MeetingEventFragment"
tools:listitem="@layout/fragment_meeting_event" />
and this is the detail layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:background="@drawable/background_border_meetings">
<TextView
android:id="@+id/slot_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:text="slot_type"
/>
</RelativeLayout>
background_border_meetings is just a box:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- This is the stroke you want to define -->
<stroke android:width="4dp"
android:color="@color/mdtp_line_dark"/>
<!-- Optional, round your corners -->
<corners android:bottomLeftRadius="2dp"
android:topLeftRadius="2dp"
android:bottomRightRadius="2dp"
android:topRightRadius="2dp" />
<gradient android:startColor="@android:color/transparent"
android:endColor="@android:color/transparent"
android:angle="90"/>
</shape>
you just need to put this
($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));
($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));
I found a small error in Grahams otherwise cool solution:
It should be
IF COLUMNS_UPDATED() <> 0 -- insert or update
instead of > 0
probably because top bit gets interpreted as SIGNED integer sign bit...(?).
So in total:
DECLARE @action CHAR(8)
IF COLUMNS_UPDATED() <> 0 -- delete or update?
BEGIN
IF EXISTS (SELECT * FROM deleted) -- updated cols + old rows means action=update
SET @action = 'UPDATE'
ELSE
SET @action = 'INSERT' -- updated columns and nothing deleted means action=insert
END
ELSE -- delete
BEGIN
SET @action = 'DELETE'
END
You should take a look at various javascript libraries, they should be able to help you out:
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);
JSONArray
may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
I also saw another style:
>>> django.VERSION
(1, 1, 0, 'final', 0)
I use:
private void WaitNSeconds(int segundos)
{
if (segundos < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(segundos);
while (DateTime.Now < _desired) {
System.Windows.Forms.Application.DoEvents();
}
}
Adding this answer for completeness, though it's only usable under certain conditions.
If you have very large lists, removing from the end of the list avoids CPython internals having to memmove
, for situations where you can re-order the list. It gives a performance gain to remove from the end of the list, since it won't need to memmove
every item after the one your removing - back one step (1).
For one-off removals the performance difference may be acceptable, but if you have a large list and need to remove many items - you will likely notice a performance hit.
Although admittedly, in these cases, doing a full list search is likely to be a performance bottleneck too, unless items are mostly at the front of the list.
This method can be used for more efficient removal,
as long as re-ordering the list is acceptable. (2)
def remove_unordered(ls, item):
i = ls.index(item)
ls[-1], ls[i] = ls[i], ls[-1]
ls.pop()
You may want to avoid raising an error when the item
isn't in the list.
def remove_unordered_test(ls, item):
try:
i = ls.index(item)
except ValueError:
return False
ls[-1], ls[i] = ls[i], ls[-1]
ls.pop()
return True
A simple way to test this, compare the speed difference from removing from the front of the list with removing the last element:
python -m timeit 'a = [0] * 100000' 'while a: a.remove(0)'
With:
python -m timeit 'a = [0] * 100000' 'while a: a.pop()'
(gives an order of magnitude speed difference where the second example is faster with CPython and PyPy).
set
, especially if the list isn't meant to store duplicates.set
. Also check on btree's if the data can be ordered.Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))
Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.
This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:
.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
border-color: transparent transparent #fff transparent !important;
}
.select2-container--default .select2-selection--single .select2-selection__arrow b {
border-color: #fff transparent transparent transparent !important;
}
I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:
Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):
var aString = nil //error
The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":
var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
That being, you can check those variables in different situations:
if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):
let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!
println(anotherString) //it will print "Hello, World!"
That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)
I also agree with the answer above: Optional type cannot be used as a boolean.
On Windows, highlight the code that has classes which need to be resolved and hit Alt+Enter
In my humble opinion, first, you have to make sure you have any kind of Node version installed. For that type:
nvm ls
And if you don't get any versions it means I was right :) Then you have to type:
nvm install <node_version**>
** the actual version you can find in Node website
Then you will have Node and you will be able to use npm commands
Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.
The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.
Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.
Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.
GET
and POST
:One way to get rid of this error message is to make your form use GET
instead of POST
. Just keep in mind that this is not always an appropriate solution (read below).
Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.
Examples of when to use POST
would include:
GET
with an <input type="file">
field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.
Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.
Examples would include:
In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.
POST
:To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST
being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?
So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.
Here is a simple example using PHP:
if(!empty($_POST['username'] && !empty($_POST['password'])) {
$user = new User;
$user->login($_POST['username'], $_POST['password']);
if ($user->isLoggedIn()) {
header("Location: /admin/welcome.php");
exit;
}
else {
header("Location: /login.php?invalid_login");
}
}
Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:
if (isset($_GET['invalid_login'])) {
echo "Your username and password combination is invalid";
}
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
The original checked
attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.
This, however is not valid for XHTML that followed HTML 4.
The standard proposed to use checked="checked"
as a condition for true - so both ways you posted end up doing the same thing.
It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).
This work for me in bootstrap 4:
<div class="alert alert-info">
<a href="#" class="alert-link">Summary:Its some description.......testtesttest</a>
<button type="button" class="btn btn-primary btn-lg float-right">Large button</button>
</div>
Simple code to check pointer aliasing:
int main () {
int a = 10, b = 20;
int *p1, *p2, *p3, *p4;
p1 = &a;
p2 = &a;
if(p1 == p2){
std::cout<<"p1 and p2 alias each other"<<std::endl;
}
else{
std::cout<<"p1 and p2 do not alias each other"<<std::endl;
}
//------------------------
p3 = &a;
p4 = &b;
if(p3 == p4){
std::cout<<"p3 and p4 alias each other"<<std::endl;
}
else{
std::cout<<"p3 and p4 do not alias each other"<<std::endl;
}
return 0;
}
Output:
p1 and p2 alias each other
p3 and p4 do not alias each other
You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.
Instead try:
void action(const typename Subclass::mytype &var) {
(static_cast<Subclass*>(this))->do_action();
}
import java.util*;
Random rnd = new Random ();
long name = Math.abs(rnd.nextLong());
This should work
In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:
SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])
I spent almost 6 hours before I stumble on the post.
I had this problem to install laravel/lumen.
It can be resolved with the following command:
$ sudo chown -R $USER ~/.composer/
It means that there is no initial context :)
But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".
An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.
UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.
@Rollerball is right. The wait()
is called, so that the thread can wait for some condition to occur when this wait()
call happens, the thread is forced to give up its lock.
To give up something, you need to own it first. Thread needs to own the lock first.
Hence the need to call it inside a synchronized
method/block.
Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized
method/block. However as @shrini1000 has pointed out, just calling wait()
within synchronized block will not avert this inconsistency from happening.
foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()
or
string.Concat(foo.ToArray().Select(a => a += ",").ToArray())
Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.
Check the project properties. It's configurable there if you are using another .net windows application for example
Using interactive rebase, you can place an amend command after each commit you want to alter. For instance:
pick a07cb86 Project tile template with full details and styling
x git commit --amend --reset-author -Chead
The objdump
tool can tell you this information. If you invoke objdump
with the -x
option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".
For example running objdump -x /usr/lib/libXpm.so.4
on my system gives the following information in the "Dynamic Section":
Dynamic Section:
NEEDED libX11.so.6
NEEDED libc.so.6
SONAME libXpm.so.4
INIT 0x0000000000002450
FINI 0x000000000000e0e8
GNU_HASH 0x00000000000001f0
STRTAB 0x00000000000011a8
SYMTAB 0x0000000000000470
STRSZ 0x0000000000000813
SYMENT 0x0000000000000018
PLTGOT 0x000000000020ffe8
PLTRELSZ 0x00000000000005e8
PLTREL 0x0000000000000007
JMPREL 0x0000000000001e68
RELA 0x0000000000001b38
RELASZ 0x0000000000000330
RELAENT 0x0000000000000018
VERNEED 0x0000000000001ad8
VERNEEDNUM 0x0000000000000001
VERSYM 0x00000000000019bc
RELACOUNT 0x000000000000001b
The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4
on my system just needs libX11.so.6
and libc.so.6
.
It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump
will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.
In swift...
This is inclusive, calling random(1,2)
will return a 1 or a 2, This will also work with negative numbers.
func random(min: Int, _ max: Int) -> Int {
guard min < max else {return min}
return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}
I had a similar problem on Ubuntu 16.04. Thanks to @Guna I figured out that I had to manually install Java (sudo apt install openjdk-8-jre
).
for inserting data into table you can write
insert into tablename values(column_name1,column_name2,column_name3);
but write the column_name
in the sequence as per sequence in table ...
If the arrays in your posted hashCode are bytes, then you will likely end up with lots of duplicates.
a[0] + a[1] will always be between 0 and 512. adding the b's will always result in a number between 0 and 768. multiply those and you get an upper limit of 400,000 unique combinations, assuming your data is perfectly distributed among every possible value of each byte. If your data is at all regular, you likely have far less unique outputs of this method.
After PHP 5 you can use this: echo date("c");
form ISO 8601 formatted datetime.
Note for comments:
Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh]
.
But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c")
. A similar discussion here.
System.Diagnostics.Process.Start( "notepad.exe", "text.txt");
In Swift -
var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)
I am using this method to read Contacts
public static List<ContactItem> readPhoneContacts(Context context) {
List<ContactItem> contactItems = new ArrayList<ContactItem>();
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
/*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
new String[] { id },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
ContactItem contactItem = new ContactItem();
contactItem.setContactName(contactName);
//the below cursor will give you details for multiple contacts
Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
//Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
switch (phoneType) {
case Phone.TYPE_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case Phone.TYPE_OTHER:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
pCursor.close();
contactItems.add(contactItem);
}
}
cursor.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return contactItems;
}//loadContacts
if you just want the ip address try this:
#Variable to store ip address
ipaddr=$(hostname -I)
echo "$ipaddr"
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
This is how I handle it:
class MyComponent extends React.Component{
constructor(props){
super(props);
this._initState = {
a: 1,
b: 2
}
this.state = this._initState;
}
_resetState(){
this.setState(this._initState);
}
}
Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
On MAC Remove gradle-2.1-all folder from the following path /Users/amitsapra/.gradle/wrapper/dists/gradle-2.1-all and then try gradle build again. I faced same issues with 5.4.1-all.
It takes a little time but fixes everything
Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:
this.print({bUI: false, bSilent: true, bShrinkToFit: true});
This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.
Auto-printing PDF!
This is what worked for me.
<!DOCTYPE html>
<form action="desired Link">
<button> <img src="desired image URL"/>
</button>
</form>
<style>
</style>
int i=1;
while (true) {
WebElementdisplay=driver.findElement(By.id("__bar"+i+"-btnGo"));
System.out.println(display);
if (display.isDisplayed()==true)
{
System.out.println("inside if statement"+i);
driver.findElement(By.id("__bar"+i+"-btnGo")).click();
break;
}
else
{
System.out.println("inside else statement"+ i);
i=i+1;
}
}
Here is a modified version of Steven Harris' that is plain ES5 and returns an object keyed on the id rather than returning an array of nodes at both the top level and for the children.
unflattenToObject = function(array, parent) {
var tree = {};
parent = typeof parent !== 'undefined' ? parent : {id: 0};
var childrenArray = array.filter(function(child) {
return child.parentid == parent.id;
});
if (childrenArray.length > 0) {
var childrenObject = {};
// Transform children into a hash/object keyed on token
childrenArray.forEach(function(child) {
childrenObject[child.id] = child;
});
if (parent.id == 0) {
tree = childrenObject;
} else {
parent['children'] = childrenObject;
}
childrenArray.forEach(function(child) {
unflattenToObject(array, child);
})
}
return tree;
};
var arr = [
{'id':1 ,'parentid': 0},
{'id':2 ,'parentid': 1},
{'id':3 ,'parentid': 1},
{'id':4 ,'parentid': 2},
{'id':5 ,'parentid': 0},
{'id':6 ,'parentid': 0},
{'id':7 ,'parentid': 4}
];
tree = unflattenToObject(arr);
With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view.
From Wikipedia:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.
A pseudo element works best.
a, a:hover {
position: relative;
text-decoration: none;
}
a:after {
content: '';
display: block;
position: absolute;
height: 0;
top:90%;
left: 0;
right: 0;
border-bottom: solid 1px red;
}
See jsfiddle.
You don't need any extra elements, you can position it as close or far as you want from the text (border-bottom is kinda far for my liking), there aren't any extra colors that show up if your link is over a different colored background (like with the box-shadow trick), and it works in all browsers (text-decoration-color only supports Firefox as of yet).
Possible downside: The link can't be position:static, but that's probably not a problem the vast majority of the time. Just set it to relative and all is good.
Easiest way is probbaly just to print a ^G ascii bell
The comment by MK pointed me in the right direction.
In the case of Apache 2.4 and up, there are different defaults and a new directive.
I am running Apache 2.4.6, and I had to add the following directives to get it working:
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
It seems you need to run ssh-agent
before using it:
eval `ssh-agent -s`
That question was answered in this topic: Could not open a connection to your authentication agent
A compiler may place structure members on particular byte boundaries for reasons of performance on a particular architecture. This may leave unused padding between members. Structure packing forces members to be contiguous.
This may be important for example if you require a structure to conform to a particular file or communications format where the data you need the data to be at specific positions within a sequence. However such usage does not deal with endian-ness issues, so although used, it may not be portable.
It may also to exactly overlay the internal register structure of some I/O device such as a UART or USB controller for example, in order that register access be through a structure rather than direct addresses.
This is one way:
.your-selector:empty::after {
content: ".";
visibility: hidden;
}
This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.
You must create them under strings.xml
<string name="close">Close</string>
You must replace and reference like this
android:text="@string/close"/>
Do not use @strings even though the XML file says strings.xml or else it will not work.
You can use this function
function getParmFromUrl(url, parm) {
var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
var match = url.match(re);
return(match ? match[1] : "");
}
1) you are calling it wrong way try:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
Just a comment on importing jars into Eclipse (plug-in development) projects:
In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages.
(BTW: Eclipse plug-ins are the same thing as OSGi bundles.)
There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:
you can keep booth EAGER lists in JPA and add to at least one of them the JPA annotation @OrderColumn (with obviously the name of a field to be ordered). No need of specific hibernate annotations. But keep in mind it could create empty elements in the list if the chosen field does not have values starting from 0
[...]
@OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
@OrderColumn(name="orderIndex")
private List<Child> children;
[...]
in Children then you should add the orderIndex field
Well, it actually looks like the warning is telling you what to do.
As part of sklearn.pipeline
stages' uniform interfaces, as a rule of thumb:
when you see X
, it should be an np.array
with two dimensions
when you see y
, it should be an np.array
with a single dimension.
Here, therefore, you should consider the following:
temp = [1,2,3,4,5,5,6,....................,7]
# This makes it into a 2d array
temp = np.array(temp).reshape((len(temp), 1))
temp = scaler.transform(temp)
^$ -- regex to accept empty string.And it wont match "/n" or "foobar/n" as you mentioned. You could test this regex on https://www.regextester.com/1924.
If you have your existing regex use or(|) in your regex to match empty string. For example /^[A-Za-z0-9&._ ]+$|^$/
openjdk-6
is a Java runtime, not a JDK (development kit which contains javac
, for example). Install openjdk-6-jdk
.
Maven also needs the JDK.
[EDIT] When the JDK is installed, use /usr/lib/jvm/java-6-openjdk
for JAVA_HOME
(i.e. without the jre
part).
WHERE filters before data is grouped, and HAVING filters after data is grouped. This is an important distinction; rows that are eliminated by a WHERE clause will not be included in the group. This could change the calculated values which, in turn(=as a result) could affect which groups are filtered based on the use of those values in the HAVING clause.
And continues,
HAVING is so similar to WHERE that most DBMSs treat them as the same thing if no GROUP BY is specified. Nevertheless, you should make that distinction yourself. Use HAVING only in conjunction with GROUP BY clauses. Use WHERE for standard row-level filtering.
Excerpt From: Forta, Ben. “Sams Teach Yourself SQL in 10 Minutes (5th Edition) (Sams Teach Yourself...).”.
This is the quote from here
Event.preventDefault
The preventDefault method prevents an event from carrying out its default functionality. For example, you would use preventDefault on an A element to stop clicking that element from leaving the current page:
//clicking the link will *not* allow the user to leave the page
myChildElement.onclick = function(e) {
e.preventDefault();
console.log('brick me!');
};
//clicking the parent node will run the following console statement because event propagation occurs
logo.parentNode.onclick = function(e) {
console.log('you bricked my child!');
};
While the element's default functionality is bricked, the event continues to bubble up the DOM.
Event.stopPropagation
The second method, stopPropagation, allows the event's default functionality to happen but prevents the event from propagating:
//clicking the element will allow the default action to occur but propagation will be stopped...
myChildElement.onclick = function(e) {
e.stopPropagation();
console.log('prop stop! no bubbles!');
};
//since propagation was stopped by the child element's onClick, this message will never be seen!
myChildElement.parentNode.onclick = function(e) {
console.log('you will never see this message!');
};
stopPropagation effectively stops parent elements from knowing about a given event on its child.
While a simple stop method allows us to quickly handle events, it's important to think about what exactly you want to happen with bubbling. I'd bet that all a developer really wants is preventDefault 90% of the time! Incorrectly "stopping" an event could cause you numerous troubles down the line; your plugins may not work and your third party plugins could be bricked. Or worse yet -- your code breaks other functionality on a site.
raw.githubusercontent.com/username/repo-name/branch-name/path
Replace username
with the username of the user that created the repo.
Replace repo-name
with the name of the repo.
Replace branch-name
with the name of the branch.
Replace path
with the path to the file.
To reverse to go to GitHub.com:
GitHub.com/username/repo-name/directory-path/blob/branch-name/filename
If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr
function like this:
regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')
If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?
For example, half the original size
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
Use the built-in isinstance()
function.
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print("do stuff")
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
If you're registering a domain and the termination (ex .com
) it is not IDN, as Aaron Hathaway said:
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org
is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a
through z
(in a case-insensitive manner), the digits 0
through 9
, and the hyphen -
. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
Later, Spain with it's .es
, .com.es
, .org.es
, .nom,es
, .gob.es
and .edu.es
introduced IDN tlds, if your tld is one of .es
or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.
If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.
Keep in mind some programs could not work well, especially old, outdated and unpopular ones.
If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)
So I have to use the following method.
CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.
Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.
Step2:
[Situation A]: target commit is the latest one.
1) In the git command console, input
git commit --amend -m "new comment message"
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
[Situation B]: target commit is not the latest one.
1) In the git command console, input
git rebase -i HEAD~n
It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2.
This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq
to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq
to save&quit.
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
Finally: In the sourcetree main window, Press F5
to refresh.
If you are using fedora then first install tkinter
sudo dnf install python3-tkinter
I don't think you need to import tkinter afterwards I also suggest you to use virtualenv
$ python3 -m venv myvenv
$ source myvenv/bin/activate
And add the necessary packages using pip
I'm using Sublime portable version (for Windows) and this (placing the mousemap in SublimeText\Packages\User
folder) did not work for me.
I had to place the mousemap file in SublimeText\Data\Packages\User
folder to get it to work where SublimeText
is the installation directory for my portable version. Data\Packages\User
is where I found the keymap file as well.
It's easy to use, I think. https://stackoverflow.com/a/32245370/4365315
var A = {a:11, b:22},
enumA = new TypeHelper(A);
if(enumA.Value === A.b || enumA.Key === "a"){
...
}
var keys = enumA.getAsList();//[object, object]
//set
enumA.setType(22, false);//setType(val, isKey)
enumA.setType("a", true);
enumA.setTypeByIndex(1);
UPDATE:
There is my helper codes(TypeHelper
).
var Helper = {_x000D_
isEmpty: function (obj) {_x000D_
return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
},_x000D_
_x000D_
isObject: function (obj) {_x000D_
return (typeof obj === 'object');_x000D_
},_x000D_
_x000D_
sortObjectKeys: function (object) {_x000D_
return Object.keys(object)_x000D_
.sort(function (a, b) {_x000D_
c = a - b;_x000D_
return c_x000D_
});_x000D_
},_x000D_
containsItem: function (arr, item) {_x000D_
if (arr && Array.isArray(arr)) {_x000D_
return arr.indexOf(item) > -1;_x000D_
} else {_x000D_
return arr === item;_x000D_
}_x000D_
},_x000D_
_x000D_
pushArray: function (arr1, arr2) {_x000D_
if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
}_x000D_
}_x000D_
};_x000D_
function TypeHelper() {_x000D_
var _types = arguments[0],_x000D_
_defTypeIndex = 0,_x000D_
_currentType,_x000D_
_value,_x000D_
_allKeys = Helper.sortObjectKeys(_types);_x000D_
_x000D_
if (arguments.length == 2) {_x000D_
_defTypeIndex = arguments[1];_x000D_
}_x000D_
_x000D_
Object.defineProperties(this, {_x000D_
Key: {_x000D_
get: function () {_x000D_
return _currentType;_x000D_
},_x000D_
set: function (val) {_x000D_
_currentType.setType(val, true);_x000D_
},_x000D_
enumerable: true_x000D_
},_x000D_
Value: {_x000D_
get: function () {_x000D_
return _types[_currentType];_x000D_
},_x000D_
set: function (val) {_x000D_
_value.setType(val, false);_x000D_
},_x000D_
enumerable: true_x000D_
}_x000D_
});_x000D_
this.getAsList = function (keys) {_x000D_
var list = [];_x000D_
_allKeys.forEach(function (key, idx, array) {_x000D_
if (key && _types[key]) {_x000D_
_x000D_
if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
var json = {};_x000D_
json.Key = key;_x000D_
json.Value = _types[key];_x000D_
Helper.pushArray(list, json);_x000D_
}_x000D_
}_x000D_
});_x000D_
return list;_x000D_
};_x000D_
_x000D_
this.setType = function (value, isKey) {_x000D_
if (!Helper.isEmpty(value)) {_x000D_
Object.keys(_types).forEach(function (key, idx, array) {_x000D_
if (Helper.isObject(value)) {_x000D_
if (value && value.Key == key) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (isKey) {_x000D_
if (value && value.toString() == key.toString()) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (value && value.toString() == _types[key]) {_x000D_
_currentType = key;_x000D_
}_x000D_
});_x000D_
} else {_x000D_
this.setDefaultType();_x000D_
}_x000D_
return isKey ? _types[_currentType] : _currentType;_x000D_
};_x000D_
_x000D_
this.setTypeByIndex = function (index) {_x000D_
for (var i = 0; i < _allKeys.length; i++) {_x000D_
if (index === i) {_x000D_
_currentType = _allKeys[index];_x000D_
break;_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
this.setDefaultType = function () {_x000D_
this.setTypeByIndex(_defTypeIndex);_x000D_
};_x000D_
_x000D_
this.setDefaultType();_x000D_
}_x000D_
_x000D_
var TypeA = {_x000D_
"-1": "Any",_x000D_
"2": "2L",_x000D_
"100": "100L",_x000D_
"200": "200L",_x000D_
"1000": "1000L"_x000D_
};_x000D_
_x000D_
var enumA = new TypeHelper(TypeA, 4);_x000D_
_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setType("200L", false);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
enumA.setDefaultType();_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setTypeByIndex(1);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
document.writeln("is equals = ", (enumA.Value == TypeA["2"]));
_x000D_
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
Year(Date)
Year()
: Returns the year portion of the date argument.
Date
: Current date only.
Explanation of both of these functions from here.
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
Doing borders on tables with css is a bit more complicated (but not as much, see this jsfiddle as example):
table {_x000D_
border-collapse: collapse;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
table td {_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>test</td>_x000D_
<td>test</td>_x000D_
</tr>_x000D_
</table>
_x000D_
textField(_:shouldChangeCharactersIn:replacementString:) worked for me in Xcode 8, Swift 3 if you want to check every single keypress.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Whatever code you want to run here.
// Keep in mind that the textfield hasn't yet been updated,
// so use 'string' instead of 'textField.text' if you want to
// access the string the textfield will have after a user presses a key
var statusText = self.status.text
var usernameText = self.username.text
switch textField{
case self.status:
statusText = string
case self.username:
usernameText = string
default:
break
}
if statusText == "" && usernameText == "" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
//Return false if you don't want the textfield to be updated
return true
}
Make sure your escaping the HTML characters
E.g.
// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
// Escape any html characters
echo htmlentities($_POST['contact_list']);
}
This would occur because of the angle brackets and the browser thinking they are tags.
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
If you are using bootstrap v4 there is a new way to do that.
You should use .dropdown-menu-right
on the .dropdown-menu
element.
<div class="btn-group">
<button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Right-aligned menu
</button>
<div class="dropdown-menu dropdown-menu-right">
<button class="dropdown-item" type="button">Action</button>
<button class="dropdown-item" type="button">Another action</button>
<button class="dropdown-item" type="button">Something else here</button>
</div>
</div>
Link to code: https://getbootstrap.com/docs/4.0/components/dropdowns/#menu-items
By default, read.csv
checks the first few rows of your data to see whether to treat each variable as numeric. If it finds non-numeric values, it assumes the variable is character data, and character variables are converted to factors.
It looks like the PTS and MP variables in your dataset contain non-numerics, which is why you're getting unexpected results. You can force these variables to numeric with
point <- as.numeric(as.character(point))
time <- as.numeric(as.character(time))
But any values that can't be converted will become missing. (The R FAQ gives a slightly different method for factor -> numeric conversion but I can never remember what it is.)
The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.
The execution policy is saved in the registry, so you need to change it only once on each computer.
To change the execution policy, use the following procedure:
Start Windows PowerShell with the "Run as administrator" option.
At the command prompt, type:
Set-ExecutionPolicy AllSigned
-or-
Set-ExecutionPolicy RemoteSigned
The change is effective immediately.
To run a script, type the full name and the full path to the script file.
For example, to run the Get-ServiceLog.ps1
script in the C:\Scripts
directory, type:
C:\Scripts\Get-ServiceLog.ps1
And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py
.
To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.
They're called indexed views in SQL Server - read these white papers for more background:
Basically, all you need to do is:
and you're done!
The tricky part is: the view has to satisfy quite a number of constraints and limitations - those are outlined in the white paper. If you do this, that's all there is. The view is being updated automatically, no maintenance needed.
Additional resources:
In past few days my co-workers keep asking me about using AlertDialog
in Xamarin.Android
and almost all of them sent this question as the ref which they read before asking me (and didn't find the answer), so here is Xamarin.Android
(C#
) version:
var alertDialog = new AlertDialog.Builder(this) // this: Activity
.SetTitle("Hello!")
.SetMessage("Are you sure?")
.SetPositiveButton("Ok", (sender, e) => { /* ok things */ })
.SetNegativeButton("Cancel", (sender, e) => { /* cancel things */ })
.Create();
alertDialog.Show();
// you can customize your AlertDialog, like so
var tvMessage = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);
tvMessage.TextSize = 13;
// ...
Here's my shot at this, covering different versions of jQuery:
// Binds a jQuery event to elements at the start of the event chain for that type.
jQuery.extend({
_bindEventHandlerAtStart: function ($elements, eventType, handler) {
var _data;
$elements.bind(eventType, handler);
// This bound the event, naturally, at the end of the event chain. We
// need it at the start.
if (typeof jQuery._data === 'function') {
// Since jQuery 1.8.1, it seems, that the events object isn't
// available through the public API `.data` method.
// Using `$._data, where it exists, seems to work.
_data = true;
}
$elements.each(function (index, element) {
var events;
if (_data) {
events = jQuery._data(element, 'events')[eventType];
} else {
events = jQuery(element).data('events')[eventType];
}
events.unshift(events.pop());
if (_data) {
jQuery._data(element, 'events')[eventType] = events;
} else {
jQuery(element).data('events')[eventType] = events;
}
});
}
});
You also have to include the FormID in your call to addMessage().
FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));
This should do the trick.
Regards.
You are passing a dictionary to a function that expects a string.
This syntax:
{"('Hello',)": 6, "('Hi',)": 5}
is both a valid Python dictionary literal and a valid JSON object literal. But loads
doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).
If you pass this string to loads
:
'''{"('Hello',)": 6, "('Hi',)": 5}'''
then it will return a dictionary that looks a lot like the one you are trying to pass to it.
You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:
json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?
It's Really Simple, This is how it works
yield
keyword simply helps to pause and resume a function in any time asynchronously.Take this simple generator function:
function* process() {
console.log('Start process 1');
console.log('Pause process2 until call next()');
yield;
console.log('Resumed process2');
console.log('Pause process3 until call next()');
let parms = yield {age: 12};
console.log("Passed by final process next(90): " + parms);
console.log('Resumed process3');
console.log('End of the process function');
}
let _process = process();
Until you call the _process.next() it wont execute the first 2 lines of code, then the first yield will pause the function. To resume the function until next pause point (yield keyword) you need to call _process.next().
You can think multiple yields are the breakpoints in a javascript debugger within a single function. Until you tell to navigate next breakpoint it wont execute the code block. (Note: without blocking the whole application)
But while yield performs this pause and resume behaviours it can return some results as well {value: any, done: boolean}
according to the previous function we haven't emit any values. If we explore the previous output it will show the same { value: undefined, done: false }
with value undefined.
Lets dig in to the yield keyword. Optionally you can add expression and set assign a default optional value. (Official doc syntax)
[rv] = yield [expression];
expression: Value to return from the generator function
yield any;
yield {age: 12};
rv: Returns the optional value that passed to the generator's next() method
Simply you can pass parameters to process() function with this mechanism, to execute different yield parts.
let val = yield 99;
_process.next(10);
now the val will be 10
Usages
References:
You can also wrap the output of a cmdlet (or pipeline) in @()
to ensure that what you get back is an array rather than a single item.
For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:
$results = @( dir c:\autoexec.bat)
One more thing... an empty array (like to initialize a variable) is denoted @()
.
This is a tricky one. I could not find a way to select the 'no file chosen' element so I created a mask using the :after pseudo selector.
My solution also requires the use of the following pseudo selector to style the button:
::-webkit-file-upload-button
Try this: http://jsfiddle.net/J8Wfx/1/
FYI: This will only work in webkit browsers.
P.S if anyone knows how to view webkit pseudo selectors like the one above in the webkit inspector please let me know
I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.
<asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />
It is retrievable from Javascript - as window.location.hash
. From there you could send it to the server with Ajax for example, or encode it and put it into URLs which can then be passed through to the server-side.
Here's a nice jQuery Tooltip:
To implement this, just follow these steps:
Add this code in your <head></head>
tags:
<script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
<script type="text/javascript">
$("[title]").tooltip();
</script>
<style type="text/css">
/* tooltip styling. by default the element to be styled is .tooltip */
.tooltip {
display:none;
background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
font-size:12px;
height:70px;
width:160px;
padding:25px;
color:#fff;
}
</style>
On the HTML elements that you want to have the tooltip, just add a title
attribute to it. Whatever text is in the title attribute will be in the tooltip.
Note: When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.
If certain maven modules are not compiling check if their pom.xml is on the "ignored files" list. In IntelliJ goto
preferences -> project settings -> maven -> ignored files
and check if the related pom.xml is ignored.
one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:
def consume_exceptions(gen):
action = next(gen)
while True:
try:
result = action()
except Exception:
# if the action fails, send a sentinel
result = None
try:
action = gen.send(result)
except StopIteration:
# if the generator is all used up, result is the return value.
return result
a generator that would be compatible with this would look like this:
def do_smth1():
1 / 0
def do_smth2():
print "YAY"
def do_many_things():
a = yield do_smth1
b = yield do_smth2
yield "Done"
>>> consume_exceptions(do_many_things())
YAY
Note that do_many_things()
does not call do_smth*
, it just yields them, and consume_exceptions
calls them on its behalf
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
you can use
android.R.drawable.xxx
(use autocomplete to see whats in there)
Or download the stuff from http://developer.android.com/design/downloads/index.html
Create the Intent like this:
Uri uriSms = Uri.parse("smsto:1234567899");
Intent intentSMS = new Intent(Intent.ACTION_SENDTO, uriSms);
intentSMS.putExtra("sms_body", "The SMS text");
startActivity(intentSMS);
You can do one of two things:
^\s*$
; a match means the string is "empty"
^
, $
are the beginning and end of string anchors respectively\s
is a whitespace character*
is zero-or-more repetition of\S
; an occurrence means the string is NOT "empty"
\S
is the negated version of \s
(note the case difference)\S
therefore matches any non-whitespace characterRegexOptions.ECMAScript
, \s
matches things like ellipsis …
count = -1
n = int(raw_input("how many primes you want starting from 2 "))
primes=[[]]*n
for p in range(2, n**2):
for i in range(2, p):
if p % i == 0:
break
else:
count +=1
primes[count]= p
if count == n-1:
break
print (primes)
print 'Done'
You can also setup multiple domain with nginx, forwarding to multiple node.js processes.
For example to achieve these:
These ports (4000 and 5000) should be used to listen the app requests in your app code.
/etc/nginx/sites-enabled/domain1
server {
listen 80;
listen [::]:80;
server_name domain1.com;
access_log /var/log/nginx/domain1.access.log;
location / {
proxy_pass http://127.0.0.1:4000/;
}
}
In /etc/nginx/sites-enabled/domain2
server {
listen 80;
listen [::]:80;
server_name domain2.com;
access_log /var/log/nginx/domain2.access.log;
location / {
proxy_pass http://127.0.0.1:5000/;
}
}
In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:
<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>
Where MyActivity
is the one you want to stay in landscape.
The android:configChanges=...
line prevents onResume()
, onPause()
from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.
Note: keyboardHidden
and orientation
are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation
.
<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> HtmlSelect Example </title>
<script runat="server">
void Button_Click (Object sender, EventArgs e)
{
Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
+ ", value: " + Select1.Value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
Select an item:
<select id="Select1" runat="server">
<option value="Text for Item 1" selected="selected"> Item 1 </option>
<option value="Text for Item 2"> Item 2 </option>
<option value="Text for Item 3"> Item 3 </option>
<option value="Text for Item 4"> Item 4 </option>
</select>
<button onserverclick="Button_Click" runat="server" Text="Submit"/>
<asp:Label id="Label1" runat="server"/>
</form>
</body>
</html>
Source from Microsoft. Hope this is helpful!
For those that want to get a sum of all the ASCII codes for a string:
'Foobar'
.split('')
.map(x=>x.charCodeAt(0))
.reduce((a,b)=>a+b);
Or, ES6:
[...'Foobar']
.map(char => char.charCodeAt(0))
.reduce((current, previous) => previous + current)
I had a same issue.
from PIL import Image
instead of
import Image
fixed the issue
Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with
git rebase
or git pull --rebase
Here is a good article explaining the difference between git pull
& git pull --rebase
.
https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
The constructor is called only once, so you can safely do what you want, however the disadvantage of calling methods from within the constructor, rather than directly, is that you don't get direct feedback if the method fails. This gets more difficult the more methods you call.
One solution is to provide methods that you can call to query the 'health' of the object once it's been constructed. For example the method isConfigOK()
can be used to see if the config read operation was OK.
Another solution is to throw exceptions in the constructor upon failure, but it really depends on how 'fatal' these failures are.
class A
{
Map <String,String> config = null;
public A()
{
readConfig();
}
protected boolean readConfig()
{
...
}
public boolean isConfigOK()
{
// Check config here
return true;
}
};
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
This is how we do it.
fun Fragment.emptyDatabase() {
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
withContext(Dispatchers.IO) {
Database.getInstance(requireActivity()).clearAllTables()
}
}
}
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
I would do this:
// add appropriate media query if required to target mobile nav only
.nav { overflow-y: hidden !important }
This should make sure the nav block doesn't stretch downpage and covers the page content.
You can do it in much easier way:
def ReLU(x):
return x * (x > 0)
def dReLU(x):
return 1. * (x > 0)
For those who want to filter from an array of objects using any key:
function filterItems(items, searchVal) {_x000D_
return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
}_x000D_
let data = [_x000D_
{ "name": "apple", "type": "fruit", "id": 123234 },_x000D_
{ "name": "cat", "type": "animal", "id": 98989 },_x000D_
{ "name": "something", "type": "other", "id": 656565 }]_x000D_
_x000D_
_x000D_
console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
console.log("Filtered by id: ", filterItems(data, 656565));
_x000D_
filter from an array of the JSON objects:**
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
Unfortunately MSTest STILL only really has the ExpectedException attribute (just shows how much MS cares about MSTest) which IMO is pretty awful because it breaks the Arrange/Act/Assert pattern and it doesnt allow you to specify exactly which line of code you expect the exception to occur on.
When I'm using (/forced by a client) to use MSTest I always use this helper class:
public static class AssertException
{
public static void Throws<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (Exception ex)
{
Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
return;
}
Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
}
public static void Throws<TException>(Action action, string expectedMessage) where TException : Exception
{
try
{
action();
}
catch (Exception ex)
{
Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
Assert.AreEqual(expectedMessage, ex.Message, "Expected exception with a message of '" + expectedMessage + "' but exception with message of '" + ex.Message + "' was thrown instead.");
return;
}
Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
}
}
Example of usage:
AssertException.Throws<ArgumentNullException>(() => classUnderTest.GetCustomer(null));
It should probably also be mentioned that you can simply chain a catch()
function after the call of your async operation because under the hood still a promise is returned.
await foo().catch(error => console.log(error));
This way you can avoid the try/catch
syntax if you do not like it.
Dictionary:
dict = {'a':'a','b':'b','c':'c'}
array of dictionary
arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})
To grant permissions to all of the existing tables in the schema use:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>
To specify default permissions that will be applied to future tables use:
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema>
GRANT <privileges> ON TABLES TO <role>;
e.g.
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;
If you use SERIAL
or BIGSERIAL
columns then you will probably want to do the same for SEQUENCES
, or else your INSERT
will fail (Postgres 10's IDENTITY
doesn't suffer from that problem, and is recommended over the SERIAL
types), i.e.
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;
See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.
Ref:
if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {
$filefound = '0';
}
Safer is to use lift
so you can extract the value if it exists and fail gracefully if it does not.
data.lift(2)
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None
Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.
Explanation:
This works because List's apply
(which sugars to just parentheses, e.g. l(index)
) is like a partial function that is defined wherever the list has an element. The List.lift
method turns the partial apply
function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.
In case you want to format number for view rather than for calculation you can use this
function numberFormat( number ){
var digitCount = (number+"").length;
var formatedNumber = number+"";
var ind = digitCount%3 || 3;
var temparr = formatedNumber.split('');
if( digitCount > 3 && digitCount <= 6 ){
temparr.splice(ind,0,',');
formatedNumber = temparr.join('');
}else if (digitCount >= 7 && digitCount <= 15) {
var temparr2 = temparr.slice(0, ind);
temparr2.push(',');
temparr2.push(temparr[ind]);
temparr2.push(temparr[ind + 1]);
// temparr2.push( temparr[ind + 2] );
if (digitCount >= 7 && digitCount <= 9) {
temparr2.push(" million");
} else if (digitCount >= 10 && digitCount <= 12) {
temparr2.push(" billion");
} else if (digitCount >= 13 && digitCount <= 15) {
temparr2.push(" trillion");
}
formatedNumber = temparr2.join('');
}
return formatedNumber;
}
Input: {Integer} Number
Outputs: {String} Number
22,870 => if number 22870
22,87 million => if number 2287xxxx (x can be whatever)
22,87 billion => if number 2287xxxxxxx
22,87 trillion => if number 2287xxxxxxxxxx
You get the idea
It breaks semantics, that's all. It works fine, but there may be screen readers or something down the road that won't enjoy processing your HTML if you "break semantics".