After struggling with this for some time I eventually came up with the following, so that the config object would only be loaded once, when called up from separate modules. The metaclass allows a global class instance to be stored in the builtins dict, which at present appears to be the neatest way of storing a proper program global.
import builtins
# -----------------------------------------------------------------------------
# So..... you would expect that a class would be "global" in scope, however
# when different modules use this,
# EACH ONE effectively has its own class namespace.
# In order to get around this, we use a metaclass to intercept
# "new" and provide the "truly global metaclass instance" if it already exists
class MetaConfig(type):
def __new__(cls, name, bases, dct):
try:
class_inst = builtins.CONFIG_singleton
except AttributeError:
class_inst = super().__new__(cls, name, bases, dct)
builtins.CONFIG_singleton = class_inst
class_inst.do_load()
return class_inst
# -----------------------------------------------------------------------------
class Config(metaclass=MetaConfig):
config_attr = None
@classmethod
def do_load(cls):
...<load-cfg-from-file>...
If you send the form empty, $_POST['mail'] will still be sent, but the value is empty. To check if the field is empty you need to check
if(isset($_POST["mail"]) && trim($_POST["mail"]) != "") { .. }
You could simply go to phpmyadmin.conf file and change "deny from all" to "allow from all". Well it worked for me, hope it works for you as well.
Use this:
SELECT s.name AS Student, c.name AS Course
FROM student s
LEFT JOIN (bridge b CROSS JOIN course c)
ON (s.id = b.sid AND b.cid = c.id);
I'll interpret your question as two questions: 1) why ->
even exists, and 2) why .
does not automatically dereference the pointer. Answers to both questions have historical roots.
Why does ->
even exist?
In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator ->
had very exclusive meaning, not synonymous with *
and .
combination
The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare
struct S {
int a;
int b;
};
and name a
would stand for offset 0, while name b
would stand for offset 2 (assuming int
type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare
struct X {
int a;
int x;
};
and that would be OK, since the name a
would consistently stand for offset 0. But this additional declaration
struct Y {
int b;
int a;
};
would be formally invalid, since it attempted to "redefine" a
as offset 2 and b
as offset 0.
And this is where the ->
operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these
int i = 5;
i->b = 42; /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */
The first assignment was interpreted by the compiler as "take address 5
, add offset 2
to it and assign 42
to the int
value at the resultant address". I.e. the above would assign 42
to int
value at address 7
. Note that this use of ->
did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).
This sort of trickery was not possible with *
and .
combination. You could not do
(*i).b = 42;
since *i
is already an invalid expression. The *
operator, since it is separate from .
, imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the ->
operator, which is independent from the type of the left-hand operand.
As Keith noted in the comments, this difference between ->
and *
+.
combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1
be of pointer type, the expression E1->MOS
is exactly equivalent to (*E1).MOS
Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of ->
operator became fully identical to the functionality of *
and .
combination.
Why can't .
dereference the pointer automatically?
Again, in CRM version of the language the left operand of the .
operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->
, as explained above). Note that CRM did not require the left operand of .
to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this
struct S { int a, b; };
struct T { float x, y, z; };
struct T c;
c.b = 55;
In this case the compiler would write 55
into an int
value positioned at byte-offset 2 in the continuous memory block known as c
, even though type struct T
had no field named b
. The compiler would not care about the actual type of c
at all. All it cared about is that c
was an lvalue: some sort of writable memory block.
Now note that if you did this
S *s;
...
s.b = 42;
the code would be considered valid (since s
is also an lvalue) and the compiler would simply attempt to write data into the pointer s
itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.
I.e. in that version of the language your proposed idea about overloading operator .
for pointer types would not work: operator .
already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.
Of course, this weird functionality is not a very strong reason against introducing overloaded .
operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.
(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)
This is Simple and best calculation for me and may be for you.
try {
/// String CurrDate= "10/6/2013";
/// String PrvvDate= "10/7/2013";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy");
date1 = df.parse(CurrDate);
date2 = df.parse(PrvvDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e1) {
System.out.println("exception " + e1);
}
You do not need to create sub directory. Just create blob container and use file name like the variable filename as below code:
string filename = "document/tech/user-guide.pdf";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConnectionString);
CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(filename);
blob.StreamWriteSizeInBytes = 20 * 1024;
blob.UploadFromStream(fileStream); // fileStream is System.IO.Stream
Unfortunately, ­
's support is so inconsistent between browsers that it can't really be used.
QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.
2013 edit: According to QuirksMode, ­
now works/is supported on all major browsers.
Firstly import:-
import hashlib, uuid
Then change your code according to this in your method:
uname = request.form["uname"]
pwd=request.form["pwd"]
salt = hashlib.md5(pwd.encode())
Then pass this salt and uname in your database sql query, below login is a table name:
sql = "insert into login values ('"+uname+"','"+email+"','"+salt.hexdigest()+"')"
this works:
window.onscroll = function (e) {
// called when the window is scrolled.
}
edit:
you said this is a function in a TimeInterval..
Try doing it like so:
userHasScrolled = false;
window.onscroll = function (e)
{
userHasScrolled = true;
}
then inside your Interval insert this:
if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}
I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.
Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)
Oracle Instant Client
ODBC Drivers
Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.
After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.
If you are using 32-bit ubuntu (my case) then it is most likely that Android Studio has downloaded 64-bit version of adb
and fastboot
inside your sdk/platform-tools
folder. I think you already have installed adb (and fastboot). If you haven't then run these commands in terminal:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install android-tools-adb android-tools-fastboot
This will install 32-bit version of adb
and fastboot
. Now just replace the 64-bit adb
and fastboot
executable files in sdk/platform-tools
with the installed 32-bit versions:
cp /usr/bin/adb <path-to-your-adt-sdk-package>/sdk/platform-tools/adb
cp /usr/bin/fastboot <path-to-your-adt-sdk-package>/sdk/platformtools/fastboot
Now your android studio should be able to run your App in your device.
First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.
As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.
Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable.
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
Since git is a distributed VCS, your local repository contains all of the information. No downloading is necessary; you just need to extract the content you want from the repo at your fingertips.
If you haven't committed the deletion, just check out the files from your current commit:
git checkout HEAD <path>
If you have committed the deletion, you need to check out the files from a commit that has them. Presumably it would be the previous commit:
git checkout HEAD^ <path>
but if it's n
commits ago, use HEAD~n
, or simply fire up gitk
, find the SHA1 of the appropriate commit, and paste it in.
Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
An array is an ordered sequence of zero or more values.
The terms "object" and "array" come from the conventions of JavaScript.
Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.
In addition to cookies and localStorage
, there's at least one other place you can store "semi-persistent" client data: window.name
. Any string value you assign to window.name
will stay there until the window is closed.
To test it out, just open the console and type window.name = "foo"
, then refresh the page and type window.name
; it should respond with foo
.
This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage
for whatever reason (legacy clients), it may be an option to consider.
window.name
has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window
. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.
Note that window.name
can only store strings, but with the wide availability of JSON
, this shouldn't be much of an issue even for complex data.
Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.
Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.
Incase of string literals(character arrays defined at declaration), they are automatically
appended by \0
.
printf
prints using the format specifier and the address provided. Since, you use %s
it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'
OVERVIEW
I have written a simple semantic hack for this using @AshutoshMehra
response. You code looks really readable this way!
MACRO
#include <time.h>
#ifndef SYSOUT_F
#define SYSOUT_F(f, ...) _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif
#ifndef speedtest__
#define speedtest__(data) for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif
USAGE
speedtest__("Block Speed: ")
{
// The code goes here
}
OUTPUT
Block Speed: 0.127000000s
Only the thread unless your process has a single thread.
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ----
to -----BEGIN RSA PUBLIC KEY-----
and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).
This article has a good explanation about both formats.
What you get in an RSA PUBLIC KEY
is closer to the content of a PUBLIC KEY
, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY
also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse
and -strparse 19
, as described in this answer.
EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY
structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER
:
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
265:d=1 hl=2 l= 3 prim: INTEGER :010001
To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:
The "ssh-rsa" key format has the following specific encoding: string "ssh-rsa" mpint e mpint n
For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61
. The first four bytes (00 00 00 07
) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61
=ssh-rsa
, followed by the exponent of length 1 (00 00 00 01 25
) and the modulus of length 256 (00 00 01 00 7f ...
).
Also, you can check the compatibility troubleshooting
Check the detail steps, and other ways to always open VS as Admin at Visual Studio requires the application to have elevated permissions.
You want the NPGSQL library. Your only other alternative is ODBC.
The following css property will do it
position: fixed;
I hope this help.
In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.
Long time ago, but still needed.
info - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
list - gcc -Q --help=optimizers test.c | grep enabled
disable as many as you like with:
gcc **-fno-web** -Q --help=optimizers test.c | grep enabled
This is the perfect kind of field to define as CHAR 36, by the way, not VARCHAR 36, since each value will have the exact same length. And you'll use less storage space, since you don't need to store the data length for each value, just the value.
Declare extern int x;
in file.h.
And define int x;
only in one cpp file.cpp.
Use ClipboardManager#setPrimaryClip
method:
import android.content.ClipboardManager;
// ...
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
If you want to reassign an element in an array, you can do the following:
var blah = ['Jan', 'Fed', 'Apr'];
console.log(blah);
function reassign(array, index, newValue) {
array[index] = newValue;
return array;
}
reassign(blah, [2], 'Mar');
It will work like this:
$('input[type="email"]').keyup(function() {
if ($(this).val() != '') {
$(':button[type="submit"]').prop('disabled', false);
} else {
$(':button[type="submit"]').prop('disabled', true);
}
});
Make sure there is an 'disabled' attribute in your HTML
Try to delete the folder c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u
manually and then retry the pip command.
On Mac:
Install easy_install
curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python
Install pip
sudo easy_install pip
Now, you could install external modules. For example
pip install regex # This is only an example for installing other modules
If you want just the time in a shell variable then this works:
var=`{ time <command> ; } 2>&1 1>/dev/null`
You can use VC CRT Heap-Check macros for _CrtSetDbgFlag: _CRTDBG_CHECK_ALWAYS_DF or _CRTDBG_CHECK_EVERY_16_DF.._CRTDBG_CHECK_EVERY_1024_DF.
shareing for others:
read stream line by line,should be good for large files piped into stdin, my version:
var n=0;
function on_line(line,cb)
{
////one each line
console.log(n++,"line ",line);
return cb();
////end of one each line
}
var fs = require('fs');
var readStream = fs.createReadStream('all_titles.txt');
//var readStream = process.stdin;
readStream.pause();
readStream.setEncoding('utf8');
var buffer=[];
readStream.on('data', (chunk) => {
const newlines=/[\r\n]+/;
var lines=chunk.split(newlines)
if(lines.length==1)
{
buffer.push(lines[0]);
return;
}
buffer.push(lines[0]);
var str=buffer.join('');
buffer.length=0;
readStream.pause();
on_line(str,()=>{
var i=1,l=lines.length-1;
i--;
function while_next()
{
i++;
if(i<l)
{
return on_line(lines[i],while_next);
}
else
{
buffer.push(lines.pop());
lines.length=0;
return readStream.resume();
}
}
while_next();
});
}).on('end', ()=>{
if(buffer.length)
var str=buffer.join('');
buffer.length=0;
on_line(str,()=>{
////after end
console.error('done')
////end after end
});
});
readStream.resume();
When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.
SQL Server 2019 Express Edition (English):
SQL Server 2017 Express Edition (English):
SQL Server 2016 with SP2 Express Edition (English):
SQL Server 2016 with SP1 Express Edition (English):
And here is how to use Fiddler.
Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd
for the search term.
(source: winaero.com)
I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.
Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different
Table structure
CREATE TABLE ITEMS (
N INTEGER NOT NULL,
S TEXT NOT NULL
);
INSERT INTO ITEMS
SELECT
(random()*1000000)::integer AS n,
md5(random()::text) AS s
FROM
generate_series(1,1000000);
CREATE INDEX N_INDEX ON ITEMS(N);
Performing JOIN
with GROUP BY
in subquery without LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN (
SELECT
COUNT(1), n
FROM ITEMS
GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);
The results
Merge Join (cost=0.87..637500.40 rows=23 width=37)
Merge Cond: (i.n = items.n)
-> Index Scan using n_index on items i (cost=0.43..101.28 rows=23 width=37)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..626631.11 rows=861418 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..593016.93 rows=10000000 width=4)
Using LATERAL
EXPLAIN
SELECT
I.*
FROM ITEMS I
INNER JOIN LATERAL (
SELECT
COUNT(1), n
FROM ITEMS
WHERE N = I.N
GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);
Results
Nested Loop (cost=9.49..1319.97 rows=276 width=37)
-> Bitmap Heap Scan on items i (cost=9.06..100.20 rows=23 width=37)
Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
-> Bitmap Index Scan on n_index (cost=0.00..9.05 rows=23 width=0)
Index Cond: (n = ANY ('{243477,997947}'::integer[]))
-> GroupAggregate (cost=0.43..52.79 rows=12 width=12)
Group Key: items.n
-> Index Only Scan using n_index on items (cost=0.43..52.64 rows=12 width=4)
Index Cond: (n = i.n)
My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)
the Jquery append function returns a jQuery object so you can just tag a method on the end
$("#root").append(child).anotherJqueryMethod();
This was our solution for replacing master on a corporate gitHub repository while maintaining history.
push -f
to master on corporate repositories is often disabled to maintain branch history. This solution worked for us.
git fetch desiredOrigin
git checkout -b master desiredOrigin/master // get origin master
git checkout currentBranch // move to target branch
git merge -s ours master // merge using ours over master
// vim will open for the commit message
git checkout master // move to master
git merge currentBranch // merge resolved changes into master
push your branch to desiredOrigin
and create a PR
32-bit Java is limited to approximately 1.4 to 1.6 GB.
Quote
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.
In case you don't want to use MoreLINQ and want to get linear time, you can also use Aggregate
:
var maxItem =
items.Aggregate(
new { Max = Int32.MinValue, Item = (Item)null },
(state, el) => (el.ID > state.Max)
? new { Max = el.ID, Item = el } : state).Item;
This remembers the current maximal element (Item
) and the current maximal value (Item
) in an anonymous type. Then you just pick the Item
property. This is indeed a bit ugly and you could wrap it into MaxBy
extension method to get the same thing as with MoreLINQ:
public static T MaxBy(this IEnumerable<T> items, Func<T, int> f) {
return items.Aggregate(
new { Max = Int32.MinValue, Item = default(T) },
(state, el) => {
var current = f(el.ID);
if (current > state.Max)
return new { Max = current, Item = el };
else
return state;
}).Item;
}
Yet another options is to use perl -s, eg:
#!/usr/bin/perl -s
print "value of -x: $x\n";
print "value of -name: $name\n";
Then call it like this :
% ./myprog -x -name=Jeff
value of -x: 1
value of -name: Jeff
Or see the original article for more details:
You can use ClickableSpan as described in this post
TextView myTextView = new TextView(this);
String myString = "Some text [clickable]";
int i1 = myString.indexOf("[");
int i2 = myString.indexOf("]");
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
myTextView.setText(myString, BufferType.SPANNABLE);
Spannable mySpannable = (Spannable)myTextView.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) { /* do something */ }
};
mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Because I will not admit the YUI/Crockford factory plan and because I like to keep things self contained and extensible this is my variation:
function Person(params)
{
this.name = params.name || defaultnamevalue;
this.role = params.role || defaultrolevalue;
if(typeof(this.speak)=='undefined') //guarantees one time prototyping
{
Person.prototype.speak = function() {/* do whatever */};
}
}
var Robert = new Person({name:'Bob'});
where ideally the typeof test is on something like the first method prototyped
Firstable, make sure that you Antivirus software doesn't block SSL2.
Because I could not solve a problem for a long time and only disabling the antivirus helped me
Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript
Tried with all the methods but nothing worked
I got one reference from git hub.
To use type script imports with nodejs, i installed below packages.
1. npm i typescript
2. npm i ts-node
Won't require type: module in package.json
E:g
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:
function Field() {
return (
<View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>
);
}
Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:
renderFields() {
const noGuest = this.state.guest;
const fields = [];
for (let i=0; i < noGuest; i++) {
// Try avoiding the use of index as a key, it has to be unique!
fields.push(
<Field key={"guest_"+i} />
);
}
return fields;
}
render () {
return (
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>
{this.renderFields()}
</View>;
)
}
However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!
We love Kubernetes is because once we give them what we want it goes on to figure out how to achieve it without our any involvement.
"create" is like playing GOD by taking things into our own hands. It is good for local debugging when you only want to work with the POD and not care abt Deployment/Replication Controller.
"apply" is playing by the rules. "apply" is like a master tool that helps you create and modify and requires nothing from you to manage the pods.
You need a click listener which calls addActivityItem
if less than 2 options exist:
var activities = document.getElementById("activitySelector");
activities.addEventListener("click", function() {
var options = activities.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
addActivityItem();
}
});
activities.addEventListener("change", function() {
if(activities.value == "addNew")
{
addActivityItem();
}
});
function addActivityItem() {
// ... Code to add item here
}
A live demo is here on JSfiddle.
For this you need to update your Project Facets setting.
Project (right click) -> Properties -> Project Facets from left navigation.
If it is not open...click on the link, Check the Dynamic Web Module Check Box and select the respective version (Probably 2.4). Click on Apply Button and then Click on OK.
Here's mine:
set statusline=
set statusline +=%1*\ %n\ %* "buffer number
set statusline +=%5*%{&ff}%* "file format
set statusline +=%3*%y%* "file type
set statusline +=%4*\ %<%F%* "full path
set statusline +=%2*%m%* "modified flag
set statusline +=%1*%=%5l%* "current line
set statusline +=%2*/%L%* "total lines
set statusline +=%1*%4v\ %* "virtual column number
set statusline +=%2*0x%04B\ %* "character under cursor
And here's the colors I used:
hi User1 guifg=#eea040 guibg=#222222
hi User2 guifg=#dd3333 guibg=#222222
hi User3 guifg=#ff66ff guibg=#222222
hi User4 guifg=#a0ee40 guibg=#222222
hi User5 guifg=#eeee40 guibg=#222222
To get a char
from a Scanner
, you can use the findInLine
method.
Scanner sc = new Scanner("abc");
char ch = sc.findInLine(".").charAt(0);
System.out.println(ch); // prints "a"
System.out.println(sc.next()); // prints "bc"
If you need a bunch of char
from a Scanner
, then it may be more convenient to (perhaps temporarily) change the delimiter to the empty string. This will make next()
returns a length-1 string every time.
Scanner sc = new Scanner("abc");
sc.useDelimiter("");
while (sc.hasNext()) {
System.out.println(sc.next());
} // prints "a", "b", "c"
With Swift 5, Array
, like other Sequence
Protocol conforming objects (Dictionary
, Set
, etc), has two methods called max()
and max(by:)
that return the maximum element in the sequence or nil
if the sequence is empty.
Array
's max()
methodIf the element type inside your sequence conforms to Comparable
protocol (may it be String
, Float
, Character
or one of your custom class or struct), you will be able to use max()
that has the following declaration:
@warn_unqualified_access func max() -> Element?
Returns the maximum element in the sequence.
The following Playground codes show to use max()
:
let intMax = [12, 15, 6].max()
let stringMax = ["bike", "car", "boat"].max()
print(String(describing: intMax)) // prints: Optional(15)
print(String(describing: stringMax)) // prints: Optional("car")
class Route: Comparable, CustomStringConvertible {
let distance: Int
var description: String { return "Route with distance: \(distance)" }
init(distance: Int) {
self.distance = distance
}
static func ==(lhs: Route, rhs: Route) -> Bool {
return lhs.distance == rhs.distance
}
static func <(lhs: Route, rhs: Route) -> Bool {
return lhs.distance < rhs.distance
}
}
let routes = [
Route(distance: 20),
Route(distance: 30),
Route(distance: 10)
]
let maxRoute = routes.max()
print(String(describing: maxRoute)) // prints: Optional(Route with distance: 30)
Array
's max(by:)
methodIf the element type inside your sequence does not conform to Comparable
protocol, you will have to use max(by:)
that has the following declaration:
@warn_unqualified_access func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element?
Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
The following Playground codes show to use max(by:)
:
let dictionary = ["Boat" : 15, "Car" : 20, "Bike" : 40]
let keyMaxElement = dictionary.max(by: { (a, b) -> Bool in
return a.key < b.key
})
let valueMaxElement = dictionary.max(by: { (a, b) -> Bool in
return a.value < b.value
})
print(String(describing: keyMaxElement)) // prints: Optional(("Car", 20))
print(String(describing: valueMaxElement)) // prints: Optional(("Bike", 40))
class Route: CustomStringConvertible {
let distance: Int
var description: String { return "Route with distance: \(distance)" }
init(distance: Int) {
self.distance = distance
}
}
let routes = [
Route(distance: 20),
Route(distance: 30),
Route(distance: 10)
]
let maxRoute = routes.max(by: { (a, b) -> Bool in
return a.distance < b.distance
})
print(String(describing: maxRoute)) // prints: Optional(Route with distance: 30)
In my case I wanted to load the same form each time I click, I didn't want the changes I've made on the file stays. It may not relevant to this post exactly, but this could be a potential solution on the client side without setting config for require. Instead of sending the contents directly, you can make a copy of the required file and keep the actual file intact.
LoadFile(filePath){
const file = require(filePath);
const result = angular.copy(file);
return result;
}
There may be other potential solutions out there (I am still looking) but thus far in my search for the same functionality, I have only found http://www.maxivista.com/ . As far as I can tell through, it only supports a dual monitor, not multiple.
Store it in a field of type long
. See Date.getTime()
and new Date(long)
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table... You can adjust the insertion values according to your table.
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
Its not especially Hamcrest, but I think it worth to mention here. What I use quite often in Java8 is something like:
assertTrue(myClass.getMyItems().stream().anyMatch(item -> "foo".equals(item.getName())));
(Edited to Rodrigo Manyari's slight improvement. It's a little less verbose. See comments.)
It may be a little bit harder to read, but I like the type and refactoring safety. Its also cool for testing multiple bean properties in combination. e.g. with a java-like && expression in the filter lambda.
I don't have enough reputation to comment, but this is referring to dsissitka's answer. It works on Windows 10 as well.
To reiterate, the commands are:
cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081
Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:
>>> 0.4/100.
0.0040000000000000001
If you actually want a decimal value, do this:
>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")
That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.
Rails 4 (other Rails 4 answers have problems):
def change
change_column_null(:users, :admin, false, <put a default value here> )
# change_column(:users, :admin, :string, :default => "")
end
Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null
does exactly that. See documentation for more details.
Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.
Try this, replacing .myClassName
with the actual name of the class (but keep the period at the beginning).
$('.myClassName').each(function() {
alert( this.id );
});
So if the class is "test", you'd do $('.test').each(func...
.
This is the specific form of .each()
that iterates over a jQuery object.
The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t
.
Using that form of $.each()
, you would need to do it like this:
$.each($('.myClassName'), function() {
alert( this.id );
});
...which will have the same result as the example above.
Step 1: See all your databases:
show dbs
Step 2: Select the database
use your_database_name
Step 3: Show the collections
show collections
This will list all the collections in your selected database.
Step 4: See all the data
db.collection_name.find()
or
db.collection_name.find().pretty()
Despite !important
usage being generally frowned upon, this is the offending code in bootstrap.css
which prevents table rows from being printed with background-color
.
.table td,
.table th {
background-color: #fff !important;
}
Let's assume you are trying to style the following HTML:
<table class="table">
<tr class="highlighted">
<td>Name</td>
<td>School</td>
<td>Height</td>
<td>Weight</td>
</tr>
</table>
To override this CSS, place the following (more specific) rule in your stylesheet:
@media print {
table tr.highlighted > td {
background-color: rgba(247, 202, 24, 0.3) !important;
}
}
This works because the rule is more specific than the bootstrap default.
Does the second query return any results from the 17th, or just from the 18th?
The first query will only return results from the 17th, or midnight on the 18th.
Try this instead
select *
from LOGS
where check_in >= CONVERT(datetime,'2013-10-17')
and check_in< CONVERT(datetime,'2013-10-19')
If you are not averse to using find
, I like its -prune
feature:
find [directory] \
-name "pattern_to_exclude" -prune \
-o -name "another_pattern_to_exclude" -prune \
-o -name "pattern_to_INCLUDE" -print0 \
| xargs -0 -I FILENAME grep -IR "pattern" FILENAME
On the first line, you specify the directory you want to search. .
(current directory) is a valid path, for example.
On the 2nd and 3rd lines, use "*.png"
, "*.gif"
, "*.jpg"
, and so forth. Use as many of these -o -name "..." -prune
constructs as you have patterns.
On the 4th line, you need another -o
(it specifies "or" to find
), the patterns you DO want, and you need either a -print
or -print0
at the end of it. If you just want "everything else" that remains after pruning the *.gif
, *.png
, etc. images, then use
-o -print0
and you're done with the 4th line.
Finally, on the 5th line is the pipe to xargs
which takes each of those resulting files and stores them in a variable FILENAME
. It then passes grep
the -IR
flags, the "pattern"
, and then FILENAME
is expanded by xargs
to become that list of filenames found by find
.
For your particular question, the statement may look something like:
find . \
-name "*.png" -prune \
-o -name "*.gif" -prune \
-o -name "*.svn" -prune \
-o -print0 | xargs -0 -I FILES grep -IR "foo=" FILES
Although its too late to answer this question, but still for those guys who came here to see the solution of same problem just like me and didn't get a satisfactory answer on this page, The reason is that you don't have your file in the form of .rb extension. You most probably have it in simple text mode. Let me elaborate. Binding up the whole solution on the page, here you go (assuming you filename is abc.rb or at least you created abc):
Type in terminal window:
cd ~/to/the/program/location
ruby abc.rb
and you are done
If the following error occurs
ruby: No such file or directory -- abc.rb (LoadError)
Then go to the directory in which you have the abc file, rename it as abc.rb Close gedit and reopen the file abc.rb. Apply the same set of commands and success!
GitHub Repositories are used to store all the files, folders and other resources which you care about.
Git Project : It is also one of the Resource in Git Repository and main use of it is to manage the projects with a visual board. If you create a project in Git Repository it create a visual board like a Kanban board to manage the project.
In this way, you can have multiple projects in a repository.
Try calling it directly with class name Book.myInt
C:\Users\\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell
I had the same issue (on windows server 2003), check in the IIS console if you have allowed ASP.NET v4 service extension (under IIS / ComputerName / Web Service extensions)
Call the marker.setIcon('newImage.png')
... Look here for the docs.
Are you asking about the actual way to do it? You could just create each div
, and a add a mouseover
and mouseout
listener that would change the icon and back for the markers.
You can do it in various ways.
The old conventional way is,
maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a) #calculate length of the array
for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
maxIndexList.append(i)
print(maxIndexList) #finally print the list
Another way without calculating the length of the list and storing maximum value to any variable,
maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
if i==max(a): #max(a) returns a maximum value of list.
maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index
print(maxIndexList)
We can do it in Pythonic and smart way! Using list comprehension just in one line,
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
All my codes are in Python 3.
You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.
Assuming that your table name is city
and your existing Primary Key is pk_city
, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time
is NULL
, otherwise you won't be able to re-create the constraint.
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.
'1.0.0.0/8'
to '191.0.0.0/8'
are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:
import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
'0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
'169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24',
'192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
'203.0.113.0/24', '224.0.0.0/4', '240.0.0.0/4', '255.255.255.255/32'
)
Generates a JSON dump of IP Addresses and associated Geo information.
Note that the valid public IP Address range is
from '1.0.0.0/8'
to '191.0.0.0/8'
excluding the reserved
Private IP Address ranges shown lower down in this readme.
docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0' geo-ip ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0' geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip
A little faster option for scanning all valid public addresses:
for i in $(seq 1 191); do \
docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
sleep 1; \
done
This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:
{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
"continent": "North America", "continent_code": "NA",
"state": "California", "country": "United States", "latitude": 37.418,
"iso_code": "US", "state_code": "CA", "aso": "PubNub",
"asn": "11404", "zip_code": "94107"}
The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses
The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home
This just works on React & React Native
const data = require('./data/photos.json');
console.log('[-- typeof data --]', typeof data); // object
const fotos = data.xs.map(item => {
return { uri: item };
});
Have a look at Fuel library, a sample GET request
"https://httpbin.org/get"
.httpGet()
.responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
}
is Result.Success -> {
val data = result.get()
}
}
}
// You can also use Fuel.get("https://httpbin.org/get").responseString { ... }
// You can also use FuelManager.instance.get("...").responseString { ... }
A sample POST request
Fuel.post("https://httpbin.org/post")
.jsonBody("{ \"foo\" : \"bar\" }")
.also { println(it) }
.response { result -> }
Their documentation can be found here ?
simply call req.url
. that should do the work. you'll get something like /something?bla=foo
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
If you just want to make sure a certain file exists (f.ex. because it shoud be created in a different way than via ansible) and fail if it doesn't, then you can do this:
- name: sanity check that /some/path/file exists
command: stat /some/path/file
check_mode: no # always run
changed_when: false # doesn't change anything
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
Here are some paths for tabs:
https://codepen.io/mochime/pen/VxxzMW
<!-- left tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,10 _x000D_
a10 10 0 0 1 10 -10_x000D_
h 50 _x000D_
v 47_x000D_
h -50_x000D_
a10 10 0 0 1 -10 -10_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- right tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10 0 _x000D_
h 40_x000D_
a10 10 0 0 1 10 10_x000D_
v 27_x000D_
a10 10 0 0 1 -10 10_x000D_
h -40_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- tab tab :) -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,40 _x000D_
v -30_x000D_
a10 10 0 0 1 10 -10_x000D_
h 30_x000D_
a10 10 0 0 1 10 10_x000D_
v 30_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
The other answers explained the mechanics. I especially liked hossein-maktoobian's answer.
The paths in the pen do the brunt of the work, the values can be modified to suite whatever desired dimensions.
You should use Java 8 to solve this, based on the Android documentation you can do this by
clicking File > Project Structure
and change Source Compatibility
and Target Compatibility
.
and you can also configure it directly in the app-level build.gradle
file:
android {
...
// Configure only for each module that uses Java 8
// language features (either in its source code or
// through dependencies).
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Article is a model containing two fields - title and content
Create a view as pages/add-update-article.blade.php
@if(!isset($article->id))
<form method = "post" action="add-new-article-record">
@else
<form method = "post" action="update-article-record">
@endif
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="Enter title" name="title" value={{$article->title}}>
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" rows="5" id="content" name="content">
{{$article->content}}
</textarea>
<span class="text-danger">{{ $errors->first('content') }}</span>
</div>
<input type="hidden" name="id" value="{{{ $article->id }}}">
<button type="submit" class="btn btn-default">Submit</button>
</form>
Route(web.php): Create routes to controller
Route::get('/add-new-article', 'ArticlesController@new_article_form');
Route::post('/add-new-article-record', 'ArticlesController@add_new_article');
Route::get('/edit-article/{id}', 'ArticlesController@edit_article_form');
Route::post('/update-article-record', 'ArticlesController@update_article_record');
Create ArticleController.php
public function new_article_form(Request $request)
{
$article = new Articles();
return view('pages/add-update-article', $article)->with('article', $article);
}
public function add_new_article(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
Articles::create($request->all());
return redirect('articles');
}
public function edit_article_form($id)
{
$article = Articles::find($id);
return view('pages/add-update-article', $article)->with('article', $article);
}
public function update_article_record(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
$article = Articles::find($request->id);
$article->title = $request->title;
$article->content = $request->content;
$article->save();
return redirect('articles');
}
8 years later I stumbled upon this gem, and yet I don't believe OP's original question was really answered:
so I came up with the following code to trim the newline character
While the bufio.Reader
type supports a ReadLine()
method which both removes \r\n
and \n
it is meant as a low-level function which is awkward to use because repeated checks are necessary.
IMO an idiomatic way to remove whitespace is to use Golang's strings library:
input, _ = src.ReadString('\n')
// more specific to the problem of trailing newlines
actual = strings.TrimRight(input, "\r\n")
// or if you don't mind to trim leading and trailing whitespaces
actual := strings.TrimSpace(input)
See this example in action in the Golang playground: https://play.golang.org/p/HrOWH0kl3Ww
In Kotlin you can try this way to handle getActivity() null condition.
activity.let { // activity == getActivity() in java
//your code here
}
It will check activity is null or not and if not null then execute inner code.
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
Why does everyone have to complicate things. Just use jQuery!
<script type="text/javascript">
$(document).ready(function() {
$('#divID').click(function(){
$('#formID').submit();
)};
$('#submitID').hide();
)};
</script>
<form name="whatever" method="post" action="somefile.php" id="formID">
<input type="hidden" name="test" value="somevalue" />
<input type="submit" name="submit" value="Submit" id="submitID" />
</form>
<div id="divID">Click Me to Submit</div>
The div doesn't even have to be in the form to submit it. The only thing that is missing here is the include of jquery.js.
Also, there is a Submit button that is hidden by jQuery, so if a non compatible browser is used, the submit button will show and allow the user to submit the form.
Steps:
If you are using Mercurial, this is done via "import". So at the command line, the hg import
command, or (you may find the --no-commit
option useful), or "Repository" => "Import..." in Hg Workbench.
Note that these will commit the changes by default; you can avoid this using hg import --no-commit
option if using the command-line, or if you used Hg Workbench, you might find it useful to issue hg rollback
after the merge.
I'm doing something very similar it's generic, no need to compute something specific for your code. Just check the remarks on the code:
In MyUIViewController.h
@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
UITableView *myTableView;
UITextField *actifText;
}
@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;
-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;
@end
In MyUIViewController.m
@implementation MyUIViewController
@synthesize myTableView;
@synthesize actifText;
- (void)viewDidLoad
{
// Register notification when the keyboard will be show
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
// Register notification when the keyboard will be hide
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
// To be link with your TextField event "Editing Did Begin"
// memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
self.actifText = textField;
}
// To be link with your TextField event "Editing Did End"
// release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
self.actifText = nil;
}
-(void) keyboardWillShow:(NSNotification *)note
{
// Get the keyboard size
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];
// Detect orientation
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGRect frame = self.myTableView.frame;
// Start animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
// Reduce size of the Table view
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
frame.size.height -= keyboardBounds.size.height;
else
frame.size.height -= keyboardBounds.size.width;
// Apply new size of table view
self.myTableView.frame = frame;
// Scroll the table view to see the TextField just above the keyboard
if (self.actifText)
{
CGRect textFieldRect = [self.myTableView convertRect:self.actifText.bounds fromView:self.actifText];
[self.myTableView scrollRectToVisible:textFieldRect animated:NO];
}
[UIView commitAnimations];
}
-(void) keyboardWillHide:(NSNotification *)note
{
// Get the keyboard size
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];
// Detect orientation
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGRect frame = self.myTableView.frame;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
// Increase size of the Table view
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
frame.size.height += keyboardBounds.size.height;
else
frame.size.height += keyboardBounds.size.width;
// Apply new size of table view
self.myTableView.frame = frame;
[UIView commitAnimations];
}
@end
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var activeText: UITextField!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("keyboardWillShow:"),
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("keyboardWillHide:"),
name: UIKeyboardWillHideNotification,
object: nil)
}
func textFieldDidBeginEditing(textField: UITextField) {
activeText = textField
}
func textFieldDidEndEditing(textField: UITextField) {
activeText = nil
}
func keyboardWillShow(note: NSNotification) {
if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
var frame = tableView.frame
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.3)
frame.size.height -= keyboardSize.height
tableView.frame = frame
if activeText != nil {
let rect = tableView.convertRect(activeText.bounds, fromView: activeText)
tableView.scrollRectToVisible(rect, animated: false)
}
UIView.commitAnimations()
}
}
func keyboardWillHide(note: NSNotification) {
if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
var frame = tableView.frame
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.3)
frame.size.height += keyboardSize.height
tableView.frame = frame
UIView.commitAnimations()
}
}
}
I had to restart the rails application on the production so I looked for an another answer. I have found it below:
http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger
I usually use something like this,
if (!str.length) {
// Do something
}
In my case, I was facing this error because my directory and its file were opened in my editor (VS code) while I was running npm install
. I solved the issue by closing my editor and running npm install
through the command line.
This question has already been answered, but I believe it would be good to throw some useful methods not previously discussed into the mix, and compare all methods proposed thus far in terms of performance.
Here are some useful solutions to this problem, in increasing order of performance.
DataFrame.agg
This is a simple str.format
-based approach.
df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
You can also use f-string formatting here:
df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
char.array
-based ConcatenationConvert the columns to concatenate as chararrays
, then add them together.
a = np.char.array(df['bar'].values)
b = np.char.array(df['foo'].values)
df['baz'] = (a + b' is ' + b).astype(str)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
zip
I cannot overstate how underrated list comprehensions are in pandas.
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
Alternatively, using str.join
to concat (will also scale better):
df['baz'] = [
' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
List comprehensions excel in string manipulation, because string operations are inherently hard to vectorize, and most pandas "vectorised" functions are basically wrappers around loops. I have written extensively about this topic in For loops with pandas - When should I care?. In general, if you don't have to worry about index alignment, use a list comprehension when dealing with string and regex operations.
The list comp above by default does not handle NaNs. However, you could always write a function wrapping a try-except if you needed to handle it.
def try_concat(x, y):
try:
return str(x) + ' is ' + y
except (ValueError, TypeError):
return np.nan
df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]
perfplot
Performance MeasurementsGraph generated using perfplot. Here's the complete code listing.
Functions
def brenbarn(df): return df.assign(baz=df.bar.map(str) + " is " + df.foo) def danielvelkov(df): return df.assign(baz=df.apply( lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)) def chrimuelle(df): return df.assign( baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is ')) def vladimiryashin(df): return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1)) def erickfis(df): return df.assign( baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs1_format(df): return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1)) def cs1_fstrings(df): return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs2(df): a = np.char.array(df['bar'].values) b = np.char.array(df['foo'].values) return df.assign(baz=(a + b' is ' + b).astype(str)) def cs3(df): return df.assign( baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])
Like this:
void * p = (void *)0x28ff44;
Or if you want it as a char *
:
char * p = (char *)0x28ff44;
...etc.
If you're pointing to something you really, really aren't meant to change, add a const
:
const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;
...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
After trying out ngGrid, ngTable, trNgGrid and Smart Table, I have come to the conclusion that Smart Table is by far the best implementation AngularJS-wise and Bootstrap-wise. It is built exactly the same way as you would build your own, naive table using standard angular. On top of that, they have added a few directives that help you do sorting, filtering etc. Their approach also makes it quite simple to extend yourself. The fact that they use the regular html tags for tables and the standard ng-repeat for the rows and standard bootstrap for formatting makes this my clear winner.
Their JS code depends on angular and your html can depend on bootstrap if you want to. The JS code is 4 kb in total and you can even easily pick stuff out of there if you want to reach an even smaller footprint.
Where the other grids will give you claustrophobia in different areas, Smart Table just feels open and to the point.
If you rely heavily on inline editing and other advanced features, you might get up and running quicker with ngTable for instance. However, you are free to add such features quite easily in Smart Table.
Don't miss Smart Table!!!
I have no relation to Smart Table, except from using it myself.
You can use the first method:
$('li').first()
btw I agree with Nick Craver -- use document.getElementById()...
You can use:
getResources().getColor(R.color.idname);
Check here on how to define custom colors:
http://sree.cc/google/android/defining-custom-colors-using-xml-in-android
EDIT(1):
Since getColor(int id)
is deprecated now, this must be used :
ContextCompat.getColor(context, R.color.your_color);
(added in support library 23)
EDIT(2):
Below code can be used for both pre and post Marshmallow (API 23)
ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme
ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme
As all the previous answers indicated, it's very well possible, and pretty easy in newer iOS versions.
I know this is not a technical answer, but since a lot of people do make it wrong (thus effectively violating licenses which may cost you a lot of money if you're being sued), let me strengthen one caveat here: Embedding a custom font in an iOS (or any other kind) app is basically redistributing the font. Most licenses for commercial fonts do forbid redistribution, so please make sure you're acting according to the license.
simply modify your home with the command:
usermod -d /newhome username
In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:
<GlobalNamingResources>_x000D_
<!-- Editable user database that can also be used by_x000D_
UserDatabaseRealm to authenticate users_x000D_
-->_x000D_
<!-- Other previus resouces -->_x000D_
<Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
</GlobalNamingResources>
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
<ResourceLink name="jdbc/your_jndi"_x000D_
global="jdbc/your_jndi"_x000D_
auth="Container"_x000D_
type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
<persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
<provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
<properties>_x000D_
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />_x000D_
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
_x000D_
<!-- <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
<property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
<property name="hibernate.show_sql" value="false" />_x000D_
<property name="hibernate.format_sql" value="true"/> _x000D_
</properties>_x000D_
</persistence-unit>_x000D_
</persistence>
_x000D_
So in your spring.xml you can do that:
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
</bean>_x000D_
_x000D_
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
<property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
<property name="dataSource" ref="postGresDataSource" />_x000D_
<property name="jpaVendorAdapter"> _x000D_
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
</property>_x000D_
</bean>
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
In this example I used spring with xml but you can do this programmaticaly if you prefer.
That's it, I hope helped.
React Native provides a .measure(...)
method which takes a callback and calls it with the offsets and width/height of a component:
myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
The following calculates the layout of a custom component after it is rendered:
class MyComponent extends React.Component {
render() {
return <View ref={view => { this.myComponent = view; }} />
}
componentDidMount() {
// Print component dimensions to console
this.myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
}
}
Note that sometimes the component does not finish rendering before componentDidMount()
is called. If you are getting zeros as a result from measure(...)
, then wrapping it in a setTimeout
should solve the problem, i.e.:
setTimeout( myComponent.measure(...), 0 )
There's a plugin called SublimeHtmlTidy which works pretty well
The best option since office 2007 is using Open XML SDK for it. We used Word.Interop but it halt sometimes, and it is not recommend for Microsoft, to use it as a server side document formatting, so Open XML SDK lets you creates word documents on DOCX and Open XML formats very easily. It lets you going well with scability, confidence ( the files, if it is corrupted can be rebuild ), and another very fine characteristics.
From Java 8 you can use :
Comparator.comparingInt(Dog::getDogAge).reversed();
Run this code snippet and see a vertically and horizontally aligned div.
html,_x000D_
body,_x000D_
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
.container {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.mydiv {_x000D_
width: 80px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="mydiv">h & v aligned</div>_x000D_
</div>
_x000D_
Use DATE_FORMAT function to change the format.
SELECT DATE_FORMAT(CURDATE(), '%d/%m/%Y')
SELECT DATE_FORMAT(column_name, '%d/%m/%Y') FROM tablename
Refer DOC for more details
Posting this as an answer because my comments above got hidden:
List the size of a container:
du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" <container_name>`
List the sizes of a container's volumes:
docker inspect -f "{{.Volumes}}" <container_name> | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h
Edit: List all running containers' sizes and volumes:
for d in `docker ps -q`; do
d_name=`docker inspect -f {{.Name}} $d`
echo "========================================================="
echo "$d_name ($d) container size:"
sudo du -d 2 -h /var/lib/docker/devicemapper | grep `docker inspect -f "{{.Id}}" $d`
echo "$d_name ($d) volumes:"
docker inspect -f "{{.Volumes}}" $d | sed 's/map\[//' | sed 's/]//' | tr ' ' '\n' | sed 's/.*://' | xargs sudo du -d 1 -h
done
NOTE: Change 'devicemapper' according to your Docker filesystem (e.g 'aufs')
Width:100%
and text-align:center
would work in my experience
<p style="display:block; line-height: 70px; width:100%; text-align:center; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>
Simple answer .
(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"
(2) Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this- onclick="document.getElementById('myid').click()"
That is all.
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
I had a similar issue with Angular and IIS throwing a 404 status code on manual refresh and tried the most voted solution but that did not work for me. Also tried a bunch of other solutions having to deal with WebDAV and changing handlers and none worked.
Luckily I found this solution and it worked (took out parts I didn't need). So if none of the above works for you or even before trying them, try this and see if that fixes your angular deployment on iis issue.
Add the snippet to your webconfig in the root directory of your site. From my understanding, it removes the 404 status code from any inheritance (applicationhost.config, machine.config), then creates a 404 status code at the site level and redirects back to the home page as a custom 404 page.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
</configuration>
You may also use:
request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137]
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]
Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).
One of the data columns in the excel (Column Id 6) has one or more cell data that exceed the datacolumn datatype length in the database.
Verify the data in excel. Also verify the data in the excel for its format to be in compliance with the database table schema.
To avoid this, try exceeding the data-length of the string datatype in the database table.
Hope this helps.
I have had a similar problem.
Under "problems" tab I have found an error saying "Error generating final archive: Debug Certificate expired on 2/22/12 1:49 PM
"
So my advice is to look in the problems tab to get some more info.
Bye
What worked for me is to change the access of the Git repository from private to public.
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
now apple support that
overflow:hidden;
-webkit-overflow-scrolling:touch;
Yes. You can use Console of Sublime with (Linux):
Ctrl + `
And type:
view.settings().get('font_face')
Get any setting the same way.
I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin
haha...I have the same question. When initViews() just do like this.The sequence is the key, listener is the last. Good Luck !
spinner.setAdapter(adapter);
spinner.setSelection(position);
spinner.setOnItemSelectedListener(listener);
You can just create an object like this:
public class SomeQuery
{
public string SomeParameter { get; set; }
public int? SomeParameter2 { get; set; }
}
And then in controller just make something like that:
[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
// Your implementation goes here..
}
Even better, you can create API model from:
[HttpGet]
public IActionResult GetSomething([FromRoute] int someId, [FromQuery] SomeQuery query)
to:
[HttpGet]
public IActionResult GetSomething(ApiModel model)
public class ApiModel
{
[FromRoute]
public int SomeId { get; set; }
[FromQuery]
public string SomeParameter { get; set; }
[FromQuery]
public int? SomeParameter2 { get; set; }
}
Do it like this:
Go to Settings -> General -> Profiles - tap on your Profile - tap on the Trust button.
but iOS10 has a little change,
Users should go to Settings - General - Device Management - tap on your Profile - tap on Trust button.
Reference: iOS10AdaptationTips
This looks similar to How do I get github to default to ssh and not https for new repositories. Probably it's worth trying to switch from http protocol to ssh:
$ git remote add origin [email protected]:username/project.git
Don't use os.walk.
Example:
import os
root = "C:\\"
for item in os.listdir(root):
if os.path.isfile(os.path.join(root, item)):
print item
Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr
In this case:
unique_ptr<double> uptr2 (pd);
pd
will be destroyed when uptr2
goes out of scope. This facilitates memory management by automatic deletion.
The case of unique_ptr<int> uptr (new int(3));
is not different, except that the raw pointer is not assigned to any variable here.
On my Mobo (ASRock A320M-HD with Ryzen 3 2200G) I have to:
SR-IOV support: enabled
IOMMU: enabled
SVM: enabled
On the OS enable Hyper V.
They each return the same singleton None
-- There is no functional difference.
I think that it is reasonably idiomatic to leave off the return
statement unless you need it to break out of the function early (in which case a bare return
is more common), or return something other than None
. It also makes sense and seems to be idiomatic to write return None
when it is in a function that has another path that returns something other than None
. Writing return None
out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).
Often in Python, functions which return None
are used like void
functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None
usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return
statement from a "language conventions" standpoint.
That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...
Its much easier than all this: Simply transition the same property on your element
.earth { width: 0.92%; transition: width 1s; }
.earth:hover { width: 50%; transition: width 1s; }
Above code made a little cleaner. InputStreams have finally close wrapping to ensure they get closed as well:
*Note
Input: InputStream is, int w, int h
Output: Bitmap
try
{
final int inWidth;
final int inHeight;
final File tempFile = new File(temp, System.currentTimeMillis() + is.toString() + ".temp");
{
final FileOutputStream tempOut = new FileOutputStream(tempFile);
StreamUtil.copyTo(is, tempOut);
tempOut.close();
}
{
final InputStream in = new FileInputStream(tempFile);
final BitmapFactory.Options options = new BitmapFactory.Options();
try {
// decode image size (decode metadata only, not the whole image)
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
}
finally {
in.close();
}
// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;
}
final Bitmap roughBitmap;
{
// decode full image pre-resized
final InputStream in = new FileInputStream(tempFile);
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/w, inHeight/h);
// decode full image
roughBitmap = BitmapFactory.decodeStream(in, null, options);
}
finally {
in.close();
}
tempFile.delete();
}
float[] values = new float[9];
{
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, w, h);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
m.getValues(values);
}
// resize bitmap
final Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
return resizedBitmap;
}
catch (IOException e) {
logger.error("Error:" , e);
throw new ResourceException("could not create bitmap");
}
You can use redial package for prefetching data on the server before attempting to render
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
Try the following code:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
</style>
This code works for me and will work on all Android devices.
I know this thread is a bit old but I came up with a better solution which supports Multidimensional hashes. It uses delete_if? except its multidimensional and cleans out anything with a an empty value by default and if a block is passed it is passed down through it's children.
# Hash cleaner
class Hash
def clean!
self.delete_if do |key, val|
if block_given?
yield(key,val)
else
# Prepeare the tests
test1 = val.nil?
test2 = val === 0
test3 = val === false
test4 = val.empty? if val.respond_to?('empty?')
test5 = val.strip.empty? if val.is_a?(String) && val.respond_to?('empty?')
# Were any of the tests true
test1 || test2 || test3 || test4 || test5
end
end
self.each do |key, val|
if self[key].is_a?(Hash) && self[key].respond_to?('clean!')
if block_given?
self[key] = self[key].clean!(&Proc.new)
else
self[key] = self[key].clean!
end
end
end
return self
end
end
I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
public interface IThingFactory
{
Thing GetThing(string theString);
}
public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.
Just use getContentResolver().openInputStream(uri)
to get an InputStream
from a URI.
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
Put the query arguments in hidden input fields:
<form action="http://spufalcons.com/index.aspx">
<input type="hidden" name="tab" value="gymnastics" />
<input type="hidden" name="path" value="gym" />
<input type="submit" value="SPU Gymnastics"/>
</form>
The current root password must be empty. Then under "new root password" enter your password and confirm.
I'm working on Docker with centOS 7, and encountered the same problem.
after looking around, and make several tries, I fixed this problem by installing mongodb, and mongodb-server
yum install mongodb mongodb-server
I don't think this is the best way to produce the minimal container. but I can limit the scope into the following packages
==============================================================================================================
Package Arch Version Repository Size
==============================================================================================================
Installing:
mongodb x86_64 2.6.5-2.el7 epel 57 M
mongodb-server x86_64 2.6.5-2.el7 epel 8.7 M
Installing for dependencies:
boost-filesystem x86_64 1.53.0-18.el7 base 66 k
boost-program-options x86_64 1.53.0-18.el7 base 154 k
boost-system x86_64 1.53.0-18.el7 base 38 k
boost-thread x86_64 1.53.0-18.el7 base 56 k
gperftools-libs x86_64 2.1-1.el7 epel 267 k
libpcap x86_64 14:1.5.3-3.el7_0.1 updates 137 k
libunwind x86_64 1.1-3.el7 epel 61 k
snappy x86_64 1.1.0-3.el7 base 40 k
To fix it simply take Set
in place of List
for your nested object.
@OneToMany
Set<Your_object> objectList;
and don't forget to use fetch=FetchType.EAGER
it will work.
There is one more concept CollectionId
in Hibernate if you want to stick with list only.
But remind that you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer!
Use these codes for 404 not found.
if(strstr($_SERVER['REQUEST_URI'],'index.php')){
header('HTTP/1.0 404 Not Found');
readfile('404missing.html');
exit();
}
Here 404missing.html is your Not found design page. (it can be .html or .php)
@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:
css:
.scrollme {
overflow-x: auto;
}
html:
<div class="scrollme">
<table class="table table-responsive"> ...
</table>
</div>
Edit: changing scroll-y to scroll-x
Chances are, if you want to know if a file exists, you plan to require it if it does.
function getFile(path){
try{
return require(path);
}catch(e){
return false;
}
}
You're missing a reference to System.Linq.
Add
using System.Linq
to get access to the ToList() function on the current code file.
To give a little bit of information over why this is necessary, Enumerable.ToList<TSource>
is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq
namespace.
Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable.
Declare @tablevar table(col1 col1Type,..
insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'
SELECT col1, col2 FROM @tablevar
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash()
and password_verify()
. Actually these are just wrappers around the function crypt()
, and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y
), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost"
parameter, it is best to omit the "salt"
parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash()
function. For PHP versions before 5.3.7 there is no support for crypt()
with 2y
, the unicode safe BCrypt algorithm. One could replace it instead with 2a
, which is the best alternative for earlier PHP versions.
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
kubectl rollout restart deployment myapp
This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout
like rollbacks.
Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.
using for loop
lst = [5, 20 ,15]
product = []
for i in lst:
product.append(i*5)
print product
using list comprehension, this is also same as using for-loop but more 'pythonic'
lst = [5, 20 ,15]
prod = [i * 5 for i in lst]
print prod
Copying and pasting from the MS-DOS tree
command might also work for you. Examples:
tree
C:\Foobar>tree
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ +---Drop
...
tree /F
C:\Foobar>tree
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ +---Drop
...
tree /A
C:\Foobar>tree /A
C:.
+---FooScripts
+---barconfig
+---Baz
¦ +---BadBaz
¦ \---Drop
...
tree /F /A
C:\Foobar>tree /A
C:.
+---FooScripts
¦ foo.sh
+---barconfig
¦ bar.xml
+---Baz
¦ +---BadBaz
¦ ¦ badbaz.xml
¦ \---Drop
...
tree
[drive:
][path
] [/F
] [/A
]
drive:\path
— Drive and directory containing disk for display of directory structure, without listing files.
/F
— Include all files living in every directory.
/A
— Replace graphic characters used for linking lines with ext characters , instead of graphic characters./a
is used with code pages that do not support graphic characters and to send output to printers that do not properly interpret graphic characters.
The mugume david answer fails on an empty folder; Count is 1 instead of a 0 when looking for a pattern rather than all files. For example *.xml
This works for me:
attrib.exe /s ./*.xml | find /v "File not found - " | find /c /v ""
In may case I had a global variable in one of my .h
files that was causing the problem, and I solved it by adding extern
in front of it.
domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.
loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.
Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:
package main
import (
"os"
"bufio"
"bytes"
"fmt"
)
// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 1024))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == os.EOF {
err = nil
}
return
}
func main() {
lines, err := readLines("foo.txt")
if err != nil {
fmt.Println("Error: %s\n", err)
return
}
for _, line := range lines {
fmt.Println(line)
}
}
Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create()
followed by a loop similar to that one in the example (see main()
).
Make sure the function is in the same DB schema as the table.
One of the options is to use the Javascript.
Here is a quick reference where you can start from.
It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null
.
Given your statement:
img1.ImageUrl = ConfigurationManager
.AppSettings
.Get("Url")
.Replace("###", randomString)
+ Server.UrlEncode(
((System.Web.UI.MobileControls.Form)Page
.FindControl("mobileForm"))
.Title);
I'm guessing either the call to AppSettings.Get("Url")
is returning null because the value isn't found or the call to Page.FindControl("mobileForm")
is returning null because the control isn't found.
You could easily break this out into multiple statements to solve the problem:
var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
as System.Web.UI.MobileControls.Form;
if(configUrl != null && mobileFormControl != null)
{
img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}
Here's a Windows Management Instrumentation (WMI) approach:
string _osVersion = "";
string _osServicePack = "";
string _osArchitecture = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject mbo in collection)
{
_osVersion = mbo.GetPropertyValue("Caption").ToString();
_osServicePack = string.Format("{0}.{1}", mbo.GetPropertyValue("ServicePackMajorVersion").ToString(), mbo.GetPropertyValue("ServicePackMinorVersion").ToString());
try
{
_osArchitecture = mbo.GetPropertyValue("OSArchitecture").ToString();
}
catch
{
// OSArchitecture only supported on Windows 7/Windows Server 2008
}
}
Console.WriteLine("osVersion : " + _osVersion);
Console.WriteLine("osServicePack : " + _osServicePack);
Console.WriteLine("osArchitecture: " + _osArchitecture);
/////////////////////////////////////////
// Test on Windows 7 64-bit
//
// osVersion : Microsoft Windows 7 Professional
// osservicePack : 1.0
// osArchitecture: 64-bit
/////////////////////////////////////////
// Test on Windows Server 2008 64-bit
// --The extra r's come from the registered trademark
//
// osVersion : Microsoftr Windows Serverr 2008 Standard
// osServicePack : 1.0
// osArchitecture: 64-bit
/////////////////////////////////////////
// Test on Windows Server 2003 32-bit
// --OSArchitecture property not supported on W2K3
//
// osVersion : Microsoft(R) Windows(R) Server 2003, Standard Edition
// osServicePack : 2.0
// osArchitecture:
Now, it's very much simplified in Visual Studio 2015 and later. You can do downgrade / upgrade within the User interface itself, without executing commands in the Package Manager Console.
Right click on your project and *go to Manage NuGet Packages.
Look at the below image.
Select your Package and Choose the Version
, which you wanted to install.Very very simple, isn't it? :)
Here is one more solution which allows for decimal numbers and also limits the digits after decimal to 2 decimal places.
function isNumberKey(evt, element) {_x000D_
var charCode = (evt.which) ? evt.which : event.keyCode_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))_x000D_
return false;_x000D_
else {_x000D_
var len = $(element).val().length;_x000D_
var index = $(element).val().indexOf('.');_x000D_
if (index > 0 && charCode == 46) {_x000D_
return false;_x000D_
}_x000D_
if (index > 0) {_x000D_
var CharAfterdot = (len + 1) - index;_x000D_
if (CharAfterdot > 3) {_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
}_x000D_
return true;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">
_x000D_
Another way is to call an external process such as curl.exe. Curl by default displays a progress bar, average download speed, time left, and more all formatted neatly in a table. Put curl.exe in the same directory as your script
from subprocess import call
url = ""
call(["curl", {url}, '--output', "song.mp3"])
Note: You cannot specify an output path with curl, so do an os.rename afterwards
@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO
to SET
to set the variables rather thon ECHOing them...
See for
documentation for a full list.
ceztko's test case (for reference)
@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
its work short code
$('.SeeMore2').click(function(){
var $this = $(this).toggleClass('SeeMore2');
if($(this).hasClass('SeeMore2'))
{
$(this).text('See More');
} else {
$(this).text('See Less');
}
});
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
You could use @> operator to do this something like
SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
Using base graphics, we can use at =
to control box position , combined with boxwex =
for the width of the boxes. The 1st boxplot
statement creates a blank plot. Then add the 2 traces in the following two statements.
Note that in the following, we use df[,-1]
to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.
boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red",
boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue",
boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15
Some dummy data:
df <- data.frame(
id = c(rep("Good",200), rep("Bad", 200)),
F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
F2 = c(rnorm(200,7,1), rnorm(200,6,1)),
F3 = c(rnorm(200,6,2), rnorm(200,9,3)),
F4 = c(rnorm(200,12,3), rnorm(200,8,2)))
Aside from using %
, age of empires III
to lower case is age of empires iii
so your query should be:
select *
from games
where lower(title) like 'age of empires iii%'
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload
should equal the return value of onPageLoad()
. For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload
to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad
as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange
listener for your XMLHttpRequest
object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}
No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:
const requestUrl = url.parse(url.format({
protocol: 'https',
hostname: 'yoursite.com',
pathname: '/the/path',
query: {
key: value
}
}));
Then make the request with the formatted url. requestUrl.path
will include the query parameters.
const req = https.get({
hostname: requestUrl.hostname,
path: requestUrl.path,
}, (res) => {
// ...
})
Here's my addition.
From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source
"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."
I did that and here is Luciano's updated code snippet:
$.getJSON("example.json", function() {
alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });
And with error description plus showing all json data as a string:
$.getJSON("example.json", function(data) {
alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
If you don't like alerts, substitute them with console.log
$.getJSON("example.json", function(data) {
console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });
I have come up with two statements that can divide positive and negative numbers into integers and fractions without compromising accuracy (bit overflow) and speed.
x = 100.1323 # A number to be divided into integers and fractions
# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction
E.g. 100.1323
-> 100
, 0.1323
or -100.1323
-> -100
, -0.1323
Speedtest
The performance test shows that the two statements are faster than math.modf
, as long as they are not put into their own function or method.
test.py
:
#!/usr/bin/env python
import math
import cProfile
""" Get the performance of both statements and math.modf. """
X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5*10**6) # Number of loops
def scenario_a():
""" The integers (i) and the fractions (f)
come out as integer and float. """
for _ in LOOPS:
i = int(X) # -100
f = (X*1e17-i*1e17)/1e17 # -0.1323
def scenario_b():
""" The integers (i) and the fractions (f)
come out as float.
NOTE: The only difference between this
and math.modf is the accuracy. """
for _ in LOOPS:
i = int(X) # -100
i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)
def scenario_c():
""" Performance test of the statements in a function. """
def modf(x):
i = int(x)
return i, (x*1e17-i*1e17)/1e17
for _ in LOOPS:
i, f = modf(X) # (-100, -0.1323)
def scenario_d():
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
def scenario_e():
""" Convert the integer part to real integer. """
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
i = int(i) # -100
if __name__ == '__main__':
cProfile.run('scenario_a()')
cProfile.run('scenario_b()')
cProfile.run('scenario_c()')
cProfile.run('scenario_d()')
cProfile.run('scenario_e()')
Output:
4 function calls in 1.312 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.312 1.312 <string>:1(<module>)
1 1.312 1.312 1.312 1.312 test.py:10(scenario_a)
1 0.000 0.000 1.312 1.312 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 function calls in 1.887 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.887 1.887 <string>:1(<module>)
1 1.887 1.887 1.887 1.887 test.py:18(scenario_b)
1 0.000 0.000 1.887 1.887 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.797 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.797 2.797 <string>:1(<module>)
1 1.261 1.261 2.797 2.797 test.py:27(scenario_c)
5000000 1.536 0.000 1.536 0.000 test.py:31(modf)
1 0.000 0.000 2.797 2.797 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 1.852 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.852 1.852 <string>:1(<module>)
1 1.050 1.050 1.852 1.852 test.py:38(scenario_d)
1 0.000 0.000 1.852 1.852 {built-in method builtins.exec}
5000000 0.802 0.000 0.802 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.467 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.467 2.467 <string>:1(<module>)
1 1.652 1.652 2.467 2.467 test.py:42(scenario_e)
1 0.000 0.000 2.467 2.467 {built-in method builtins.exec}
5000000 0.815 0.000 0.815 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
NOTE:
The statement can be faster with modulo, but modulo can not be used to split negative numbers into integer and fraction parts.
i, f = int(x), x*1e17%1e17/1e17 # x can not be negative
On CentOS this worked for me:
echo "email body" | mail -s "Subject here" -r from_email_address email_address_to
Such thing is easy with ggplot2
library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5),
rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..)) +
geom_density()
or to mimic the result from Dirk's solution
ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..), binwidth = 5) +
geom_density()
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
This code may help you:
public class EN implements Serializable {
//... you don't need implement any methods when you implements Serializable
}
Putting data. Create new Activity with extra:
EN enumb = new EN();
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("en", enumb); //second param is Serializable
startActivity(intent);
Obtaining data from new activity:
public class NewActivity extends Activity {
private EN en;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
en = (EN)getIntent().getSerializableExtra("en"); //Obtaining data
}
//...
With Python 3.8 this workes for me. For instance to execute a python script within the venv:
import subprocess
import sys
res = subprocess.run([
sys.executable, # venv3.8/bin/python
'main.py', '--help',],
stdout=PIPE,
text=True)
print(res.stdout)
Output needs to be redirected with &>/dev/null
which redirects both stderr and stdout to /dev/null and is a synonym of >/dev/null 2>/dev/null
or >/dev/null 2>&1
.
The best way is to use sh -c '( ( command ) & )'
where command is anything.
ssh askapache 'sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
You can also use nohup directly to launch the shell:
ssh askapache 'nohup sh -c "( ( chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
Another trick is to use nice to launch the command/shell:
ssh askapache 'nice -n 19 sh -c "( ( nohup chown -R ask:ask /www/askapache.com &>/dev/null ) & )"'
The attribute that stores the classes in use is className
.
So you can say:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
If you want a location that shows you how jQuery does everything, I would suggest:
Generally it means:
127 - command not found
but it can also mean that the command is found,
but a library that is required by the command is NOT found.
No need to get too complicated. If all you need is ² then use the unicode representation.
http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
(which is how I assume you got the ² to appear in your question. )
a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')
app.get('/report/:chart_id/:user_id',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
with Node older then 10 you will need to use pump instead of pipeline.