Here is how you do it:
$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
.then(function (response) { /* */ })...
Angular takes care of encoding the parameters.
Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData}
is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).
One danger with params
Keyword is, if after Calls to the Method have been coded,
params
Parameter prior to the Signature change were Type-Compatible with the params
Parameter,those Calls will continue to compile with one/more Expressions previously intended for required Parameters being treated as the optional params
Parameter. I just ran into the worst possible case of this: the params
Parameter was of Type object[]
.
This is noteworthy because developers are used to the compiler slapping their wrists with the much, much more common scenario where Parameters are removed from a Method with all required Parameters (because the # of Parameters expected would change).
For me, it's not worth the shortcut. (Type)[]
without params
will work with 0 to infinity # of Parameters without needing Overrides. Worst case is you'll have to add a , new (Type) [] {}
to Calls where it doesn't apply.
Btw, imho, the safest (and most readable practice) is to:
pass via Named Parameters (which we can now do even in C# ~2 decades after we could in VB ;P) (because:
1.1. it's the only way that guarantees prevention of unintended values passed to Parameters after Parameter order, Compatible-Type and/or count change after Calls have been coded,
1.2. it reduces those chances after a Parameter meaning change, because the likely new identifier name reflecting the new meaning is right next to the value being passed to it,
1.3. it avoids having to count commas and jump back & forth from Call to Signature to see what Expression is being passed for what Parameter, and
1.3.1. By the way, this reason alone should be plenty (in terms of avoiding frequent error-prone violations of the DRY Principle just to read the code not to mention also modify it), but this reason can be exponentially more important if there are one/more Expressions being Passed that themselves contain commas, i.e. Multi-Dimensional Array Refs or Multi-Parameter Function Calls. In that case, you couldn't even use (which even if you could, would still be adding an extra step per Parameter per Method Call) a Find All Occurrences in a Selection feature in your editor to automate the comma-counting for you.
1.4. if you must use Optional Parameters (params
or not), it allows you to search for Calls where a particular Optional Parameter is Passed (and therefore, most likely is not or at least has the possibility of being not the Default Value),
(NOTE: Reasons 1.2. and 1.3. can ease and reduce chances of error even on coding the initial Calls not to mention when Calls have to be read and/or changed.))
and
do so ONE - PARAMETER - PER - LINE for better readability (because:
2.1. it's less cluttered, and
2.2. it avoids having to scroll right & back left (and having to do so PER - LINE, since most mortals can't read the left part of multiple lines, scroll right and read the right part)).
2.3. it's consistent with the "Best Practice" we've already evolved into for Assignment Statements, because every Parameter Passed is in essence an Assignment Statement (assigning a Value or Reference to a Local Variable). Just like those who follow the latest "Best Practice" in Coding Style wouldn't dream of coding multiple Assignment Statements per line, we probably shouldn't (and won't once "Best Practice" catches up to my "genius" ;P ) do so when Passing Parameters.
NOTES:
Passing in Variables whose names mirror the Parameters' doesn't help when:
1.1. you're passing in Literal Constants (i.e. a simple 0/1, false/true or null that even "'Best Practices'" may not require you use a Named Constant for and their purpose can't be easily inferred from the Method name),
1.2. the Method is significantly lower-level / more generic than the Caller such that you would not want / be able to name your Variables the same/similar to the Parameters (or vice versa), or
1.3. you're re-ordering / replacing Parameters in the Signature that may result in prior Calls still Compiling because the Types happen to still be compatible.
Having an auto-wrap feature like VS does only eliminates ONE (#2.2) of the 8 reasons I gave above. Prior to as late as VS 2015, it did NOT auto-indent (!?! Really, MS?!?) which increases severity of reason #2.1.
VS should have an option that generates Method Call snippets with Named Parameters (one per line of course ;P) and a compiler option that requires Named Parameters (similar in concept to Option Explicit in VB which, btw, the requirement of was prolly once thought equally as outrageous but now is prolly required by "'Best Practices'"). In fact, "back in my day" ;), in 1991 just months into my career, even before I was using (or had even seen) a language with Named Parameters, I had the anti-sheeple / "just cuz you can, don't mean you should" / don't blindly "cut the ends of the roast" sense enough to simulate it (using in-line comments) without having seen anyone do so. Not having to use Named Parameters (as well other syntax that save "'precious'" source code keystrokes) is a relic of the Punch Card era when most of these syntaxes started. There's no excuse for that with modern hardware and IDE's and much more complex software where readability is much, Much, MUCH more important. "Code is read much more often than is written". As long as you're not duplicating non-auto-updated code, every keystroke saved is likely to cost exponentially more when someone (even yourself) is trying to read it later.
You can set height and width like this:
myGraphView.setLayoutParams(new LayoutParams(width, height));
Open ~/.bash_profile
and add:
export ANDROID_HOME=~/Library/Android/sdk/
export PATH=$PATH:~/android-sdks/platform-tools/
export PATH=$PATH:~/android-sdks/tools/
source ~/.bash_profile
git push origin HEAD:master
Git threw the below error when I tried simply git push
. So clearly this is because Git matches the local and remote branch while pushing commits. This is the push.default
behavior, you can find out more details here.
fatal: The upstream branch of your current branch does not match
the name of your current branch. To push to the upstream branch
on the remote, use
git push origin HEAD:<Branch_Name>
To push to the branch of the same name on the remote, use
git push origin <Branch_Name>
To choose either option permanently, see push.default in 'git help config'.
There is a read_pickle function as part of pandas 0.22+
import pandas as pd
object = pd.read_pickle(r'filepath')
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
EDIT: This solution is not viable for newer versions of Bootstrap, where the navbar-inverse and navbar-static-top classes are not available.
Using MVC 5, the way I fixed mine, was to simply add my own Site.css, loaded after the others, with the following line:
body{padding: 0}
and I changed the code in the beginning of _Layout.cshtml, to be:
<body>
<div class="navbar navbar-inverse navbar-static-top">
<div class="container">
@if (User.Identity.IsAuthenticated) {
<div class="top-navbar">
Quick answer: No, at least not with native SMS service.
Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.
A simple
echo "Y Y N N Y N Y Y N" | ./your_script
This allow you to pass any sequence of "Y" or "N" to your script.
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
i usually use ng-show
<li ng-show="variable.length"></li>
where variable you define for example
<div class="list-group-item" ng-repeat="product in store.products">
<li ng-show="product.length">show something</li>
</div>
Most of the answers here give a solution using -
for loop
Although all the solutions should work with these methods, I thought we could use string manipulation.
Points to note about this solution -
The trick is to -
stringify
input data set and the search valuesplit
data on delimiter ,
. remove = (input, value) => {
const stringVal = JSON.stringify(value);
const result = JSON.stringify(input)
return result.replace(stringVal, "").split(",");
}
A JSFiddle with tests for objects and numbers is created here - https://jsfiddle.net/4t7zhkce/33/
Check the remove
method in the fiddle.
This answer does not directly answer the question but may be a good solution outside of the box.
I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:
tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.
tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.
Positive:
*.wav
files.Negative:
filter_by
is used for simple queries on the column names using regular kwargs, like
db.users.filter_by(name='Joe')
The same can be accomplished with filter
, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:
db.users.filter(db.users.name=='Joe')
You can also write more powerful queries using filter
, such as expressions like:
db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))
The current answer is outdated. Here's the up-to-date flow:
The approach outlined here still works (10.12.2020) as confirmed by alexwhan.
We will use the YouTube Data API for our example. Make changes accordingly.
Make sure you have enabled your desired API for your project.
https://console.cloud.google.com/apis/credentials
https://oauth.pstmn.io/v1/callback
We will use the file later to authenticate Postman.
Click here to see the settings
You can find everything else you need in your .json file.
Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.
The problem with a LEFT JOIN is that if there are no appointments, it will still return one row with a null, which when aggregated by COUNT will become 1, and it will appear that the person has one appointment when actually they have none. I think this will give the correct results:
SELECT person.person_id,
(SELECT COUNT(*) FROM appointment WHERE person.person_id = appointment.person_id) AS 'Appointments'
FROM person;
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
byte[] bytes = { 1,2,3,4 };
string stringByte= BitConverter.ToString(bytes);
Console.WriteLine(stringByte);
Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.
Connect as PCT account in the database, then grant the account you are using select access for the table.
grant select on pi_int to Account_used_to_connect
If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):
Order deny,allow
Deny from all
Allow from 10.0.0.1
You can even specify a subnet
Allow from 10.0.0
Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.
SyntaxError: missing ) after argument list.
the issue also may occur if you pass string directly without a single or double quote.
$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "' onclick=\"(canLaunch(' + v.LibraryItemName + '))\">View »</a></div></div>").
so always keep the habit to pass in a quote like
onclick=\"(canLaunch(\'' + v.LibraryItemName + '\'))"\
First of all, it's important to know what you mean by "open an Excel file for reading and copy it to clipboard..."
This is very important because there are many ways you could do that depending just on what you intend to do. Let me explain:
If you want to read a set of data and copy that in the clipboard and you know the data format (e.g. column names), I suggest you use an OleDbConnection to open the file, this way you can treat the xls file content as a Database Table, so you can read data with SQL instruction and treat the data as you want.
If you want to do operations on the data with the Excel object model then open it in the way you began.
Some time it's possible to treat an xls file as a kind of csv file, there are tools like File Helpers which permit you to treat and open an xls file in a simple way by mapping a structure on an arbitrary object.
Another important point is in which Excel version the file is.
I have, unfortunately I say, a strong experience working with Office automation in all ways, even if bounded in concepts like Application Automation, Data Management and Plugins, and generally I suggest only as the last resort, to using Excel automation or Office automation to read data; just if there aren't better ways to accomplish that task.
Working with automation could be heavy in performance, in terms of resource cost, could involve in other issues related for example to security and more, and last but not at least, working with COM interop it's not so "free".. So my suggestion is think and analyze the situation within your needs and then take the better way.
You cannot initialize an array like that. In addition to what others have suggested, you can do :
data[0] = 10;
data[1] = 20;
...
data[9] = 91;
If there is not substantial history on one end (aka if it is just a single readme commit on the github end), I often find it easier to manually copy the readme to my local repo and do a git push -f
to make my version the new root commit.
I find it is slightly less complicated, doesn't require remembering an obscure flag, and keeps the history a bit cleaner.
At the point where the code is run, you can insert this small snippet to see a nicely formatted printed stack trace. It assumes that you have a folder called logs
at your project's root directory.
# DEBUG: START DEBUG -->
import traceback
with open('logs/stack-trace.log', 'w') as file:
traceback.print_stack(file=file)
# DEBUG: END DEBUG --!
This answer works for me in c#:
using System.IO;
string fileName = Path.GetFileName("C:\Hello\AnotherFolder\The File Name.PDF");
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/
It turns out, the russian developer Ilya Konyukhov picked up the gauntlet after reading this and created a new auth library for CI based on DX Auth, following the recommendations and requirements below.
And the resulting Tank Auth is looking like the answer to the OP's question. I'm going to go out on a limb here and call Tank Auth the best authentication library for CodeIgniter available today. It's a rock-solid library that has all the features you need and none of the bloat you don't:
Pros
- Full featured
- Lean footprint (20 files) considering the feature set
- Very good documentation
- Simple and elegant database design (just 4 DB tables)
- Most features are optional and easily configured
- Language file support
- reCAPTCHA supported
- Hooks into CI's validation system
- Activation emails
- Login with email, username or both (configurable)
- Unactivated accounts auto-expire
- Simple yet effective error handling
- Uses phpass for hashing (and also hashes autologin codes in the DB)
- Does not use security questions
- Separation of user and profile data is very nice
- Very reasonable security model around failed login attempts (good protection against bots and DoS attacks)
(Minor) Cons
- Lost password codes are not hashed in DB
- Includes a native (poor) CAPTCHA, which is nice for those who don't want to depend on the (Google-owned) reCAPTCHA service, but it really isn't secure enough
- Very sparse online documentation (minor issue here, since the code is nicely documented and intuitive)
Original answer:
I've implemented my own as well (currently about 80% done after a few weeks of work). I tried all of the others first; FreakAuth Light, DX Auth, Redux, SimpleLogin, SimpleLoginSecure, pc_user, Fresh Powered, and a few more. None of them were up to par, IMO, either they were lacking basic features, inherently INsecure, or too bloated for my taste.
Actually, I did a detailed roundup of all the authentication libraries for CodeIgniter when I was testing them out (just after New Year's). FWIW, I'll share it with you:
Pros
- Very full featured
- Medium footprint (25+ files), but manages to feel quite slim
- Excellent documentation, although some is in slightly broken English
- Language file support
- reCAPTCHA supported
- Hooks into CI's validation system
- Activation emails
- Unactivated accounts auto-expire
- Suggests grc.com for salts (not bad for a PRNG)
- Banning with stored 'reason' strings
- Simple yet effective error handling
Cons
- Only lets users 'reset' a lost password (rather than letting them pick a new one upon reactivation)
- Homebrew pseudo-event model - good intention, but misses the mark
- Two password fields in the user table, bad style
- Uses two separate user tables (one for 'temp' users - ambiguous and redundant)
- Uses potentially unsafe md5 hashing
- Failed login attempts only stored by IP, not by username - unsafe!
- Autologin key not hashed in the database - practically as unsafe as storing passwords in cleartext!
- Role system is a complete mess: is_admin function with hard-coded role names, is_role a complete mess, check_uri_permissions is a mess, the whole permissions table is a bad idea (a URI can change and render pages unprotected; permissions should always be stored exactly where the sensitive logic is). Dealbreaker!
- Includes a native (poor) CAPTCHA
- reCAPTCHA function interface is messy
Pros
- Very full featured
- Mostly quite well documented code
- Separation of user and profile data is a nice touch
- Hooks into CI's validation system
- Activation emails
- Language file support
- Actively developed
Cons
- Feels a bit bloated (50+ files)
- And yet it lacks automatic cookie login (!)
- Doesn't support logins with both username and email
- Seems to have issues with UTF-8 characters
- Requires a lot of autoloading (impeding performance)
- Badly micromanaged config file
- Terrible View-Controller separation, with lots of program logic in views and output hard-coded into controllers. Dealbreaker!
- Poor HTML code in the included views
- Includes substandard CAPTCHA
- Commented debug echoes everywhere
- Forces a specific folder structure
- Forces a specific Ajax library (can be switched, but shouldn't be there in the first place)
- No max limit on login attempts - VERY unsafe! Dealbreaker!
- Hijacks form validation
- Uses potentially unsafe md5 hashing
Pros
- Good feature set for its tiny footprint
- Lightweight, no bloat (3 files)
- Elegant automatic cookie login
- Comes with optional test implementation (nice touch)
Cons
- Uses the old CI database syntax (less safe)
- Doesn't hook into CI's validation system
- Kinda unintuitive status (role) system (indexes upside down - impractical)
- Uses potentially unsafe sha1 hashing
Pros
- Small footprint (6 files)
Cons
- Lacks a lot of essential features. Dealbreaker!
- Everything is hard-coded. Dealbreaker!
According to the CodeIgniter wiki, Redux has been discontinued, but the Ion Auth fork is going strong: https://github.com/benedmunds/CodeIgniter-Ion-Auth
Ion Auth is a well featured library without it being overly heavy or under advanced. In most cases its feature set will more than cater for a project's requirements.
Pros
- Lightweight and simple to integrate with CodeIgniter
- Supports sending emails directly from the library
- Well documented online and good active dev/user community
- Simple to implement into a project
Cons
- More complex DB schema than some others
- Documentation lacks detail in some areas
Pros
- Tiny footprint (4 files)
- Minimalistic, absolutely no bloat
- Uses phpass for hashing (excellent)
Cons
- Only login, logout, create and delete
- Lacks a lot of essential features. Dealbreaker!
- More of a starting point than a library
Don't get me wrong: I don't mean to disrespect any of the above libraries; I am very impressed with what their developers have accomplished and how far each of them have come, and I'm not above reusing some of their code to build my own. What I'm saying is, sometimes in these projects, the focus shifts from the essential 'need-to-haves' (such as hard security practices) over to softer 'nice-to-haves', and that's what I hope to remedy.
Therefore: back to basics.
Here's my MINIMAL required list of features from an authentication library. It also happens to be a subset of my own library's feature list ;)
- Tiny footprint with optional test implementation
- Full documentation
- No autoloading required. Just-in-time loading of libraries for performance
- Language file support; no hard-coded strings
- reCAPTCHA supported but optional
- Recommended TRUE random salt generation (e.g. using random.org or random.irb.hr)
- Optional add-ons to support 3rd party login (OpenID, Facebook Connect, Google Account, etc.)
- Login using either username or email
- Separation of user and profile data
- Emails for activation and lost passwords
- Automatic cookie login feature
- Configurable phpass for hashing (properly salted of course!)
- Hashing of passwords
- Hashing of autologin codes
- Hashing of lost password codes
- Hooks into CI's validation system
- NO security questions!
- Enforced strong password policy server-side, with optional client-side (Javascript) validator
- Enforced maximum number of failed login attempts with BEST PRACTICES countermeasures against both dictionary and DoS attacks!
- All database access done through prepared (bound) statements!
Note: those last few points are not super-high-security overkill that you don't need for your web application. If an authentication library doesn't meet these security standards 100%, DO NOT USE IT!
Recent high-profile examples of irresponsible coders who left them out of their software: #17 is how Sarah Palin's AOL email was hacked during the Presidential campaign; a nasty combination of #18 and #19 were the culprit recently when the Twitter accounts of Britney Spears, Barack Obama, Fox News and others were hacked; and #20 alone is how Chinese hackers managed to steal 9 million items of personal information from more than 70.000 Korean web sites in one automated hack in 2008.
These attacks are not brain surgery. If you leave your back doors wide open, you shouldn't delude yourself into a false sense of security by bolting the front. Moreover, if you're serious enough about coding to choose a best-practices framework like CodeIgniter, you owe it to yourself to at least get the most basic security measures done right.
<rant>
Basically, here's how it is: I don't care if an auth library offers a bunch of features, advanced role management, PHP4 compatibility, pretty CAPTCHA fonts, country tables, complete admin panels, bells and whistles -- if the library actually makes my site less secure by not following best practices. It's an authentication package; it needs to do ONE thing right: Authentication. If it fails to do that, it's actually doing more harm than good.
</rant>
/Jens Roland
You're looking for the /Y
switch.
cursor.fetchall()
and list(cursor)
are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:
for result in cursor:
This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).
Most of the time, the problem is due to some error on the human side. In my case, I was using some classes whose names are similar. I have added the empty() method under one class; however, my code was calling the empty() method from another class. At that moment, the mind was stuck. I was running make clean, and remake thinking that it was some older version of the header got used. After walking away for a moment, I found that problem right away. We programmers tends to blame others first. Maybe we should insist on ourselves to be wrong first.
Sometimes, I forget to write the latest update to disk and looking at the correct version of the code, but the compiler is seeing the wrong version of the code. This situation may be less a issue on IDE (I use vi to do coding).
Web Browser control might work. http://ryanfarley.com/blog/archive/2004/12/23/1330.aspx
Also a bunch of pdf open source c# projects here http://csharp-source.net/open-source/pdf-libraries
ES 6 Version of Accepted Answer:
function round(value, precision) {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
}
To get the data from the database, you'd use a SimpleCursorAdapter
.
I think you can directly bind the SimpleCursorAdapter
to a ListView
- if not, you can create a custom adapter class that extends SimpleCursorAdapter with a custom ViewBinder
that overrides setViewValue
.
Look at the Notepad tutorial to see how to use a SimpleCursorAdapter
.
Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();
Calling nextInt()
was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine()
after that does the work.
Just to give a small example of using PHP's XML functionality for the task:
$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><img src=\"myimage.jpg\" title=\"title\" alt=\"alt\"></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath('//img');
foreach ($images as $img) {
echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
}
I did use the DOMDocument::loadHTML()
method because this method can cope with HTML-syntax and does not force the input document to be XHTML. Strictly speaking the conversion to a SimpleXMLElement
is not necessary - it just makes using xpath and the xpath results more simple.
Take a look in .git/config and make the changes you need.
Alternatively you could use
git remote rm [name of the url you sets on adding]
and
git remote add [name] [URL]
Or just
git remote set-url [URL]
Before you do anything wrong, double check with
git help remote
What about using something like PouchDB? http://pouchdb.com/
Try GLOB()
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}
<html>
<head>
</head>
<style>
.out{
width:200px;
height:200px;
background-color:yellow;
}
.in{
width:100px;
height:100px;
background-color:green;
margin-top:50%;
margin-left:50%;
transform:translate(-50%,50%);
}
</style>
<body>
<div class="out">
<div class="in">
</div>
</div>
</body>
</html>
No - there's a big prejudice in IT against web design; but in this case the "real" programmers are on pretty firm ground.
If you've done a lot of web design work you've probably done some JavaScript, so you can put that down under 'programming languages'; if you want to list HTML as well, then I agree with the answer that suggests "Technologies".
But unless you're targeting agents who're trying to tick boxes rather than find you a good job, a bare list of things you've used doesn't really look all that good. You're better off listing the projects you've worked on and detailing the technologies you used on each; that demonstrates that you've got real experience of using them rather than just that you know some buzzwords.
If you want to scroll with a smooth transition, you could use this!
(Vanilla JS)
const tabScroll = document.getElementById("tabScroll");
window.scrollTo({
'behavior': 'smooth',
'left': 0,
'top': tabScroll.offsetTop - 80
});
If your target users are Chrome and Firefox, then this is good! But unfortunately this method isn’t supported well enough on all browsers. Check Here
Hope this helps!!
You can use a try-except
try:
print(str.to.id)
except AttributeError: # Not a Retweet
print('null')
I know this an old thread, but I found out using the Subtotal method in VBA also accurately renders a count of the rows. The formula I found is in this article, and looks like this:
Application.WorksheetFunction.Subtotal(2, .Range("A2:A" & .Rows(.Rows.Count).End(xlUp).Row))
I tested it and it came out accurately every time, rendering the correct number of visible rows in column A.
Hopefully this will help some other wayfarer of the 'Net like me.
Try this
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
?>
Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?
This help
target will only print targets which have ##
followed by a description. This allows for documenting both public and private targets. Using the .DEFAULT_GOAL
makes the help more discoverable.
Only sed
, xargs
and printf
used which are pretty common.
Using the < $(MAKEFILE_LIST)
allows for the makefile to be called something other than Makefile
for instance Makefile.github
You can customize the output to suit your preference in the printf
. This example is set up to match the OP's request for rake
style output
When cutting and pasting the below make file, don't forget to change the 4 spaces indentation to tabs.
# vim:ft=make
# Makefile
.DEFAULT_GOAL := help
.PHONY: test help
help: ## these help instructions
@sed -rn 's/^([a-zA-Z_-]+):.*?## (.*)$$/"\1" "\2"/p' < $(MAKEFILE_LIST) | xargs printf "make %-20s# %s\n"
lint: ## style, bug and quality checker
pylint src test
private: # for internal usage only
@true
test: private ## run pytest with coverage
pytest --cov test
Here is the output from the Makefile
above. Notice the private
target doesn't get output because it only has a single #
for it's comment.
$ make
make help # these help instructions
make lint # style, bug and quality checker
make test # run pytest with coverage
That's what I do and it works great for me, and many others. First, find the length of the video in the below snippet:
Seems stream 0 codec frame rate differs from container frame rate: 5994.00
(5994/1) -> 29.97 (30000/1001)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/stu/Movies/District9.mov':
Duration: 00:02:32.20, start: 0.000000, bitrate: 9808 kb/s
Stream #0.0(eng): Video: h264, yuv420p, 1920x1056, 29.97tbr, 2997tbn, 5994tbc
Stream #0.1(eng): Audio: aac, 44100 Hz, 2 channels, s16
Stream #0.2(eng): Data: tmcd / 0x64636D74
You'll should be able to consistently and safely find Duration: hh:mm:ss.nn
to determine the source video clip size. Then, for each update line (CR, no LF) you can parse the text for the current time mark it is at:
frame= 84 fps= 18 q=10.0 size= 5kB time=1.68 bitrate= 26.1kbits/s
frame= 90 fps= 17 q=10.0 size= 6kB time=1.92 bitrate= 23.8kbits/s
frame= 94 fps= 16 q=10.0 size= 232kB time=2.08 bitrate= 913.0kbits/s
Just be careful to not always expect perfect output from these status lines. They can include error messages like here:
frame= 24 fps= 24 q=-1.0 size= 0kB time=1.42 bitrate= 0.3kbits/s
frame= 41 fps= 26 q=-1.0 size= 0kB time=2.41 bitrate= 0.2kbits/s
[h264 @ 0x1013000]Cannot parallelize deblocking type 1, decoding such frames in
sequential order
frame= 49 fps= 24 q=26.0 size= 4kB time=0.28 bitrate= 118.1kbits/s
frame= 56 fps= 22 q=23.0 size= 4kB time=0.56 bitrate= 62.9kbits/s
Once you have the time, it is simple math: time / duration * 100 = % done
.
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.
If you really want to dive into it and even need to distinguish between -0
and 0
, here's a way to do it.
function negative(number) {
return !Object.is(Math.abs(number), +number);
}
console.log(negative(-1)); // true
console.log(negative(1)); // false
console.log(negative(0)); // false
console.log(negative(-0)); // true
<?php
$address = 'BTM 2nd Stage, Bengaluru, Karnataka 560076'; // Address
$apiKey = 'api-key'; // Google maps now requires an API key.
// Get JSON results from this request
$geo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.$apiKey);
$geo = json_decode($geo, true); // Convert the JSON to an array
if (isset($geo['status']) && ($geo['status'] == 'OK')) {
$latitude = $geo['results'][0]['geometry']['location']['lat']; // Latitude
$longitude = $geo['results'][0]['geometry']['location']['lng']; // Longitude
}
?>
public static int[] removeDuplicates(int[] input){
int j = 0;
int i = 1;
//return if the array length is less than 2
if(input.length < 2){
return input;
}
while(i < input.length){
if(input[i] == input[j]){
i++;
}else{
j = j+1;
input[j] = input[i];
i = i+1;
}
}
int[] output = new int[j+1];
for(int k=0; k<output.length; k++){
output[k] = input[k];
}
return output;
}
public static void main(String a[]){
int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
int[] output = removeDuplicates(input1);
for(int i:output){
System.out.println(i+" ");
}
}
Another case when you should use .getParameter()
is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp
, you can access userName
like this:
request.getParameter("userName")
truncate tableName
That is what you are looking for.
Truncate will delete all records in the table, emptying it.
Why are you all going the hard way?
with open("myfile") as myfile:
nonempty = filter(str.rstrip, myfile)
Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x
In Python 2.x you may use itertools.ifilter
to do your bidding instead.
// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width
public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (OnlyResizeIfWider)
{
if (FullsizeImage.Width <= NewWidth)
{
NewWidth = FullsizeImage.Width;
}
}
int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
if (NewHeight > MaxHeight)
{
// Resize with height instead
NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
NewHeight = MaxHeight;
}
System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose();
// Save resized picture
NewImage.Save(NewFile);
}
There would be another way to do this:
var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();
There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:
Run the script in your PowerShell ISE:
Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking
BUild list of Servers manually (this builds an array list):
$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
## - Add Code block:
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto
## - End of Code block
}
I am not sure,how you are opening popup or say model in your code. But you can try something like this..
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript">
var myApp = angular.module("MyApp", []);
myApp.controller('MyController', function ($scope) {
$scope.open = function(){
var modalInstance = $modal.open({
templateUrl: '/assets/yourOpupTemplatename.html',
backdrop:'static',
keyboard:false,
controller: function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
$scope.ok = function () {
$modalInstance.close();
};
}
});
}
});
</script>
</head>
<body ng-controller="MyController">
<button class="btn btn-primary" ng-click="open()">Test Modal</button>
<!-- Confirmation Dialog -->
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
</body>
</html>
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.
For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner
Here is a wikipedia article explaining what map-reduce
is all about
Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.
Personally, found this link quite useful to understand the concept
Copying the explanation provided in the blog (In case the link goes stale)
Finding Friends
MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.
I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:
3 : the 3 : and 3 : you 4 : then 4 : what 4 : when 5 : steve 5 : where 8 : savannah 8 : research
They get grouped as:
3 : [the, and, you] 4 : [then, what, when] 5 : [steve, where] 8 : [savannah, research]
Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:
3 : 3 4 : 3 5 : 2 8 : 2
The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...
The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.
The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of
1
. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):
Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.
Assume the friends are stored as Person->[List of Friends], our friends list is then:
A -> B C D B -> A C D E C -> A B D E D -> A B C E E -> B C D
Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:
For map(A -> B C D) : (A B) -> B C D (A C) -> B C D (A D) -> B C D For map(B -> A C D E) : (Note that A comes before B in the key) (A B) -> A C D E (B C) -> A C D E (B D) -> A C D E (B E) -> A C D E For map(C -> A B D E) : (A C) -> A B D E (B C) -> A B D E (C D) -> A B D E (C E) -> A B D E For map(D -> A B C E) : (A D) -> A B C E (B D) -> A B C E (C D) -> A B C E (D E) -> A B C E And finally for map(E -> B C D): (B E) -> B C D (C E) -> B C D (D E) -> B C D Before we send these key-value pairs to the reducers, we group them by their keys and get: (A B) -> (A C D E) (B C D) (A C) -> (A B D E) (B C D) (A D) -> (A B C E) (B C D) (B C) -> (A B D E) (A C D E) (B D) -> (A B C E) (A C D E) (B E) -> (A C D E) (B C D) (C D) -> (A B C E) (A B D E) (C E) -> (A B D E) (B C D) (D E) -> (A B C E) (B C D)
Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.
The result after reduction is:
(A B) -> (C D) (A C) -> (B D) (A D) -> (B C) (B C) -> (A D E) (B D) -> (A C E) (B E) -> (C D) (C D) -> (A B E) (C E) -> (B D) (D E) -> (B C)
Now when D visits B's profile, we can quickly look up
(B D)
and see that they have three friends in common,(A C E)
.
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2
that aren't in array1
. It sounds like you're asking is array1 a subset of array2?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
If you want mm-dd-yyyy
format you can use:
mkdir %date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
I had the same issue, I had to remove the async keyword from the method and also remove the await keyword from the calling method to use getawaiter() without any error.
create a new repository on the command line
echo "# <RepositoryName>" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git
git push -u origin master
push an existing repository from the command line
git remote add origin https://github.com/**<gituserID>/<RepositoryName>**.git
git push -u origin master
In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.
catch needs to return an observable.
.catch(e => { console.log(e); return Observable.of(e); })
if you'd like to stop the pipeline after a caught error, then do this:
.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)
this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.
edit:
better way of stopping the pipeline is to do
.catch(e => Observable.empty())
Add the following line in your code to Suppress the warnings:
const moment = require('moment');
moment.suppressDeprecationWarnings = true;
For overloading you'd need a subclass:
class ChildTestclass extends Testclass {
public $testvar = "newVal";
}
$obj = new ChildTestclass();
$obj->dosomething();
This code would echo newVal
.
What is actually the most robust and elegant automated solution for deserializing JSON to TypeScript runtime class instances?
Using property decorators with ReflectDecorators to record runtime-accessible type information that can be used during a deserialization process provides a surprisingly clean and widely adaptable approach, that also fits into existing code beautifully. It is also fully automatable, and works for nested objects as well.
An implementation of this idea is TypedJSON, which I created precisely for this task:
@JsonObject
class Foo {
@JsonMember
name: string;
getName(): string { return this.name };
}
var foo = TypedJSON.parse('{"name": "John Doe"}', Foo);
foo instanceof Foo; // true
foo.getName(); // "John Doe"
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.
<?php
if(isset($_POST['save'])) {
//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed = array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}
}
// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?
Your html will look something like this;
<html>
<head>
</head>
<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>
<!-- Form -->
<form method="post" action="">
<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />
<p><input type="submit" name="save" value="SAVE" /></p>
</form>
</body>
</html>
To add to @mrry's post, I put together a tutorial that explains how to load a TensorFlow graph with the C++ API. It's very minimal and should help you understand how all of the pieces fit together. Here's the meat of it:
Requirements:
Folder structure:
tensorflow/tensorflow/|project name|/
tensorflow/tensorflow/|project name|/|project name|.cc (e.g. https://gist.github.com/jimfleming/4202e529042c401b17b7)
tensorflow/tensorflow/|project name|/BUILD
BUILD:
cc_binary(
name = "<project name>",
srcs = ["<project name>.cc"],
deps = [
"//tensorflow/core:tensorflow",
]
)
Two caveats for which there are probably workarounds:
https://medium.com/@jimfleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f
Easy solution:
compare the two dates:
A = the one with smaller start date, B = the one with bigger start date
if(A.end < B.start)
return false
return true
I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)
https://getcomposer.org/Composer-Setup.exe
I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".
Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html
If it still not working, check if your apache server use the good php.ini file by running the following cmd command :
php --ini
Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File: C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.
It must be something like this :
PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"
Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like
I sometime use this method:
// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");
// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));
Works all MOST of the time.
Need to include jquery-ui too:
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
If you looking for something short and simple, maybe it will be enough for you:
class A(object):
def __init__(self, l):
self.data = l
def __iter__(self):
return iter(self.data)
example of usage:
In [3]: a = A([2,3,4])
In [4]: [i for i in a]
Out[4]: [2, 3, 4]
In addition to Mathias answer.
Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable
:
$ Get-Variable
Name Value
---- -----
$ name
? True
^ gci
args {}
ChocolateyTabSettings @{AllCommands=False}
ConfirmPreference High
DebugPreference SilentlyContinue
EnabledExperimentalFeatures {}
Error {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference Continue
ErrorView NormalView
ExecutionContext System.Management.Automation.EngineIntrinsics
false False
FormatEnumerationLimit 4
...
These also include stuff you may have set in your profile startup script.
If you are looking for a rapid, normalized cross correlation in either one or two dimensions
I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).
While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.
import numpy
import cv
#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp
#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )
#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv = cv.fromarray(numpy.float32(resultNp))
#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)
#convert result back to numpy array
resultNp = np.asarray(resultCv)
For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.
I was also a bit confused between adjustResize and adjustPan when I was a beginner. The definitions given above are correct.
AdjustResize : Main activity's content is resized to make room for soft input i.e keyboard
AdjustPan : Instead of resizing overall contents of the window, it only pans the content so that the user can always see what is he typing
AdjustNothing : As the name suggests nothing is resized or panned. Keyboard is opened as it is irrespective of whether it is hiding the contents or not.
I have a created a example for better understanding
Below is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Type Here"
app:layout_constraintTop_toBottomOf="@id/button1"/>
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/button2"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@id/button1"
app:layout_constraintEnd_toStartOf="@id/button3"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/button2"
android:layout_marginBottom="@dimen/margin70dp"/>
</android.support.constraint.ConstraintLayout>
Here is the design view of the xml
AdjustResize Example below:
AdjustPan Example below:
AdjustNothing Example below:
My favorite:
https://inloop.github.io/sqlite-viewer/
No installation needed. Just drop the file.
Alternativly if your using bootstrap then you can just add align-middle
to vertical align the element.
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
<i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>
When you say multiple queries do you mean multiple SQL statements as in:
UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;
Or multiple query function calls as in:
mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)
The former can all be done using a single mySqlQuery call if that is what you wanted to achieve, simply call the mySqlQuery function in the following manner:
mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)
This will execute all three queries with one mySqlQuery() call.
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);
int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days
int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days
int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
Also, the project is mostly dormant... the last release was in 2004.
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
According to a quick google search, this update only applies to the current shell you have open. It can probably be fixed by typing python3, as mac and linux are similar enough for things like this to coincide. Link to the result of google search.
Also, as ninjagecko stated, most programs have not been updated to 3.x yet, so having the default python as 3.x would break many python scripts used in applications.
If you're here looking for a way to increment a specific field value in a model...
This worked for me as of [email protected]
User.increment("field", {by: 1, where: {id: 1});
I've seen this happen in a piece of code where the often recurring check for null values was performed:
if(( A==null ) && ( B==null )
return +1;//WRONG: two null values should return 0!!!
A .pl is a single script.
In .pm (Perl Module) you have functions that you can use from other Perl scripts:
A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.
You can create a list of primes using list comprehensions in a fairly elegant manner. Taken from here:
>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
I had this issue after installing HP ProtectTools on HP Probook 6470b, because of included Password Manager.
To disable it run "HP ProtectTools Administrative Console", go to "Applications->Settings", open "Applications" tab and uncheck "Status" checkbox.
After PC restart problem should be solved, but you can't use Password Manager anymore :(
This post was helpful to solve my problem which has a little different XML format... my XML contains a list of keys like the following example and I store the XML in the SourceKeys column in a table named DeleteBatch:
<k>1</k>
<k>2</k>
<k>3</k>
Create the table and populate it with some data:
CREATE TABLE dbo.DeleteBatch (
ExecutionKey INT PRIMARY KEY,
SourceKeys XML)
INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 1,
(CAST('<k>1</k><k>2</k><k>3</k>' AS XML))
INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 2,
(CAST('<k>100</k><k>101</k>' AS XML))
Here's my SQL to select the keys from the XML:
SELECT ExecutionKey, p.value('.', 'int') AS [Key]
FROM dbo.DeleteBatch
CROSS APPLY SourceKeys.nodes('/k') t(p)
Here's the query results...
ExecutionKey Key 1 1 1 2 1 3 2 100 2 101
/System/Library/Frameworks/JavaVM.framework/
Also see Java 7 path on mountain lion
It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.
You can do this by using IPTABLES to redirect port 80 to 8080.
A single line implementation of dcastro's answer (the most compliant with other languages):
int Mod(int a, int n)
{
return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
}
If you'd like to keep the use of %
operator (you can't overload native operators in C#):
public class IntM
{
private int _value;
private IntM(int value)
{
_value = value;
}
private static int Mod(int a, int n)
{
return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
}
public static implicit operator int(IntM i) => i._value;
public static implicit operator IntM(int i) => new IntM(i);
public static int operator %(IntM a, int n) => Mod(a, n);
public static int operator %(int a, IntM n) => Mod(a, n);
}
Use case, both works:
int r = (IntM)a % n;
// Or
int r = a % n(IntM);
This code will perform the click operation on the WebElement
"we" after 100 ms:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);
If the OP is trying to determine the history that was traversed by a branch when a particular commit was created ("find out what branch a commit comes from given its SHA-1 hash value"), then without the reflog there aren't any records in the Git object database that shows what named branch was bound to what commit history.
(I posted this as an answer in reply to a comment.)
Hopefully this script illustrates my point:
rm -rf /tmp/r1 /tmp/r2; mkdir /tmp/r1; cd /tmp/r1
git init; git config user.name n; git config user.email [email protected]
git commit -m"empty" --allow-empty; git branch -m b1; git branch b2
git checkout b1; touch f1; git add f1; git commit -m"Add f1"
git checkout b2; touch f2; git add f2; git commit -m"Add f2"
git merge -m"merge branches" b1; git checkout b1; git merge b2
git clone /tmp/r1 /tmp/r2; cd /tmp/r2; git fetch origin b2:b2
set -x;
cd /tmp/r1; git log --oneline --graph --decorate; git reflog b1; git reflog b2;
cd /tmp/r2; git log --oneline --graph --decorate; git reflog b1; git reflog b2;
The output shows the lack of any way to know whether the commit with 'Add f1' came from branch b1 or b2 from the remote clone /tmp/r2.
(Last lines of the output here)
+ cd /tmp/r1
+ git log --oneline --graph --decorate
* f0c707d (HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: merge b2: Fast-forward
086c9ce b1@{1}: commit: Add f1
18feb84 b1@{2}: Branch: renamed refs/heads/master to refs/heads/b1
18feb84 b1@{3}: commit (initial): empty
+ git reflog b2
f0c707d b2@{0}: merge b1: Merge made by the 'recursive' strategy.
80c10e5 b2@{1}: commit: Add f2
18feb84 b2@{2}: branch: Created from b1
+ cd /tmp/r2
+ git log --oneline --graph --decorate
* f0c707d (HEAD, origin/b2, origin/b1, origin/HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: clone: from /tmp/r1
+ git reflog b2
f0c707d b2@{0}: fetch origin b2:b2: storing head
Two answers for you:
Based on parsing
Regular expression
Note that in both cases, I've interpreted "positive integer" to include 0
, even though 0
is not positive. I include notes if you want to disallow 0
.
If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:
function isNormalInteger(str) {
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
or if you want to allow whitespace and leading zeros:
function isNormalInteger(str) {
str = str.trim();
if (!str) {
return false;
}
str = str.replace(/^0+/, "") || "0";
var n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
Live testbed (without handling leading zeros or whitespace):
function isNormalInteger(str) {_x000D_
var n = Math.floor(Number(str));_x000D_
return n !== Infinity && String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
var result = isNormalInteger(str);_x000D_
console.log(_x000D_
str + ": " +_x000D_
(result ? "Yes" : "No") +_x000D_
(expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
);_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
"click",_x000D_
function() {_x000D_
test(gid("text").value);_x000D_
},_x000D_
false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
String:_x000D_
<input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
Live testbed (with handling for leading zeros and whitespace):
function isNormalInteger(str) {_x000D_
str = str.trim();_x000D_
if (!str) {_x000D_
return false;_x000D_
}_x000D_
str = str.replace(/^0+/, "") || "0";_x000D_
var n = Math.floor(Number(str));_x000D_
return String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
var result = isNormalInteger(str);_x000D_
console.log(_x000D_
str + ": " +_x000D_
(result ? "Yes" : "No") +_x000D_
(expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
);_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
"click",_x000D_
function() {_x000D_
test(gid("text").value);_x000D_
},_x000D_
false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", true);_x000D_
test(" 123 ", true);
_x000D_
<label>_x000D_
String:_x000D_
<input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
If you want to disallow 0
, just change >= 0
to > 0
. (Or, in the version that allows leading zeros, remove the || "0"
on the replace
line.)
How that works:
In the version allowing whitespace and leading zeros:
str = str.trim();
removes any leading and trailing whitepace.if (!str)
catches a blank string and returns, no point in doing the rest of the work.str = str.replace(/^0+/, "") || "0";
removes all leading 0s from the string — but if that results in a blank string, restores a single 0.Number(str)
: Convert str
to a number; the number may well have a fractional portion, or may be NaN
.
Math.floor
: Truncate the number (chops off any fractional portion).
String(...)
: Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don't quite know where the split is, the details are in the spec, but for whole numbers I believe it's at the point you've exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..)
... === str
: Compares that to the original string.
n >= 0
: Check that it's positive.
Note that this fails for the input "+1"
, any input in scientific notation that doesn't turn back into the same scientific notation at the String(...)
stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can't accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789
will fail). The former is an easy fix, the latter two not so much.
The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional +
followed by either 0
or a string in normal decimal format:
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
Live testbed:
function isNormalInteger(str) {_x000D_
return /^\+?(0|[1-9]\d*)$/.test(str);_x000D_
}_x000D_
function gid(id) {_x000D_
return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
var result = isNormalInteger(str);_x000D_
console.log(_x000D_
str + ": " +_x000D_
(result ? "Yes" : "No") +_x000D_
(expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
);_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
"click",_x000D_
function() {_x000D_
test(gid("text").value);_x000D_
},_x000D_
false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
String:_x000D_
<input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
How that works:
^
: Match start of string
\+?
: Allow a single, optional +
(remove this if you don't want to)
(?:...|...)
: Allow one of these two options (without creating a capture group):
(0|...)
: Allow 0
on its own...
(...|[1-9]\d*)
: ...or a number starting with something other than 0
and followed by any number of decimal digits.
$
: Match end of string.
If you want to disallow 0
(because it's not positive), the regular expression becomes just /^\+?[1-9]\d*$/
(e.g., we can lose the alternation that we needed to allow 0
).
If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*)
with \d+
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
If you want to allow whitespace, add \s*
just after ^
and \s*
just before $
.
Note for when you convert that to a number: On modern engines it would probably be fine to use +str
or Number(str)
to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10)
to ensure that it's parsed as decimal (base 10). parseInt
would ignore garbage at the end of the string, but we've ensured there isn't any with the regex.
cat(capture.output(print(my.list), file="test.txt"))
from R: Export and import a list to .txt file https://stackoverflow.com/users/1855677/42 is the only thing that worked for me. This outputs the list of lists as it is in the text file
For me path for templateUrl was not correct
I was using
shopping-list-edit.component.html
Whereas it should have been
./shopping-list-edit.component.html
Silly mistake but happens when starting out. Hope that helps somebody in distress.
Below you have some VALID html5 example document. The type
attribute in script
tag is not mandatory in HTML5.
You use jquery by $
charater. Put libraries (like jquery) in <head>
tag - but your script put allways at the bottom of document (<body>
tag) - due this you will be sure that all libraries and html document will be loaded when your script execution starts. You can also use src
attribute in bottom script tag to include you script file instead of putting direct js code like above.
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Example</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div>Im the content</div>_x000D_
_x000D_
<script>_x000D_
alert( $('div').text() ); // show message with div content_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
(something else)
should be a.Country
if Country
is nullable then make(something else)
be a.Country OR a.Country is NULL
Try this. It is not watertight1, but it might be good enough:
function addhttp($url) {
if (!preg_match("@^[hf]tt?ps?://@", $url)) {
$url = "http://" . $url;
}
return $url;
}
1. That is, prefixes like "fttps://" are treated as valid.
What you want is a SQL case statement. The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
Works for me. How log all php errors to a log fiie?
Just add following line to /etc/php.ini to log errors to specified file – /var/log/php-scripts.log
vi /etc/php.ini
Modify error_log directive
error_log = /var/log/php-scripts.log
Make sure display_errors set to Off (no errors to end users)
display_errors = Off
Save and close the file. Restart web server:
/etc/init.d/httpd restart
How do I log errors to syslog or Windows Server Event Log?
Modify error_log as follows :
error_log = syslog
How see logs?
Login using ssh or download a log file /var/log/php-scripts.log using sftp:
$ sudo tail -f /var/log/php-scripts.log
Say you were opening a file in your current directory. The command would be:
start %cd%\filename.filetype
I hope I answered your question.
Here is @DwB solution upgraded to Commons CLI 1.3.1 compliance (replaced deprecated components OptionBuilder and GnuParser). The Apache documentation uses examples that in real life have unmarked/bare arguments but ignores them. Thanks @DwB for showing how it works.
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public static void main(String[] parameters) {
CommandLine commandLine;
Option option_A = Option.builder("A").argName("opt3").hasArg().desc("The A option").build();
Option option_r = Option.builder("r").argName("opt1").hasArg().desc("The r option").build();
Option option_S = Option.builder("S").argName("opt2").hasArg().desc("The S option").build();
Option option_test = Option.builder().longOpt("test").desc("The test option").build();
Options options = new Options();
CommandLineParser parser = new DefaultParser();
options.addOption(option_A);
options.addOption(option_r);
options.addOption(option_S);
options.addOption(option_test);
String header = " [<arg1> [<arg2> [<arg3> ...\n Options, flags and arguments may be in any order";
String footer = "This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated methods replaced)";
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("CLIsample", header, options, footer, true);
String[] testArgs =
{ "-r", "opt1", "-S", "opt2", "arg1", "arg2",
"arg3", "arg4", "--test", "-A", "opt3", };
try
{
commandLine = parser.parse(options, testArgs);
if (commandLine.hasOption("A"))
{
System.out.print("Option A is present. The value is: ");
System.out.println(commandLine.getOptionValue("A"));
}
if (commandLine.hasOption("r"))
{
System.out.print("Option r is present. The value is: ");
System.out.println(commandLine.getOptionValue("r"));
}
if (commandLine.hasOption("S"))
{
System.out.print("Option S is present. The value is: ");
System.out.println(commandLine.getOptionValue("S"));
}
if (commandLine.hasOption("test"))
{
System.out.println("Option test is present. This is a flag option.");
}
{
String[] remainder = commandLine.getArgs();
System.out.print("Remaining arguments: ");
for (String argument : remainder)
{
System.out.print(argument);
System.out.print(" ");
}
System.out.println();
}
}
catch (ParseException exception)
{
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
}
}
Output:
usage: CLIsample [-A <opt3>] [-r <opt1>] [-S <opt2>] [--test]
[<arg1> [<arg2> [<arg3> ...
Options, flags and arguments may be in any order
-A <opt3> The A option
-r <opt1> The r option
-S <opt2> The S option
--test The test option
This is DwB's solution brought to Commons CLI 1.3.1 compliance (deprecated
methods replaced)
Option A is present. The value is: opt3
Option r is present. The value is: opt1
Option S is present. The value is: opt2
Option test is present. This is a flag option.
Remaining arguments: arg1 arg2 arg3 arg4
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.
Suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with (supported in practically all browser versions):
Object.keys(j).map(function(_) { return j[_]; })
or simply:
Object.values(j)
Output:
["1", "2", "3", "4"]
the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -
Previous month
#cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
DEC-2016
Current month
#cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
JAN-2017
Next month
#cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
FEB-2017
Use streams:
someCollection.stream().collect(Collectors.toList())
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
With tr
:
# Converts upper to lower case
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt
# Converts lower to upper case
$ tr '[:lower:]' '[:upper:]' < input.txt > output.txt
Or, sed
on GNU (but not BSD or Mac as they don't support \L
or \U
):
# Converts upper to lower case
$ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt
# Converts lower to upper case
$ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt
It worked for me now, I have change the setting of my google account as below:
System.out.println("Start");
final String username = "[email protected]";
final String password = "************";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Transport transport=session.getTransport();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));//formBean.getString("fromEmail")
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("subject");//formBean.getString(
message.setText("mailBody");
transport.connect();
transport.send(message, InternetAddress.parse("[email protected]"));//(message);
System.out.println("Done");
} catch (MessagingException e) {
System.out.println("e="+e);
e.printStackTrace();
throw new RuntimeException(e);
}
Though I have enabled SSL and TSL while running program in this link of same post. I spend a lot of time but than I realized and found this link. And done 2 following steps and setting control in google. :
Disable the 2-step verification (password and OTP)
Enabling to allow to access less secure app(Allow less secure apps: ON.)
Now I am able to send mail using above program.
As using the String.substring
and String.lastIndex
in a one-liner is good, there are some issues in terms of being able to cope with certain file paths.
Take for example the following path:
a.b/c
Using the one-liner will result in:
a
That's incorrect.
The result should have been c
, but since the file lacked an extension, but the path had a directory with a .
in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.
Need for checks
Inspired by skaffman's answer, I took a look at the FilenameUtils.removeExtension
method of the Apache Commons IO.
In order to recreate its behavior, I wrote a few tests the new method should fulfill, which are the following:
Path Filename -------------- -------- a/b/c c a/b/c.jpg c a/b/c.jpg.jpg c.jpg a.b/c c a.b/c.jpg c a.b/c.jpg.jpg c.jpg c c c.jpg c c.jpg.jpg c.jpg
(And that's all I've checked for -- there probably are other checks that should be in place that I've overlooked.)
The implementation
The following is my implementation for the removeExtension
method:
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf(".");
if (extensionIndex == -1)
return filename;
return filename.substring(0, extensionIndex);
}
Running this removeExtension
method with the above tests yield the results listed above.
The method was tested with the following code. As this was run on Windows, the path separator is a \
which must be escaped with a \
when used as part of a String
literal.
System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));
System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));
System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));
The results were:
c
c
c.jpg
c
c
c.jpg
c
c
c.jpg
The results are the desired results outlined in the test the method should fulfill.
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:
CREATE TABLE voting (
QuestionID NUMERIC,
MemberID NUMERIC,
PRIMARY KEY (QuestionID, MemberID)
);
The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:
SELECT * FROM voting WHERE QuestionID = 7
it will use the primary key's index. If however you do this:
SELECT * FROM voting WHERE MemberID = 7
it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.
If necessary, add an index on the other:
CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
In my case it did not work until I ran the command
composer dump-autoload
that way you can leave the foreign keys inside the create Schema
public function up()
{
//
Schema::create('priorities', function($table) {
$table->increments('id', true);
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('priority_name');
$table->smallInteger('rank');
$table->text('class');
$table->timestamps('timecreated');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('priorities');
}
This answer below shows another method using "regexp feature of the Description Setter Plugin" which solved my problem as I could not install new plugins on Jenkins due to permission issues:
A rather separable way of doing this is to use
import tensorflow as tf
from keras import backend as K
num_cores = 4
if GPU:
num_GPU = 1
num_CPU = 1
if CPU:
num_CPU = 1
num_GPU = 0
config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
inter_op_parallelism_threads=num_cores,
allow_soft_placement=True,
device_count = {'CPU' : num_CPU,
'GPU' : num_GPU}
)
session = tf.Session(config=config)
K.set_session(session)
Here, with booleans
GPU
and CPU
, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU
and num_CPU
define this value. num_cores
then sets the number of CPU cores available for usage via intra_op_parallelism_threads
and inter_op_parallelism_threads
.
The intra_op_parallelism_threads
variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads
variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).
allow_soft_placement
allows for operations to be run on the CPU if any of the following criterion are met:
there is no GPU implementation for the operation
there are no GPU devices known or registered
there is a need to co-locate with other inputs from the CPU
All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.
Note: This requires tensorflow-gpu
and cuda
/cudnn
to be installed because the option is given to use a GPU.
Refs:
A little alternative to @gasp´s answer is to simply put the actual domain name you are running it from. Docs: https://httpd.apache.org/docs/2.4/upgrading.html
In the following example, there is no authentication and all hosts in the example.org domain are allowed access; all other hosts are denied access.
Apache 2.2 configuration:
Order Deny,Allow
Deny from all
Allow from example.org
Apache 2.4 configuration:
Require host example.org
First of all, You can verify this on your own by writing a simple TestCase!
empty Arraylist (with nulls as its items)
Second, If ArrayList is EMPTY that means it is really empty, it cannot have NULL or NON-NULL things as element.
Third,
List list = new ArrayList();
list.add(null);
System.out.println(list == null)
would print false.
I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards
depends on Less 1.7.0
https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less
.if(isnumber(2), {
.-then(){
log {
isnumber: true;
}
}
.-else(){
log {
isnumber: false;
}
}
});
.if(lightness(#fff) gt (20% * 2), {
.-then(){
log {
is-light: true;
}
}
});
using on example from above
.if(@debug, {
.-then(){
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
});
The previous answers using the ISNULL
function are correct only for MS Sql Server. The COALESCE
function will also work in SQL Server. But will also work in standard SQL database systems. In the given example:
SELECT sum(COALESCE(TotalHoursM,0))
+ COALESCE(TotalHoursT,0)
+ COALESCE(TotalHoursW,0)
+ COALESCE(TotalHoursTH,0)
+ COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest
This is identical to the ISNULL
solution with the only difference being the name of the function. Both work in SQL Server but, COALESCE
is ANSI standard and ISNULL
is not. Also, COALESCE
is more flexible.
ISNULL
will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned.
COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not NULL
. When there are only two parameters the effect is the same as ISNULL
.
Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel ... />
</ScrollViewer>
Yes, presumably it wants the path to the javadoc
command line tool that comes with the JDK (in the bin directory, same as java
and javac
).
Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.
It turns out this is either a poorly documented, intentionally misleading, or undocumented interaction between the "controls" param and the "modestbranding" param. There is no way to remove YouTube's logo from an embedded YouTube video, at least while the video controls are exposed. All you get to do is choose how and when you want the logo to appear. Here are the details:
If controls = 1 and modestbranding = 1, then the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, and shows when the play controls are exposed as a big gray scale watermark in the lower right. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=1&&showinfo=0&modestbranding=1" frameborder="0"></iframe>
If controls = 1 and modestbranding = 0 (our change here), then the YouTube logo is smaller, is not on the video still image as a grayscale watermark in the lower right, and shows only when the controls are exposed as a white icon in the lower right. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=1&&showinfo=0&modestbranding=0" frameborder="0"></iframe>
If controls = 0, then the modestbranding param is ignored and the YouTube logo is bigger, is on the video still image as a grayscale watermark in the lower right, the watermark appears on hover of a playing video, and the watermark appears in the lower right of any paused video. example:
<iframe width="560" height="315" src="https://www.youtube.com/embed/Z6ytvzNlmRo?rel=0&controls=0&&showinfo=0&modestbranding=1" frameborder="0"></iframe>
Swift:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
// remove separator for last cell
cell.separatorInset = indexPath.row < numberOfRowsInSection-1
? tableView.separatorInset
: UIEdgeInsets(top: 0, left: tableView.bounds.size.width, bottom: 0, right: 0)
return cell
}
Objective-C:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
// remove separator for last cell
cell.separatorInset = (indexPath.row < numberOfRowsInSection-1)
? tableView.separatorInset
: UIEdgeInsetsMake(0.f, tableView.bounds.size.width, 0.f, 0.f);
return cell;
}
For SQL Server 2000, this should tell you only the #temp tables in your session. (Adapted from my example for more modern versions of SQL Server here.) This assumes you don't name your tables with three consecutive underscores, like CREATE TABLE #foo___bar
:
SELECT
name = SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1),
t.id
FROM tempdb..sysobjects AS t
WHERE t.name LIKE '#%[_][_][_]%'
AND t.id =
OBJECT_ID('tempdb..' + SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1));
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
In a specific case the issue is due to the maven-archetype-webapp which is released for a dynamic webapp, faceted to the ver.2.5 (see the produced web.xml and the related xsd) and it's related to eclipse. When you try to change the project facet to dynamic webapp > 2.5 the src folder structure will syntactically change (the 2.5 is different from 3.1), but not fisically.
This is why you will face in a null pointer exception if you apply to the changes.
To solve it you have to set from the project facets configuration the Default configuration. Apply the changes, then going into the Java Build Path you have to remove the /src folder and create the /src/main/java folder at least (it's also required /src/main/resources and /src/test/java to be compliant) re-change into the required configuration you desire (3.0, 3.1) and then do apply.
Yes. ArrayList
has a toArray()
method.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
You need a /g
on there, like this:
var textTitle = "this is a test";_x000D_
var result = textTitle.replace(/ /g, '%20');_x000D_
_x000D_
console.log(result);
_x000D_
You can play with it here, the default .replace()
behavior is to replace only the first match, the /g
modifier (global) tells it to replace all occurrences.
A "Collapse All" command exists in recent builds (e.g. 3.2 M6) and is bound to Ctrl+Shift+NUM_KEYPAD_DIVIDE by default.
You can also configure it in Preferences->Editor->Keys.
When I accidentally switched to a guest wifi network I got this error. Had to switch back to my default wifi network.
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
By the way it is written, clean rule is invoked only if it is explicitly called:
make clean
I think it is better, than make clean every time. If you want to do this by your way, try this:
CXX = g++ -O2 -Wall all: clean code1 code2 code1: code1.cc utilities.cc $(CXX) $^ -o $@ code2: code2.cc utilities.cc $(CXX) $^ -o $@ clean: rm ... echo Clean done
You can convert it to datetime
, and then use DATEADD(DAY, -30, date)
.
See here.
edit
I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:
DATEADD(DAY, -30, GETDATE())
You should add next permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And then here is usages in code:
val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)
The same way you declare any other variable, just use the bit
type:
DECLARE @MyVar bit
Set @MyVar = 1 /* True */
Set @MyVar = 0 /* False */
SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar
Yes, you can... If a then a, else if b then if c then c(b), else b, else null
a ? a : (b ? (c ? c(b) : b) : null)
a
? a
: b
? c
? c(b)
: b
: null
Ternary operator ?:
used as inline if-else is right associative. In short this means that the rightmost ?
gets fed first and it takes exactly one closest operand on the left and two, with a :
, on the right.
Practically speaking, consider the following statement (same as above):
a ? a : b ? c ? c(b) : b : null
The rightmost ?
gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?
.
a ? a : b ? c ? c(b) : b : null
^ <---- RTL
1. |1-?-2----:-3|
^ <-
2. |1-?|--2---------|:-3---|
^ <-
3.|1-?-2-:|--3--------------------|
result: a ? a : (b ? (c ? c(b) : b) : null)
- Term
a
is read.
Node:a
- Nonterminal
?
is read.
Node:a ?
- Term
a
is read.
Node:a ? a
- Nonterminal
:
is read.
Node:a ? a :
- Term
b
is read.
Node:a ? a : b
- Nonterminal
?
is read, triggering the right-associativity rule. Associativity decides:
node:a ? a : (b ?
- Term
c
is read.
Node:a ? a : (b ? c
- Nonterminal
?
is read, re-applying the right-associativity rule.
Node:a ? a : (b ? (c ?
- Term
c(b)
is read.
Node:a ? a : (b ? (c ? c(b)
- Nonterminal
:
is read.
Node:a ? a : (b ? (c ? c(b) :
- Term
b
is read.
Node:a ? a : (b ? (c ? c(b) : b
- Nonterminal
:
is read. The ternary operator?:
from previous scope is satisfied and the scope is closed.
Node:a ? a : (b ? (c ? c(b) : b) :
- Term
null
is read.
Node:a ? a : (b ? (c ? c(b) : b) : null
- No tokens to read. Close remaining open parenthesis.
#Result is:a ? a : (b ? (c ? c(b) : b) : null)
The ugly oneliner from above could (and should) be rewritten for readability as:
(Note that the indentation does not implicitly define correct closures as brackets () do.)
a
? a
: b
? c
? c(b)
: b
: null
for example
return a + some_lengthy_variable_name > another_variable
? "yep"
: "nop"
Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity
var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!
a
&& a
|| b
&& c
&& c(b) // if this returns false, || b is processed
|| b
|| null
Using logical operators as in this example is ugly and wrong, but this is where they shine...
This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.
function f(mayBeNullOrFalsy) {
var cantBeNull = mayBeNullOrFalsy || 42 // "default" value
var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42 // ugly...
..
}
false && (anything) // is short-circuit evaluated to false.
true || (anything) // is short-circuit evaluated to true.
Logical operators
Null coalescence
Short-circuit evaluation
developer.mozilla.org~Nullish_coalescing_operator
function f(mayBeNullOrUndefined, another) {
var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
another ??= 37 // nullish coalescing self-assignment
another = another ?? 37 // same effect
..
}
Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
// before
var street = user.address && user.address.street
// after
var street = user.address?.street
// combined with Nullish coalescing
// before
var street = user.address
? user.address.street
: "N/A"
// after
var street = user.address?.street ?? "N/A"
// arrays
obj.someArray?.[index]
// functions
obj.someMethod?.(args)
your folder name is scripts..
and you are Referencing it like ../script/login.js
Also make sure that script folder is in your project directory
Thanks
I think your answer can be found on this page. From the page:
This Folder, Subfolders and Files:
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
To add to the answers above, while print can only take one parameter, it will allow for concatenation of multiple values, ie:
$count = 5;
print "This is " . $count . " values in " . $count/5 . " parameter";
This is 5 values in 1 parameter
FOR ANDROID:
You only need to enable “USB remote debugger” within your android device and plug with a USB cable. Then open your application in the device. Chrome will detect the remote browser and you can see the console in the same way than you see it when you use Chrome locally.
Use this link: chrome://inspect/#devices
in Chrome browser (you'll have to paste it into the nav bar).
If your app crashes in the device you only need to see the console’s log within your browser and see what happens. You also can add functionality, change variables, and override functions in the same way than we do it with our local browser.
Read this article for more information on the steps to take.
This will work ONLY with devices running Android 4.4+.
FOR iOS:
Use Safari for iOS, follow these steps:
1.In your iOS device go to Settings > Safari > Advanced > Web Inspector to enable Web Inspector
2.Open Safari on your iOS device.
3.Connect it to your computer via USB.
4.Open Safari on your computer.
5.In Safari’s menu, go to Develop and, look for your device’s name.
6.Select the tab you want to debug.
You can get a similar result by creating scalar-valued functions that return the variable values. Of course, function calls can be expensive if you use them in queries that return a large number of results, but if you're limiting the result-set you should be fine. Here I'm using a database created just to hold these semi-static values, but you can create them on a per-database basis, too. As you can see, there are no input variables, just a well-named function that returns a static value: if you change that value in the function, it will instantly change anywhere it's used (the next time it's called).
USE [globalDatabase]
GO
CREATE FUNCTION dbo.global_GetStandardFonts ()
RETURNS NVARCHAR(255)
AS
BEGIN
RETURN 'font-family:"Calibri Light","sans-serif";'
END
GO
-- Usage:
SELECT '<html><head><style>body{' + globalDatabase.dbo.global_GetStandardFonts() + '}</style></head><body>...'
-- Result: <html><head><style>body{font-family:"Calibri Light","sans-serif";}</style></head><body>...
have you tried:
$("#yourAnchor").click(function () {
$("#yourTextarea").val("your text");
});
not sure about autohighlighting, though.
EDIT:
To append:
$("#yourAnchor").click(function () {
$("#yourTextarea").append("your text to append");
});
I know this is old... But I was having the same problem today and found a solution:
Model.find_by_sql
If you want to instantiate the results:
Client.find_by_sql("
SELECT * FROM clients
INNER JOIN orders ON clients.id = orders.client_id
ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]
Model.connection.select_all('sql').to_hash
If you just want a hash of values:
Client.connection.select_all("SELECT first_name, created_at FROM clients
WHERE id = '1'").to_hash
# => [
{"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
{"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]
Result object:
select_all
returns a result
object. You can do magic things with it.
result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]
# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
[2, "title_2", "body_2"],
...
]
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
# ActiveRecord::Result also includes Enumerable.
result.each do |row|
puts row['title'] + " " + row['body']
end
Sources:
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:
KeyStore ks = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);
this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:
SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
You could always use apache commons' DateUtils
class. It has the static method isSameDay()
which "Checks if two date objects are on the same day ignoring time."
static boolean isSameDay(Date date1, Date date2)
Hello Friends Try This
In this Code
1) How to Declare 2 File Provider in Manifest.
2) First Provider for file Download
3) second Provider used for camera and gallary
STEP 1
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
Provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="apks" path="." />
</paths>
Second Provider
<provider
android:name=".Utils.MyFileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities"
tools:ignore="InnerclassSeparator">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" />
</provider>
file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="storage/emulated/0" path="."/>
</paths>
.Utils.MyFileProvider
Create Class MyFileProvider (only Create class no any method declare)
When you used File Provider used (.fileprovider) this name and you used for image (.provider) used this.
IF any one Problem to understand this code You can Contact on [email protected] i will help you.
You can use the --prefix
option:
mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>
The package(s) will then be installed in ./install/here/node_modules
. The mkdir
is needed since npm might otherwise choose an already existing node_modules
directory higher up in the hierarchy. (See npm documentation on folders.)
In Angular we can add an option as placeholder that can be hidden in option dropdown. We can even add a custom dropdown icon as background that replaces browser dropdown icon.
The trick is to enable placeholder css only when value is not selected
/**My Component Template*/
<div class="dropdown">
<select [ngClass]="{'placeholder': !myForm.value.myField}"
class="form-control" formControlName="myField">
<option value="" hidden >Select a Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
/**My Component.TS */
constructor(fb: FormBuilder) {
this.myForm = this.fb.build({
myField: ''
});
}
/**global.scss*/
.dropdown {
width: 100%;
height: 30px;
overflow: hidden;
background: no-repeat white;
background-image:url('angle-arrow-down.svg');
background-position: center right;
select {
background: transparent;
padding: 3px;
font-size: 1.2em;
height: 30px;
width: 100%;
overflow: hidden;
/*For moz*/
-moz-appearance: none;
/* IE10 */
&::-ms-expand {
display: none;
}
/*For chrome*/
-webkit-appearance:none;
&.placeholder {
opacity: 0.7;
color: theme-color('mutedColor');
}
option {
color: black;
}
}
}
Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.
If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:
sudo add-apt-repository ppa:jonathonf/python-3.6 # (only for 16.04 LTS)
Then, run the following (this works out-of-the-box on 16.10 and 17.04):
sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1
(or a more recent version of Python 3.6):
python --version # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".
This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip
.
For example if a compressed pickle archive is made like this,
import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
pickle.dump([1,2,3], ofp)
Trying to open it throws the errors
with open('test.pklz', 'rb') as ifp:
print(pickle.load(ifp))
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.
But, if the pickle file is opened using gzip
all is harmonious
with gzip.open('test.pklz', 'rb') as ifp:
print(pickle.load(ifp))
[1, 2, 3]
You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.
Compress!!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
setresult.putExtra("BMP",bytes);
Uncompress!!
byte[] bytes = data.getByteArrayExtra("BMP");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Simple and fast since a 1d array is essentially a vector
vector <- array[1:length(array)]
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
You can manage to have a pure CSS implementation with max-height
#main-image{
max-height: 0;
overflow: hidden;
background: red;
-prefix-animation: slide 1s ease 3.5s forwards;
}
@keyframes slide {
from {max-height: 0;}
to {max-height: 500px;}
}
You might have to also set padding
, margin
and border
to 0, or simply padding-top
, padding-bottom
, margin-top
and margin-bottom
.
I updated the demo of Duopixel here : http://jsfiddle.net/qD5XX/231/
I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.
So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.
In short: what you are looking for cannot be done legally within the structure of the syntax.
Source: W3 Validator
Its a fixed version of MaxOvrdrv's Code.
public static bool IsReadable(this DirectoryInfo di)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (UnauthorizedAccessException uae)
{
Debug.WriteLine(uae.ToString());
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) &&
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) &&
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
public static bool IsWriteable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (UnauthorizedAccessException uae)
{
Debug.WriteLine(uae.ToString());
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) &&
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) &&
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) &&
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) &&
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
Some good answers here. Especially the one by @torek. I thought I'd add this work-around with a little explanation for those in a rush.
To summarize, what happens is that when you move a tag locally, it changes the tag from a non-Null commit value to a different value. However, because git (as a default behavior) doesn't allow changing non-Null remote tags, you can't push the change.
The work-around is to delete the tag (and tick remove all remotes). Then create the same tag and push.
Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use
$data = file_get_contents("php://input");
to just retrieve the http body and handle it yourself. See PHP input/output streams.
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.
The padding options padx
and pady
of the grid
and pack
methods can take a 2-tuple that represent the left/right and top/bottom padding.
Here's an example:
import tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
l1 = tk.Label(self.root, text="Hello")
l2 = tk.Label(self.root, text="World")
l1.grid(row=0, column=0, padx=(100, 10))
l2.grid(row=1, column=0, padx=(10, 100))
app = MyApp()
app.root.mainloop()
... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26'
may potentially work better(if you have an index on date_column) than DATE
.
class Example extends React.Component {
render() {
return <h1>{this.props.text}</h1>;
}
}
Example.defaultProps = { text: 'yo' };
You can get to SIZES
by means of self.SIZES
(in an instance method) or cls.SIZES
(in a class method).
In any case, you will have to be explicit about where to find SIZES
. An alternative is to put SIZES
in the module containing the classes, but then you need to define all classes in a single module.
this works for me, full working example (I wish more people would do this):
//logon impersonation
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute
...
class Program {
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public void DoWorkUnderImpersonation() {
//elevate privileges before doing file copy to handle domain security
WindowsImpersonationContext impersonationContext = null;
IntPtr userHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
string user = ConfigurationManager.AppSettings["ImpersonationUser"];
string password = ConfigurationManager.AppSettings["ImpersonationPassword"];
try {
Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);
// if domain name was blank, assume local machine
if (domain == "")
domain = System.Environment.MachineName;
// Call LogonUser to get a token for the user
bool loggedOn = LogonUser(user,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref userHandle);
if (!loggedOn) {
Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
return;
}
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
Console.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);
//run the program with elevated privileges (like file copying from a domain server)
DoWork();
} catch (Exception ex) {
Console.WriteLine("Exception impersonating user: " + ex.Message);
} finally {
// Clean up
if (impersonationContext != null) {
impersonationContext.Undo();
}
if (userHandle != IntPtr.Zero) {
CloseHandle(userHandle);
}
}
}
private void DoWork() {
//everything in here has elevated privileges
//example access files on a network share through e$
string[] files = System.IO.Directory.GetFiles(@"\\domainserver\e$\images", "*.jpg");
}
}
To create frames from video:
ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner
Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss
& -t
)
Then create video from image/frames eg.:
ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4
I also made a library for this. It is fully configurable with a Mustache template. That can:
I also made:
More details on Github: https://github.com/tomasbjerre/git-changelog-lib
From command line:
npx git-changelog-command-line -std -tec "
# Changelog
Changelog for {{ownerName}} {{repoName}}.
{{#tags}}
## {{name}}
{{#issues}}
{{#hasIssue}}
{{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{/hasIssue}}
{{^hasIssue}}
### {{name}}
{{/hasIssue}}
{{#commits}}
**{{{messageTitle}}}**
{{#messageBodyItems}}
* {{.}}
{{/messageBodyItems}}
[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*
{{/commits}}
{{/issues}}
{{/tags}}
"
Or in Jenkins:
The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n
, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n
on input, and conversely on output.
From the C99 standard (the N869 draft document), §7.19.2/2,
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.
And in §7.19.3/2
Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.
About use of fseek
, in §7.19.9.2/4:
For a text stream, either
offset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
About use of ftell
, in §17.19.9.4:
The
ftell
function obtains the current value of the file position indicator for the stream pointed to bystream
. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by thefseek
function for returning the file position indicator for the stream to its position at the time of theftell
call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
I think that’s the most important, but there are some more details.
Locate your ipython binary. If you have used anaconda to install ipython-notebook on a mac, chances are it will be in the /Users/[name]/anaconda/bin/
directory
in that directory, instead of launching your notebook as
./ipython notebook
add a --notebook-dir=<unicode>
option.
./ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'
I use a bashscript in my ipython bin directory to launch my notebooks:
DIR=$(dirname $0)
$DIR/ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'
Note - the path to the notebook dir is relative to the ipython bin directory.
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.
remote: error: GH003: Sorry, force-pushing to master is not allowed.
If you get an error message like this one please try the following steps.
To effectively reset your fork you need to follow these steps :
git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin
Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :
git checkout master
git push --force origin
Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :
git push origin --delete tmp_master
git branch -D tmp_master
Other answers warning about lossing your change still apply, be carreful.
You should use the =
operator for string comparison:
Sourcesystem="ABC"
if [ "$Sourcesystem" = "XYZ" ]; then
echo "Sourcesystem Matched"
else
echo "Sourcesystem is NOT Matched $Sourcesystem"
fi;
man test
says that you use -z
to match for empty strings.
PHP 7: Null Coalesce Operator
//$http = 'SCRIPT_NAME';
$http = 'X_REQUESTED_WITH';
$http = strtoupper($http);
$header = $_SERVER['HTTP_'.$http] ?? $_SERVER[$http] ?? NULL;
if(is_null($header)){
die($http. ' Not Found');
}
echo $header;
If you have pending scheduled local notifications and don't want to use cancelAllLocalNotifications
to clear old ones in Notification Center, you can also do the following:
[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
It appears that if you set the scheduledLocalNotifications
it clears the old ones in Notification Center, and by setting it to itself, you retain the pending local notifications.
TL;DR Use Cmd/Ctrl+Shift+P
then Package Control: Install Package
, then Print to HTML
and install it. Use Alt+Shift+P
to print.
My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.
This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.
Install the "Print to HTML" package using the package manager.
Ctrl + Shift + P
=> Gives a list of commands.install
"Package Control: Install Package
"print to
"Print to HTML
". Select that, and it is being installed.Alt+Shift+P
const:
readonly:
Johann-S solution works great. (And it looks like he created the awesome plugin)
The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input
Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.
$(document).ready(function () {
bsCustomFileInput.init()
})
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
The JSON array data type cannot have named keys on an array.
When you pass a JavaScript array to JSON.stringify
the named properties will be ignored.
If you want named properties, use an Object, not an Array.
const test = {}; // Object_x000D_
test.a = 'test';_x000D_
test.b = []; // Array_x000D_
test.b.push('item');_x000D_
test.b.push('item2');_x000D_
test.b.push('item3');_x000D_
test.b.item4 = "A value"; // Ignored by JSON.stringify_x000D_
const json = JSON.stringify(test);_x000D_
console.log(json);
_x000D_
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
You should remove "style" attribute instead of "display" property :
$("span").removeAttr("style");
You have to look how this is called:
someObject.equals(someOtherObj);
This invokes the equals
method on the instance of someObject
. Now, inside that method:
public boolean equals(Object obj) { if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj? return true;//If so, these are the same objects, and return true }
You can see that this
is referring to the instance of the object that equals is called on. Note that equals()
is non-static, and so must be called only on objects that have been instantiated.
Note that ==
is only checking to see if there is referential equality; that is, the reference of this
and obj
are pointing to the same place in memory. Such references are naturally equal:
Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place
Further note that equals()
is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:
FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing.
I write this custom function this will help you. But make discussions about the Time complexity.
std::vector<std::string> words;
std::string s;
std::string separator = ",";
while(s.find(separator) != std::string::npos){
separatorIndex = s.find(separator)
vtags.push_back(s.substr(0, separatorIndex ));
words= s.substr(separatorIndex + 1, s.length());
}
words.push_back(s);
This CSS will overwrite even the JavaScript:
#demofour li[style] {
display: inline !important;
}
or for only first one
#demofour li[style]:first-child {
display: inline !important;
}
When you fired command php artisan config:cache
then it will wipe out all the env
variables and env()
will give null values, try running following command and boom there your env()
again begin to catch all env
variable
php artisan config:clear
With Python's built-in library, it's pretty easy:
a = [2, 9, -10, 5, 18, 9]
max(xrange(len(a)), key = lambda x: a[x])
This tells max
to find the largest number in the list [0, 1, 2, ..., len(a)]
, using the custom function lambda x: a[x]
, which says that 0
is actually 2
, 1
is actually 9
, etc.