I had this logs in Windows. I did the following
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
To anybody who is facing this issue on MacOS machines, try this:
brew uninstall gpg
brew install gpg2
brew install pinentry-mac
(if needed)gpg --full-generate-key
Create a key by using an algorithm.gpg --list-keys
git config --global user.signingkey <Key from your list>
git config --global gpg.program /usr/local/bin/gpg
git config --global commit.gpgsign true
gpg --armor --export <key>
and add this key to GitHub at GPG keys: https://github.com/settings/keys (with START and END line included)If the issue still exists:
test -r ~/.bash_profile && echo 'export GPG_TTY=$(tty)' >> ~/.bash_profile
echo 'export GPG_TTY=$(tty)' >> ~/.profile
If the issue still exists:
Install https://gpgtools.org and sign the key that you used by pressing Sign from the menu bar: Key->Sign
If the issue still exists:
Go to: ??your global .gitconfig
file which in my case is at: ??/Users/gent/.gitconfig
And modify the .gitconfig file (please make sure Email and Name are the same with the one that you have created while generating the Key):
[user]_x000D_
email = [email protected]_x000D_
name = Gent_x000D_
signingkey = <YOURKEY>_x000D_
[gpg]_x000D_
program = /usr/local/bin/gpg_x000D_
[commit]_x000D_
gpsign = true_x000D_
gpgsign = true_x000D_
[filter "lfs"]_x000D_
process = git-lfs filter-process_x000D_
required = true_x000D_
clean = git-lfs clean -- %f_x000D_
smudge = git-lfs smudge -- %f_x000D_
[credential]_x000D_
helper = osxkeychain
_x000D_
It seems to work fine in Postgresql 9.5:
SELECT current_setting('TIMEZONE');
This is a bug in the npm package regarding dependencies : https://askubuntu.com/questions/1088662/npm-depends-node-gyp-0-10-9-but-it-is-not-going-to-be-installed
Bugs have been reported. The above may not work depending what you have installed already, at least it didn't for me on an up to date Ubuntu 18.04 LTS.
I followed the suggested dependencies and installed them as the above link suggests:
sudo apt-get install nodejs-dev node-gyp libssl1.0-dev
and then
sudo apt-get install npm
Please subscribe to the bug if you're affected:
bugs.launchpad.net/ubuntu/+source/npm/+bug/1517491
bugs.launchpad.net/ubuntu/+source/npm/+bug/1809828
You can use font face like this:
@font-face {
font-family:"Name-Of-Font";
src: url("yourfont.ttf") format("truetype");
}
AND
between ORDER BY
and LIMIT
=
between ORDER BY
, LIMIT
keywords and conditionSo you query will look like:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.
Try this before searching for the elements within the iframe:
driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));
Places is a list and not a dictionary. This line below should therefore not work:
print data['places']['latitude']
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print data['places'][0]['post code']
Alright, this doesn't apply to the OP's exact situation, but for anyone like myself who comes here facing a similar issue, figure I should throw this out there-- maybe save a headache or two.
If you're using an non-standard "button" to ensure the submit
event isn't called:
<form>
<input type="hidden" name="hide" value="1">
<a href="#" onclick="submitWithChecked(this.form)">Hide Selected</a>
</form>
Then, when you try to access this.form
in the script, it's going to come up undefined. As I discovered, apparently anchor elements don't have same access to a parent form
element the way your standard form elements do.
In such cases, (again, assuming you are intentionally avoiding the submit
event for the time-being), you can use a button
with type="button"
<form>
<input type="hidden" name="hide" value="1">
<button type="button" onclick="submitWithChecked(this.form)">Hide Selected</a>
</form>
(Addendum 2020: All these years later, I think the more important lesson to take away from this is to check your input. If my function had bothered to check that the argument it received was actually a form element, the problem would have been much easier to catch.)
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
This worked for me (not using proxy):
set registry mirror for npm..
npm config set registry http://skimdb.npmjs.com/registry
found mirror from docs:https://docs.npmjs.com/misc/registry
3.npm install -g handlebar //i did because it was showing error in npm log but you can skip
4.after that try to set again official registry
npm config set registry http://registry.npmjs.org
5.now try to install whatever package you want :-)
I'm using
Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"
to format a column
So I guess
Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"
would do the trick for you.
More: NumberFormat function.
I use brew and the prefix was already set to be:
$ npm config get prefix
/Users/[user]/.node
I did notice that the bin and lib folder were owned by root, which prevented the usual non sudo install, so I re-owned them to the user
$ cd /Users/[user]/.node
$ chown -R [user]:[group] lib
$ chown -R [user]:[group] bin
Then I just added the path to my .bash_profile which is located at /Users/[user]
PATH=$PATH:~/.node/bin
It's usually describes as for optional add-on software packages
source, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local
.
Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.
DataGridView1.Columns[0].Width=100;// The id column
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining
//space
As per the documentation, most browsers will display the <ul>
, <ol>
and <li>
elements with the following default values:
Default CSS settings for UL or OL tag:
ul, ol {
display: block;
list-style: disc outside none;
margin: 1em 0;
padding: 0 0 0 40px;
}
ol {
list-style-type: decimal;
}
Default CSS settings for LI tag:
li {
display: list-item;
}
Style nested list items as well:
ul ul, ol ul {
list-style-type: circle;
margin-left: 15px;
}
ol ol, ul ol {
list-style-type: lower-latin;
margin-left: 15px;
}
Note: The result will be perfect if we use the above styles with a class. Also see different List-Item markers.
There is one more way to run grunt on windows, without adding anything globally. This is a case when you don't have to do anything with %PATH%
if you have grunt and grunt-cli installed (without -g switch). Either by:
npm install grunt-cli
npm install [email protected]
Or by having that in your packages.json file like:
"devDependencies": {
"grunt-cli": "^1.2.0",
"grunt": "^0.4.5",
You can call grunt from your local installation by:
node node_modules\grunt-cli\bin\grunt --version
This is a solution for those who for some reasons don't want to or can't play with PATH, or have something else messing it all the time, for instance on a build agent.
Edit: Added versions as the grunt-cli works with grunt > 0.3
I had same problem as yours, but my concern was list view. When i try to scroll list view fixed header also scroll little bit. Problem was list view height smaller than viewport (browser) height. You just need to reduce your viewport height lower than content tag (list view within content tag) height. Here is my meta tag;
<meta name="viewport" content="width=device-width,height=90%, user-scalable = no">
Hope this will help.Thnks.
I ran into the same situation where when I copied the formula to another cell the formula was still referencing the cell used in the first formula. To correct this when you set up the rules, select the option "use a formula to determine which cells to format. Then type in the box your formula, for example H23*.25. When you copy the cells down the formulas will change to H24*.25, H25*.25 and so on. Hope this helps.
This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.
This is for the following query:
data = Leaderboard.objects.filter(id=custom_user.id).values(
'value1',
'value2',
'value3')
In template:
{% for dictionary in data %}
{% for key, value in dictionary.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
{% endfor %}
Authentication
is a process of verification:
digital signature
[About]Authorization
is the next step after Authentication
. It is about permissions/roles/privileges to resources. OAuth
(Open Authorization) is an example of Authorization
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3)
+ "-"
+ Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.
Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.
This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..
Ex:
Table 1
DiffKey Other Val
1 X
1 Y
1 Z
Table 3
DiffKey Key Key2 Tbl3 Other
1 2 6 V
1 2 6 X
1 2 6 Y
1 2 6 Z
Table 2
Key Key2 Other Val
2 6 a
2 6 b
2 6 c
2 6 d
2 6 e
So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.
So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.
SELECT
COUNT(*)
FROM
Table1
INNER JOIN Table3
ON Table1.DifferentKey = Table3.DifferentKey
INNER JOIN Table2
ON Table3.Key =Table2.Key
AND Table3.Key2 = Table2.Key2
You could write a function template back
that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:
template <typename C>
typename C::reference back(C& container)
{
return container.back();
}
template <typename C>
typename C::const_reference back(const C& container)
{
return container.back();
}
char& back(std::string& str)
{
return *(str.end() - 1);
}
char back(const std::string& str)
{
return *(str.end() - 1);
}
Then you can just say back(foo)
without worrying whether foo
is a string or a vector.
I had to read subtitles files and split them into sentences. After pre-processing (like removing time information etc in the .srt files), the variable fullFile contained the full text of the subtitle file. The below crude way neatly split them into sentences. Probably I was lucky that the sentences always ended (correctly) with a space. Try this first and if it has any exceptions, add more checks and balances.
# Very approximate way to split the text into sentences - Break after ? . and !
fullFile = re.sub("(\!|\?|\.) ","\\1<BRK>",fullFile)
sentences = fullFile.split("<BRK>");
sentFile = open("./sentences.out", "w+");
for line in sentences:
sentFile.write (line);
sentFile.write ("\n");
sentFile.close;
Oh! well. I now realize that since my content was Spanish, I did not have the issues of dealing with "Mr. Smith" etc. Still, if someone wants a quick and dirty parser...
import json
d = json.loads(j)
print d['glossary']['title']
If you don't want to import the calendar library, and need something that is a bit more robust -- you can make your code a little bit more dynamic to inconsistent text input than some of the other solutions provided. You can:
month_to_number
dictionary.items()
of that dictionary and check if the lowercase of a string s
is in a lowercase key k
.month_to_number = {
'January' : 1,
'February' : 2,
'March' : 3,
'April' : 4,
'May' : 5,
'June' : 6,
'July' : 7,
'August' : 8,
'September' : 9,
'October' : 10,
'November' : 11,
'December' : 12}
s = 'jun'
[v for k, v in month_to_number.items() if s.lower() in k.lower()][0]
Out[1]: 6
Likewise, if you have a list l
instead of a string, you can add another for
to loop through the list. The list I have created has inconsistent values, but the output is still what would be desired for the correct month number:
l = ['January', 'february', 'mar', 'Apr', 'MAY', 'JUne', 'july']
[v for k, v in month_to_number.items() for m in l if m.lower() in k.lower()]
Out[2]: [1, 2, 3, 4, 5, 6, 7]
The use case for me here is that I am using Selenium
to scrape data from a website by automatically selecting a dropdown value based off of some conditions. Anyway, this requires me relying on some data that I believe our vendor is manually entering to title each month, and I don't want to come back to my code if they format something slightly differently than they have done historically.
If you don't need to support IE7, the following is a great, concise hack:
JSON.parse(JSON.stringify(new Date()))
Use LocalDate
from java.time, the modern Java date and time API, for a date
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
System.out.println(date);
Output:
2007-06-27
As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate
is a date without time of day, so a lot better suitable for the date from your string than the old Date
class. Despite its name a Date
does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.
Only if you need an old-fashioned Date
for an API that you cannot afford to upgrade to java.time just now, convert like this:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(startOfDay);
System.out.println(oldfashionedDate);
Output in my time zone:
Wed Jun 27 00:00:00 CEST 2007
Oracle tutorial: Date Time explaining how to use java.time.
$timezone = array(
'Pacific/Midway' => '(GMT-11:00) Midway Island, Samoa',
'America/Adak' => '(GMT-10:00) Hawaii-Aleutian',
'Etc/GMT+10' => '(GMT-10:00) Hawaii',
'Pacific/Marquesas' => '(GMT-09:30) Marquesas Islands',
'Pacific/Gambier' => '(GMT-09:00) Gambier Islands',
'America/Anchorage' => '(GMT-09:00) Alaska',
'America/Ensenada' => '(GMT-08:00) Tijuana, Baja California',
'Etc/GMT+8' => '(GMT-08:00) Pitcairn Islands',
'America/Los_Angeles' => '(GMT-08:00) Pacific Time (US & Canada)',
'America/Denver' => '(GMT-07:00) Mountain Time (US & Canada)',
'America/Chihuahua' => '(GMT-07:00) Chihuahua, La Paz, Mazatlan',
'America/Dawson_Creek' => '(GMT-07:00) Arizona',
'America/Belize' => '(GMT-06:00) Saskatchewan, Central America',
'America/Cancun' => '(GMT-06:00) Guadalajara, Mexico City, Monterrey',
'Chile/EasterIsland' => '(GMT-06:00) Easter Island',
'America/Chicago' => '(GMT-06:00) Central Time (US & Canada)',
'America/New_York' => '(GMT-05:00) Eastern Time (US & Canada)',
'America/Havana' => '(GMT-05:00) Cuba',
'America/Bogota' => '(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
'America/Caracas' => '(GMT-04:30) Caracas',
'America/Santiago' => '(GMT-04:00) Santiago',
'America/La_Paz' => '(GMT-04:00) La Paz',
'Atlantic/Stanley' => '(GMT-04:00) Faukland Islands',
'America/Campo_Grande' => '(GMT-04:00) Brazil',
'America/Goose_Bay' => '(GMT-04:00) Atlantic Time (Goose Bay)',
'America/Glace_Bay' => '(GMT-04:00) Atlantic Time (Canada)',
'America/St_Johns' => '(GMT-03:30) Newfoundland',
'America/Araguaina' => '(GMT-03:00) UTC-3',
'America/Montevideo' => '(GMT-03:00) Montevideo',
'America/Miquelon' => '(GMT-03:00) Miquelon, St. Pierre',
'America/Godthab' => '(GMT-03:00) Greenland',
'America/Argentina/Buenos_Aires' => '(GMT-03:00) Buenos Aires',
'America/Sao_Paulo' => '(GMT-03:00) Brasilia',
'America/Noronha' => '(GMT-02:00) Mid-Atlantic',
'Atlantic/Cape_Verde' => '(GMT-01:00) Cape Verde Is.',
'Atlantic/Azores' => '(GMT-01:00) Azores',
'Europe/Belfast' => '(GMT) Greenwich Mean Time : Belfast',
'Europe/Dublin' => '(GMT) Greenwich Mean Time : Dublin',
'Europe/Lisbon' => '(GMT) Greenwich Mean Time : Lisbon',
'Europe/London' => '(GMT) Greenwich Mean Time : London',
'Africa/Abidjan' => '(GMT) Monrovia, Reykjavik',
'Europe/Amsterdam' => '(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
'Europe/Belgrade' => '(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
'Europe/Brussels' => '(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
'Africa/Algiers' => '(GMT+01:00) West Central Africa',
'Africa/Windhoek' => '(GMT+01:00) Windhoek',
'Asia/Beirut' => '(GMT+02:00) Beirut',
'Africa/Cairo' => '(GMT+02:00) Cairo',
'Asia/Gaza' => '(GMT+02:00) Gaza',
'Africa/Blantyre' => '(GMT+02:00) Harare, Pretoria',
'Asia/Jerusalem' => '(GMT+02:00) Jerusalem',
'Europe/Minsk' => '(GMT+02:00) Minsk',
'Asia/Damascus' => '(GMT+02:00) Syria',
'Europe/Moscow' => '(GMT+03:00) Moscow, St. Petersburg, Volgograd',
'Africa/Addis_Ababa' => '(GMT+03:00) Nairobi',
'Asia/Tehran' => '(GMT+03:30) Tehran',
'Asia/Dubai' => '(GMT+04:00) Abu Dhabi, Muscat',
'Asia/Yerevan' => '(GMT+04:00) Yerevan',
'Asia/Kabul' => '(GMT+04:30) Kabul',
'Asia/Yekaterinburg' => '(GMT+05:00) Ekaterinburg',
'Asia/Tashkent' => '(GMT+05:00) Tashkent',
'Asia/Kolkata' => '(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
'Asia/Katmandu' => '(GMT+05:45) Kathmandu',
'Asia/Dhaka' => '(GMT+06:00) Astana, Dhaka',
'Asia/Novosibirsk' => '(GMT+06:00) Novosibirsk',
'Asia/Rangoon' => '(GMT+06:30) Yangon (Rangoon)',
'Asia/Bangkok' => '(GMT+07:00) Bangkok, Hanoi, Jakarta',
'Asia/Krasnoyarsk' => '(GMT+07:00) Krasnoyarsk',
'Asia/Hong_Kong' => '(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
'Asia/Irkutsk' => '(GMT+08:00) Irkutsk, Ulaan Bataar',
'Australia/Perth' => '(GMT+08:00) Perth',
'Australia/Eucla' => '(GMT+08:45) Eucla',
'Asia/Tokyo' => '(GMT+09:00) Osaka, Sapporo, Tokyo',
'Asia/Seoul' => '(GMT+09:00) Seoul',
'Asia/Yakutsk' => '(GMT+09:00) Yakutsk',
'Australia/Adelaide' => '(GMT+09:30) Adelaide',
'Australia/Darwin' => '(GMT+09:30) Darwin',
'Australia/Brisbane' => '(GMT+10:00) Brisbane',
'Australia/Hobart' => '(GMT+10:00) Hobart',
'Asia/Vladivostok' => '(GMT+10:00) Vladivostok',
'Australia/Lord_Howe' => '(GMT+10:30) Lord Howe Island',
'Etc/GMT-11' => '(GMT+11:00) Solomon Is., New Caledonia',
'Asia/Magadan' => '(GMT+11:00) Magadan',
'Pacific/Norfolk' => '(GMT+11:30) Norfolk Island',
'Asia/Anadyr' => '(GMT+12:00) Anadyr, Kamchatka',
'Pacific/Auckland' => '(GMT+12:00) Auckland, Wellington',
'Etc/GMT-12' => '(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
'Pacific/Chatham' => '(GMT+12:45) Chatham Islands',
'Pacific/Tongatapu' => '(GMT+13:00) Nukualofa',
'Pacific/Kiritimati' => '(GMT+14:00) Kiritimati',
date_default_timezone_set($timezone);
This is typically done using an edit distance measure. Searching for "edit distance java" turns up a number of libraries, like this one.
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
using Log to solve the problem....
static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}
Also in c#, but should be a snap to convert. Also I rounded to 1 decimal place for readability.
Basically Determine the number of decimal places in Base 1024 and then divide by 1024^decimalplaces.
And some samples of use and output:
Console.WriteLine(BytesToString(9223372036854775807)); //Results in 8EB
Console.WriteLine(BytesToString(0)); //Results in 0B
Console.WriteLine(BytesToString(1024)); //Results in 1KB
Console.WriteLine(BytesToString(2000000)); //Results in 1.9MB
Console.WriteLine(BytesToString(-9023372036854775807)); //Results in -7.8EB
Edit: Was pointed out that I missed a math.floor, so I incorporated it. (Convert.ToInt32 uses rounding, not truncating and that's why Floor is necessary.) Thanks for the catch.
Edit2: There were a couple of comments about negative sizes and 0 byte sizes, so I updated to handle those 2 cases.
The printf
command will print the complete strings:
(gdb) printf "%s\n", string
I don't know HOW FEASIBLE this would be, but I haven't seen this mentioned so I thought I would go ahead and suggest this:
If you are strictly in the US... get a huge database of all zip codes, states, cities and streets. Now look for these in your addresses. You can validate what you find by testing if, say, the city you found exists in the state you found, or by checking if the street you found exists in the city you found. If not, chances are John isn't for John's street, but is the name of the addressee... Basically, get the most information you can and check your addresses against it. An extreme example would be to get A LIST OF ALL THE ADDRESSES IN THE US OF A and then find which one has the most relevant match to each of your addresses...
Use a docstring, as others have already written.
You can even go one step further and add a doctest to your docstring, making automated testing of your functions a snap.
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
Use the Chart Wizard.
On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.
Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.
Select your new series.
There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.
Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.
Hope that helps.
EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
Docker Compose does not support the deploy
key. It's only respected when you use your version 3 YAML file in a Docker Stack.
This message is printed when you add the deploy
key to you docker-compose.yml
file and then run docker-compose up -d
WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use
docker stack deploy
to deploy to a swarm.
The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.
I had this issue caused by a sort of overlap of a div
element with a bootstrap class ="row"
over a "brother" div
element with the class="col"
, the first hid the focus of the second div
element.
I solved taking outer the div row
element from that level of the divs' tree and so rebalancing bootstrap logical hierarchy based on the row
and col
classes.
Here is another alternative. It will of course give you a bad result if the input char is not ascii. I've not perf tested it but I think it would be pretty fast:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(string s, int index) {
return GetAsciiVal(s[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetAsciiVal(char c) {
return unchecked(c & 0xFF);
}
While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:
ng-click="hidePrefs()"
and then in your controller:
$scope.hidePrefs = function() {
$scope.prefs = false;
}
Personally, I just use Cygwin. Which allows you to use many common *nix commands in Windows. SSH being one of them.
That's a simple one
UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);
I know this is a fairly old question, but I ran into the same problem today and wasn't too interested in referencing all of MVVMLight just so I can use event triggers with event args. I have used MVVMLight in the past and it's a great framework, but I just don't want to use it for my projects any more.
What I did to resolve this problem was create an ULTRA minimal, EXTREMELY adaptable custom trigger action that would allow me to bind to the command and provide an event args converter to pass on the args to the command's CanExecute and Execute functions. You don't want to pass the event args verbatim, as that would result in view layer types being sent to the view model layer (which should never happen in MVVM).
Here is the EventCommandExecuter class I came up with:
public class EventCommandExecuter : TriggerAction<DependencyObject>
{
#region Constructors
public EventCommandExecuter()
: this(CultureInfo.CurrentCulture)
{
}
public EventCommandExecuter(CultureInfo culture)
{
Culture = culture;
}
#endregion
#region Properties
#region Command
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
#region EventArgsConverterParameter
public object EventArgsConverterParameter
{
get { return (object)GetValue(EventArgsConverterParameterProperty); }
set { SetValue(EventArgsConverterParameterProperty, value); }
}
public static readonly DependencyProperty EventArgsConverterParameterProperty =
DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
public IValueConverter EventArgsConverter { get; set; }
public CultureInfo Culture { get; set; }
#endregion
protected override void Invoke(object parameter)
{
var cmd = Command;
if (cmd != null)
{
var param = parameter;
if (EventArgsConverter != null)
{
param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
}
if (cmd.CanExecute(param))
{
cmd.Execute(param);
}
}
}
}
This class has two dependency properties, one to allow binding to your view model's command, the other allows you to bind the source of the event if you need it during event args conversion. You can also provide culture settings if you need to (they default to the current UI culture).
This class allows you to adapt the event args so that they may be consumed by your view model's command logic. However, if you want to just pass the event args on verbatim, simply don't specify an event args converter.
The simplest usage of this trigger action in XAML is as follows:
<i:Interaction.Triggers>
<i:EventTrigger EventName="NameChanged">
<cmd:EventCommandExecuter Command="{Binding Path=Update, Mode=OneTime}" EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
If you needed access to the source of the event, you would bind to the owner of the event
<i:Interaction.Triggers>
<i:EventTrigger EventName="NameChanged">
<cmd:EventCommandExecuter
Command="{Binding Path=Update, Mode=OneTime}"
EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"
EventArgsConverterParameter="{Binding ElementName=SomeEventSource, Mode=OneTime}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
(this assumes that the XAML node you're attaching the triggers to has been assigned x:Name="SomeEventSource"
This XAML relies on importing some required namespaces
xmlns:cmd="clr-namespace:MyProject.WPF.Commands"
xmlns:c="clr-namespace:MyProject.WPF.Converters"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
and creating an IValueConverter
(called NameChangedArgsToStringConverter
in this case) to handle the actual conversion logic. For basic converters I usually create a default static readonly
converter instance, which I can then reference directly in XAML as I have done above.
The benefit of this solution is that you really only need to add a single class to any project to use the interaction framework much the same way that you would use it with InvokeCommandAction
. Adding a single class (of about 75 lines) should be much more preferable to an entire library to accomplish identical results.
this is somewhat similar to the answer from @adabyron but it uses event triggers instead of behaviours. This solution also provides an event args conversion ability, not that @adabyron's solution could not do this as well. I really don't have any good reason why I prefer triggers to behaviours, just a personal choice. IMO either strategy is a reasonable choice.
There is a c++ class called _bstr_t
. It has useful methods and a collection of overloaded operators.
For example, you can easily assign from a const wchar_t *
or a const char *
just doing _bstr_t bstr = L"My string";
Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();
. You can even convert it back to a regular char const char * c = bstr.operator char *();
You can then just use the const wchar_t *
or the const char *
to initialize a new std::wstring
oe std::string
.
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
Try this ...
public class Solution {
public static void main(String[] args) {
long t = 1000;
long sum = 0;
for(int i = 1; i<t; i++){
if(i%3 == 0 || i%5 == 0){
sum = sum + i;
}
}
System.out.println(sum);
}
}
This is generic code for configuration collection :
public class GenericConfigurationElementCollection<T> : ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
{
List<T> _elements = new List<T>();
protected override ConfigurationElement CreateNewElement()
{
T newElement = new T();
_elements.Add(newElement);
return newElement;
}
protected override object GetElementKey(ConfigurationElement element)
{
return _elements.Find(e => e.Equals(element));
}
public new IEnumerator<T> GetEnumerator()
{
return _elements.GetEnumerator();
}
}
After you have GenericConfigurationElementCollection
,
you can simple use it in the config section (this is an example from my Dispatcher):
public class DispatcherConfigurationSection: ConfigurationSection
{
[ConfigurationProperty("maxRetry", IsRequired = false, DefaultValue = 5)]
public int MaxRetry
{
get
{
return (int)this["maxRetry"];
}
set
{
this["maxRetry"] = value;
}
}
[ConfigurationProperty("eventsDispatches", IsRequired = true)]
[ConfigurationCollection(typeof(EventsDispatchConfigurationElement), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
public GenericConfigurationElementCollection<EventsDispatchConfigurationElement> EventsDispatches
{
get { return (GenericConfigurationElementCollection<EventsDispatchConfigurationElement>)this["eventsDispatches"]; }
}
}
The Config Element is config Here:
public class EventsDispatchConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string) this["name"];
}
set
{
this["name"] = value;
}
}
}
The config file would look like this:
<?xml version="1.0" encoding="utf-8" ?>
<dispatcherConfigurationSection>
<eventsDispatches>
<add name="Log" ></add>
<add name="Notification" ></add>
<add name="tester" ></add>
</eventsDispatches>
</dispatcherConfigurationSection>
Hope it help !
This answer is for beginners (none-git gurus). I recently had this problem and maybe its just me but most of the answers seemed to require rather advance understanding of git. After reading several stack overflow answers including this thread, here are the steps I needed to take in order to easily switch between GitHub accounts (e.g. assume two GitHub accounts, github.com/personal and gitHub.com/work):
ls -al ~/.ssh
.pub
are your ssh keys so you should have two for the personal
and work
accounts. If there is only one or none, its time to generate other wise skip this.ssh-keygen -t rsa -C "the copied email"
, you'll see:/.../.ssh/id_rsa_work
if generating for work account. provide a password or just enter to ignore and, you'll read something like The key's randomart image is: and the image. done.ls -al ~/.ssh
again.pbcopy < ~/.ssh/id_rsa_work.pub
, replace id_rsa_work.pub
with what you called yours.id_rsa_work
] and navigate toEdit the global git configuration: Last step is to make sure the global configuration file is aware of all github accounts (so to say).
Run git config --global --edit
to edit this global file, if this opens vim and you don't know how to use it, press i
to enter Insert mode, edit the file as below, and press esc followed by :wq
to exit insert mode:
[inside this square brackets give a name to the followed acc.]
name = github_username
email = github_emailaddress
[any other name]
name = github_username
email = github_email
[credential]
helper = osxkeychain
useHttpPath = true
Done!, now when trying to push or pull from a repo, you'll be asked which GitHub account should be linked with this repo and its asked only once, the local configuration will remember this link and not the global configuration so you can work on different repos that are linked with different accounts without having to edit global configuration each time.
This should do the job:
const createQueryParams = params =>
Object.keys(params)
.map(k => `${k}=${encodeURI(params[k])}`)
.join('&');
Example:
const params = { name : 'John', postcode: 'W1 2DL'}
const queryParams = createQueryParams(params)
Result:
name=John&postcode=W1%202DL
.overlay
didn't have a height or width and no content, and you can't hover over display:none
.
I instead gave the div the same size and position as .image
and changes RGBA
value on hover.
http://jsfiddle.net/Zf5am/566/
.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }
I'm not sure about you, but I spent about 30 minutes troubleshooting the same issue here, until I realized that the line for app/build.gradle is:
apply plugin: 'com.google.gms.google-services'
and not:
apply plugin: 'com.google.gms:google-services'
Eg: I had copied that line from a tutorial, but when specifying the apply plugin namespace, no colon (:
) is required. It's, in fact, a dot. (.
).
Hey... it's easy to miss.
in my case the error was it was not able to find servlet-api.jar. Don't know why suddenly it started giving error for that. Because previously it was running without any issue. After giving the servlet-api.jar in the build path option the server started successfully.
Sounds like ehcache is overkill for what you want, however note that it does not need external configuration files.
It is generally a good idea to move configuration into a declarative configuration files ( so you don't need to recompile when a new installation requires a different expiry time ), but it is not at all required, you can still configure it programmatically. http://www.ehcache.org/documentation/user-guide/configuration
For integer values represented by a double
, you can use this code, which is much faster than the other solutions.
public static String doubleToString(final double d) {
// check for integer, also see https://stackoverflow.com/a/9898613/868941 and
// https://github.com/google/guava/blob/master/guava/src/com/google/common/math/DoubleMath.java
if (isMathematicalInteger(d)) {
return Long.toString((long)d);
} else {
// or use any of the solutions provided by others, this is the best
DecimalFormat df =
new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); // 340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
return df.format(d);
}
}
// Java 8+
public static boolean isMathematicalInteger(final double d) {
return StrictMath.rint(d) == d && Double.isFinite(d);
}
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
@restartable
def main():
print "foo"
main()
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y'
and keep running the code until the answer isn't 'y'
.
You could also provide a link to the page after login and have it auto redirect using javascript after 10 seconds.
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
in a case of Elliptic Curve and answer the question import an existing x509 certificate and private key in Java keystore, you may want to have a look also to this thread How to read EC Private key in java which is in .pem file format
You can ignore a file or directory like .gitignore. Just create a text file of list of directories/files you want to ignore and run the code below:
svn propset svn:ignore -F ignorelist.txt .
OR if you don't want to use a text file, you can do it like this:
svn propset svn:ignore "first
second
third" .
Source: Karsten's Blog - Set svn:ignore for multiple files from command line
You should install PDO on your server.
Edit your php.ini (look at your phpinfo()
, "Loaded Configuration File" line, to find the php.ini file path).
Find and uncomment the following line (remove the ;
character):
;extension=pdo_mysql.so
Then, restart your Apache server. For more information, please read the documentation.
read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)
This technique uses Bash's "process substitution" not to be confused with "command substitution".
Here are a few good references:
Your string is not valid JSON, so JSON.parse
(or jQuery's $.parseJSON
) won't work.
One way would be to use eval
to "parse" the "invalid" JSON, and then stringify
it to "convert" it to valid JSON.
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));
I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str
being generated, it should be fixed there, before it's generated, not after.
EDIT: You said (in the comments) this string is stored in a data attribute:
<div data-object="{hello:'world'}"></div>
I suggest you fix it here, so it can just be JSON.parse
d. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):
<div data-object='{"hello":"world"}'></div>
Now, you can just use JSON.parse
(or jQuery's $.parseJSON
).
var str = '{"hello":"world"}';
var obj = JSON.parse(str);
I've often done:
function doSomething(variable)
{
var undef;
if(variable === undef)
{
alert('Hey moron, define this bad boy.');
}
}
I find using these interactive tools help visualize what's happening, and whats possible
http://css3gen.com/box-shadow/
http://www.cssmatic.com/box-shadow
Edit: Check out the other tools for experimenting with the other generators and combinations. I have to remind myself sometimes that just because you can, doesn't mean you should - its easy to get carried away!
try this:
Sub test()
With Application.WorksheetFunction
Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With
End Sub
Hope this works for you.
If you truly wish to use PHP, you could use
include "file.php";
or
require "file.php";
and then in file.php, use a heredoc & echo it in.
file.php contents:
$some_js_code <<<_code
function myFunction()
{
Alert("Some JS code would go here.");
}
_code;
At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in
<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>
Different way but it works. Just my $.02...
You need to create a new Font
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
In my case it worked at first and after a while stopped working and IIS Express reported that the port was in use.
netstat -ab
showed that Chrome was using the port. After I quit Chrome, it started working again.
I am not sure however, why Chrome would occupy that port.
For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.
Note this are complete cross-browser working, valid HTML files. Just change title
and src
for your needs.
1. this is my favorite:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>
<!-- More verbose CSS for better understanding:
html { height:100% }
body { height:100%; margin:0 }
iframe { height:100%; width:100%; border:0; display:block }
-->
or 2. something like that, slightly shorter:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>
Note:
The above examples avoid using height:100vh
because old browsers don't know it (maybe moot these days) and height:100vh
is not always equal to height:100%
on mobile browsers (probably not applicable here). Otherwise, vh
simplifies things a little bit, so
3. this is an example using vh (not my favorite, less compatible with little advantage)
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
body { margin:0 }
iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>
The guy above gave comparison for HashMap / HashSet vs. TreeMap / TreeSet.
I will talk about ArrayList vs. LinkedList:
ArrayList:
get()
add()
ListIterator.add()
or Iterator.remove()
, it will be O(n) to shift all the following elements LinkedList:
get()
add()
ListIterator.add()
or Iterator.remove()
, it will be O(1)This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex
magic that makes the whole cell Latex without the $$
wrapper for each line.
Refer notebook tour for Rich Display System
Both are similar in functionality because they both return type information, however I personally prefer instanceof
because it's comparing actual types rather than strings. Type comparison is less prone to human error, and it's technically faster since it's comparing pointers in memory rather than doing whole string comparisons.
In the following link you can find useful info about recording with AVAudioRecording. In this link in the first part "USing Audio" there is an anchor named “Recording with the AVAudioRecorder Class.” that leads you to the example.
Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)
bag2set () {
# Reduce a_bag to a_set.
local -i i j n=${#a_bag[@]}
for ((i=0; i < n; i++)); do
if [[ -n ${a_bag[i]} ]]; then
a_set[i]=${a_bag[i]}
a_bag[i]=$'\0'
for ((j=i+1; j < n; j++)); do
[[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
done
fi
done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
a_bag[i]=$e
i=$i+1
done
bag2set
echo "${a_set[@]}"
I recommend you to use CodeCompare tool. It supports native highlighting of XML-data and it can be a good solution for your task.
Addition to third answer: If you're using non-english Windows, you can find "Credentials Manager" through "Control panel" > "User Accounts" > "Credentials Manager" Icon of Credentials Manager
Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.
$monthly_index = @array_shift(unpack('H*', date('m/Y')));
It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.
As result, I am sure your friend 'system administrator' will be pleased with a less polluted error.log
.
Try changing
git checkout -- a
to
git checkout -- `git ls-files -m -- a`
Since version 1.7.0, Git's ls-files
honors the skip-worktree flag.
Running your test script (with some minor tweaks changing git commit
... to git commit -q
and git status
to git status --short
) outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba
Running your test script with the proposed checkout
change outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/b/ab
b/a/ba
when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?
wrap it in
if (window.myTimeout) {
clearTimeout(myTimeout);
myTimeout = setTimeout("timerDone()", 1000 * 1440);
}
edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(..
and this is a matter of variable scope. If so, try this:
window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
window.message="Logged out";
}
function timerReset()
{
clearTimeout(window.myTimeout);
window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}
To color each cell based on its current integer value, the following should work, if you have a recent version of Excel. (Older versions don't handle rgb as well)
Sub Colourise()
'
' Colourise Macro
'
' Colours all selected cells, based on their current integer rgb value
' For e.g. (it's a bit backward from what you might expect)
' 255 = #ff0000 = red
' 256*255 = #00ff00 = green
' 256*256*255 #0000ff = blue
' 255 + 256*256*255 #ff00ff = magenta
' and so on...
'
' Keyboard Shortcut: Ctrl+Shift+C (or whatever you want to set it to)
'
For Each cell In Selection
If WorksheetFunction.IsNumber(cell) Then
cell.Interior.Color = cell.Value
End If
Next cell
End Sub
If instead of a number you have a string then you can split the string into three numbers and combine them using rgb().
try this command in terminal:
sudo ufw enable
ufw allow 12397
very simple
$('#label-ID').text("label value which you want to set");
The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?
Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.
If you set the loading factor to say 1.0 then something very interesting might happen.
Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.
Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.
Correct me if i am wrong somewhere.
I had the same problem and my solution was simple: instead of
Encoding.ASCII
use
Encoding.GetEncoding("iso-8859-1")
The answer was found here.
Edit: more solutions. This maybe more accurate one:
Encoding.GetEncoding(1252);
Also, in some cases this will work for you too if your OS default encoding matches file encoding:
Encoding.Default;
Solution 1 : Re-start SQL services and try to restore DB Solution 2 : Re-start system / server and try to restore DB Solution 3 : Take back of current DB, Delete the current/destination DB and try to restore DB.
Here is the solution which worked very fine for me, if it can help :
/**
* Add the equals method to the jquery objects
*/
$.fn.equals = function(compareTo) {
if (!compareTo || this.length !== compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
/**
* Activate popover message for all concerned fields
*/
var popoverOpened = null;
$(function() {
$('span.btn').popover();
$('span.btn').unbind("click");
$('span.btn').bind("click", function(e) {
e.stopPropagation();
if($(this).equals(popoverOpened)) return;
if(popoverOpened !== null) {
popoverOpened.popover("hide");
}
$(this).popover('show');
popoverOpened = $(this);
e.preventDefault();
});
$(document).click(function(e) {
if(popoverOpened !== null) {
popoverOpened.popover("hide");
popoverOpened = null;
}
});
});
I have used this in a TryDeleteDirectory function. It was something like this
do
{
try
{
DisableReadOnly(directory);
directory.Delete(true);
}
catch (Exception)
{
retryDeleteDirectoryCount++;
}
} while (Directory.Exists(fullPath) && retryDeleteDirectoryCount < 4);
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
You can do effectively from Eclipse IDE
. Of course if you are using it.
Project_Name->Maven->Update Project Configuration->Force Update of Snapshots/Releases
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
Just to complete JJC answer, in python 3.5.3 the behavior is correct if you use hashlib this way:
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -V
Python 3.5.3
Running python -h
, I see a command line option:
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant doc.
this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
Refer Link: blogspot.in
This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:
import platform # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
# In my installations of Windows 7, it takes an inordinate amount of time to save
# graphs as .svg files, so on that platform I've disabled the call that does so.
# The first run of a script is still a little slow while everything is loaded in,
# but execution times of subsequent runs are improved immensely.
fig.savefig('figure_name.svg')
I posted some information on the Infragistics forums for designer widgets that may help you for this. You can view the post with the following link:
http://forums.infragistics.com/forums/p/52530/320151.aspx#320151
Note that the registry keys would be different for the different product and you may need to install on a 32 bit machine to see what keys you need.
Css classes are here
<style type="text/css">
.mymenu
{
background-color: blue;
color: white;
}
.newmenu
{
background-color: red;
color: white;
}
</style>
Make your HTML like this, Set url as id
<div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
<div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>
Here write javascript, put this javascript after the HTML code.
function menuHighlight() {
var url = window.location.href;
$('#'+tabst).addClass('new_current');
}
menuHighlight();
To get an access token: facebook Graph API Explorer
You can customize specific access permissions, basic permissions are included by default.
If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js
> function doCheckbox(elem){
> .click(function(){
if ( $(elem+':checked').val() == 'check' ) {
$(elem).attr('checked','checked');
}
else {
$(elem).removeAttr('checked');
}
if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this
if ($(elem).is(':checked')) {
$(elem).attr('checked','checked');
}
else
{
$(elem).removeAttr('checked');
}
If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) {
function change
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
}
To
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
if (isChecked) {
$el.attr(c, c);
} else {
$el.removeAttr(c);
}
}
There's no need to redirect to a file and delete it later. Try:
Robocopy src dest > null
I had this error message:
Error: Can't open display: localhost:13.0
This fixed it for me:
export DISPLAY="localhost:10.0"
You can use this too:
export DISPLAY="127.0.0.1:10.0"
Here a solution using only std. However, note that this only rounds down.
float number = 3.14159;
std::string num_text = std::to_string(number);
std::string rounded = num_text.substr(0, num_text.find(".")+3);
For rounded
it yields:
3.14
The code converts the whole float to string, but cuts all characters 2 chars after the "."
IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment
Will do the job as Buttle Butkus suggested.
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
The package.json file is used by npm to learn about your node.js project.
Use npm init
to generate package.json files for you!
It comes bundled with npm. Read its documentation here: https://docs.npmjs.com/cli/init
Also, there's an official tool you can use to generate this file programmatically: https://github.com/npm/init-package-json
You are just updating the value of i
in the loop. The value of i
should also be added each time.
It is never a good idea to update the value of i
inside the for
loop. The for
loop index should only be used as a counter. In your case, changing the value of i
inside the loop will cause all sorts of confusion.
Create variable total
that holds the sum of the numbers up to i
.
So
for (int i = 0; i < positiveInteger; i++)
total += i;
You can simply compare 2 strings
function isLater(dateString1, dateString2) {
return dateString1 > dateString2
}
Then
isLater("2012-12-01", "2012-11-01")
returns true while
isLater("2012-12-01", "2013-11-01")
returns false
See the Android Color resource documentation for reference.
Basically you have the option to set the transparency (opacity) and the color either directly in the layout or using resources references.
The hex value that you set it to is composed of 3 to 4 parts:
Alpha (opacity), i'll refer to that as aa
Red, i'll refer to it as rr
Green, i'll refer to it as gg
Blue, i'll refer to it as bb
Without an alpha (transparency) value:
android:background="#rrggbb"
or as resource:
<color name="my_color">#rrggbb</color>
With an alpha (transparency) value:
android:background="#aarrggbb"
or as resource:
<color name="my_color">#aarrggbb</color>
The alpha value for full transparency is 00 and the alpha value for no transparency is FF.
See full range of hex values below:
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
You can experiment with values in between those.
For Android Studio 1.0.2:
First make sure Intel x86 emulator accelerator is installer. Check it in your SDK Manager. If not, then install it from there.
Go to your Android SDK folder, **{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager**
There you will find silent_install.bat.
Run it. It will create haxm_silent_run.log. After that, close and restart your Android Studio and then run your app.
It will work. In case of a problem, check the haxm_silent_run.log file.
You can enter the following formula in the cell where you want to see the Overdue
or Not due
result:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))
This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue
, otherwise it is set to Not due
.
Angular-CLI is the recommended method and is the standard in the Angular 2+ community.
Crete a new project with SCSS
ng new My-New-Project --style=sass
Convert an existing project (CLI less than v6)
ng set defaults.styleExt scss
(must rename all .css files manually with this approach, don't forget to rename in your component files)
Convert an existing project (CLI greater than v6)
"@schematics/angular:component": {
"styleext": "sass"
}
You can find some technical comparison on npmcompare
Comparing browserify vs. grunt vs. gulp vs. webpack
As you can see webpack is very well maintained with a new version coming out every 4 days on average. But Gulp seems to have the biggest community of them all (with over 20K stars on Github) Grunt seems a bit neglected (compared to the others)
So if need to choose one over the other i would go with Gulp
I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:
read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"
which yields:
2|4|6
as expected.
New class ViewPager2 from androidx allows to disable scrolling with method setUserInputEnabled(false)
private val pager: ViewPager2 by bindView(R.id.pager)
override fun onCreate(savedInstanceState: Bundle?) {
pager.isUserInputEnabled = false
}
If you are certain that the script runs in the first hours of the day, you can simply do
date -d "12 hours ago" '+%Y-%m-%d'
BTW, if the script runs daily at 00:35 (via crontab?) you should ask yourself what will happen if a DST change falls in that hour; the script could not run, or run twice in some cases. Modern implementations of cron
are quite clever in this regard, though.
think of operator as unary function: is_false(type value)
which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.
other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.
PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.
you can use this way
editText.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do some things
return true;
}
return false;
});
you can see list of action there.
For example:
IME_ACTION_GO
IME_ACTION_SEARCH
IME_ACTION_SEND
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
Using
calls Dispose()
after the using
-block is left, even if the code throws an exception.
So you usually use using
for classes that require cleaning up after them, like IO.
So, this using block:
using (MyClass mine = new MyClass())
{
mine.Action();
}
would do the same as:
MyClass mine = new MyClass();
try
{
mine.Action();
}
finally
{
if (mine != null)
mine.Dispose();
}
Using using
is way shorter and easier to read.
Here is a better script:
$('#mainimage').click(function(e)
{
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
alert("Left: " + left + " Top: " + top);
});
VAR=$(scan)
Exactly the same way as for programs.
There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.
The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.
To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.
As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.
One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.
The short answer
Use one of these two methods:
For example:
InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");
--
The long answer
Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:
File file = new File("C:\\Users\\Joe\\image.jpg");
This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.
Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).
Instead, use the getResource()
methods in the Class
class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.
The following is the right method
$(document).ready(function() {
$('#btnSun').click(function(){
$(this).myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});
So on a button click it will get string from edittext and store in listitem. you can change this to your needs.
With tensorflow version >3.2 you may use this command:
x1 = tf.Variable(5)
y1 = tf.Variable(3)
z1 = x1 + y1
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
init.run()
print(sess.run(z1))
The output: 8 will be displayed.
Syntax refers to the structure of a language, tracing its etymology to how things are put together.
For example you might require the code to be put together by declaring a type then a name and then a semicolon, to be syntactically correct.
Type token;
On the other hand, the semantics is about meaning. A compiler or interpreter could complain about syntax errors. Your co-workers will complain about semantics.
I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.
const jobs = [_x000D_
{_x000D_
name: "sipher",_x000D_
family: "sipherplus",_x000D_
job: "Devops"_x000D_
},_x000D_
{_x000D_
name: "john",_x000D_
family: "Doe",_x000D_
job: "Devops"_x000D_
},_x000D_
{_x000D_
name: "jim",_x000D_
family: "smith",_x000D_
job: "Devops"_x000D_
}_x000D_
];_x000D_
_x000D_
const txt = _x000D_
` <ul>_x000D_
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}_x000D_
</ul>`_x000D_
;_x000D_
_x000D_
document.body.innerHTML = txt;
_x000D_
Be careful about the back Ticks (`)
In windows, specified protocol for application can be registered in Registry. In this msdn doc shows Registering an Application to a URI Scheme.
For example, an executable files 'alert.exe' is to be started. The following item can be registered.
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe"
Then you can write a html to test
<head>
<title>alter</title>
</head>
<body>
<a href="alert:" >alert</a>
<body>
Please control if the the tmp directory property is pointing to a valid directory in core-site.xml
<property>
<name>hadoop.tmp.dir</name>
<value>/home/hduser/data/tmp</value>
</property>
If the directory is misconfigured, the datanode process will not start properly.
Add display:block;
to your iframe css.
div, iframe {
width: 100px;
height: 50px;
margin: 0 auto;
background-color: #777;
}
iframe {
display: block;
border-style:none;
}
_x000D_
<div>div</div>
<iframe src="data:,iframe"></iframe>
_x000D_
You can use method getDate():
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
function Time_Function() {
var date = new Date()
var time =""
var x= "AM"
if(date.getHours() >12){
x= "PM"
}
time= date.getHours()%12 + x +":"+ date.getMinutes() +":"+ date.getSeconds()
}
The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):
#include <iostream>
void Swap(const char * & left, const char * & right) {
const char *const temp = left;
left = right;
right = temp;
}
int main() {
const char * x = "Hello"; // These works because you are making a variable
const char * y = "World"; // pointer to a constant string
std::cout << "x = " << x << ", y = " << y << '\n';
Swap(x, y);
std::cout << "x = " << x << ", y = " << y << '\n';
}
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
This is what i found in a similar question's answer
Map<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
values.add("Value 1");
values.add("Value 2");
hm.put("Key1", values);
// to get the arraylist
System.out.println(hm.get("key1"));
RESULT: [Value 1, Value 2]
There is an official recommendation on storing additional information about users. The Django Book also discusses this problem in section Profiles.
Addition is much faster than rand
, so your program is (especially) useless.
You need to identify performance hotspots and incrementally modify your program. It sounds like you have problems with your development environment that will need to be solved first. Is it impossible to run your program on your PC for a small problem set?
Generally, attempting FP jobs with integer arithmetic is a recipe for slow.
To start the batch file at the start of your system, you can also use a registry key.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Here you can create a string. As name you can choose anything and the data is the full path to your file.
There is also the registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
to run something at only the next start of your system.
<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}
printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>
A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.
You already attempt to filter out NULL
values with NOT NULL
. I have changed this to IS NOT NULL
in the WHERE
clause so it will execute. We can refactor this by removing the ISNULL
function in the AVG
method. Also, I doubt you'll actually need bigint
so we can remove the cast.
SELECT distinct
AVG(a.SecurityW) as Average1
,AVG(a.TransferW) as Average2
,AVG(a.StaffW) as Average3
FROM Table1 a, Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013
Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.
This worked for me:
SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;
If you're open to using javascript then you can get the property on an element like this: document.GetElementByID('rightdiv').style.getPropertyValue('max-height');
And you can set the attribute on an element like this: .setAttribute('style','max-height:'+heightVariable+';');
Note: if you're simply looking to set both element's max-height
property in one line, you can do so like this:
#leftdiv,#rightdiv
{
min-height: 600px;
}
I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
for (Long s : list) {
System.out.println(s);
}
}
Works also with array of strings
Using islice
and chain.from_iterable
:
>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]
This can be useful when you need more than one element:
>>> elements = [(0, 1, 2, 3, 4, 5),
(10, 11, 12, 13, 14, 15),
(20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]
I solve my problem by passing nil permission while login.
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
Guava offers Lists#reverse(List)
and ImmutableList#reverse()
. As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList
, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
Use the standard CSS tab-size
.
To insert a tab symbol (if standard tab key, move cursor) press Alt + 0 + 0 + 9
.element {
-moz-tab-size: 4;
tab-size: 4;
}
My preferred:
*{-moz-tab-size: 1; tab-size: 1;}
Look at snippet or quick found example at tab-size.
.t1{_x000D_
-moz-tab-size: 1;_x000D_
tab-size: 1;_x000D_
}_x000D_
.t2{_x000D_
-moz-tab-size: 2;_x000D_
tab-size: 2;_x000D_
}_x000D_
.t4{_x000D_
-moz-tab-size: 4;_x000D_
tab-size: 4;_x000D_
}_x000D_
pre {border: 1px dotted;}
_x000D_
<h3>tab = {default} space</h3>_x000D_
<pre>_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 1 space</h3>_x000D_
<pre class="t1">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 2 space</h3>_x000D_
<pre class="t2">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>_x000D_
_x000D_
<h3>tab = 4 space</h3>_x000D_
<pre class="t4">_x000D_
one tab text_x000D_
two tab text_x000D_
</pre>
_x000D_
Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:
df['column_name'].astype(np.float).astype("Int32")
NB: You have to go through numpy float first and then to nullable Int32, for some reason.
The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.
Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:
... ??: class, interface, or enum expected ...
And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.
If you don't want to use the elasticdump like a console tool. You can use next node.js script
Please follow these Steps:
For Eclipse:
Properties
Java Build Path
Libraries
tab. There click the Add External JARs
Button on the Right pane.android-support-v4.jar
file, usually the path for the Jar file is :android-support-v4.jar
Library, navigate to the Order and Export
tab and put check mark on the android-support-v4
Library file.For Android Studio:
Short Version:
build.gradle
file: implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION'
Long Version:
Go to File -> Project Structure
Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"
Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"
Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.
Rebuild your project and now everything should work.
Further reading regarding this Question:
I hope this helps.
If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:
i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
if x in d:
d[x] = d[x] + y #or whatever your function needs to be to combine them
else:
d[x] = y
In that example, d == {'a': 3, 'c': 4, 'b': 8}
Intention of ConstraintLayout
is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.
Rules remind you of RelativeLayout
, for example setting the left to the left of some other view.
app:layout_constraintBottom_toBottomOf="@+id/view1"
Unlike RelativeLayout
, ConstraintLayout
offers bias
value that is used to position a view in terms of 0% and 100% horizontal and vertical offset relative to the handles (marked with circle). These percentages (and fractions) offer seamless positioning of the view across different screen densities and sizes.
app:layout_constraintHorizontal_bias="0.33" <!-- from 0.0 to 1.0 -->
app:layout_constraintVertical_bias="0.53" <!-- from 0.0 to 1.0 -->
Baseline handle (long pipe with rounded corners, below the circle handle) is used to align content of the view with another view reference.
Square handles (on each corner of the view) are used to resize the view in dps.
This is totally opinion based and my impression of ConstraintLayout
if you are using ASP.NET MVC
Open the layout file "_Layout.cshtml" or your custom one
At the part of the code you see, as below:
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")
Remove the line "@Scripts.Render("~/bundles/jquery")"
(at the part of the code you see) past as the latest line, as below:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
This help me and hope helps you as well.
For me this works well with IE10, Chrome, Firefox and Safari:
#MyDiv>*
{
zoom: 50%;
-moz-transform: scale(0.5);
-webkit-transform: scale(1.0);
}
This zooms all content in to 50%.
For anyone wanting to have their label at the base of their bars just divide v by the value of the label like this:
for i, v in enumerate(labels):
axes.text(i-.25,
v/labels[i]+100,
labels[i],
fontsize=18,
color=label_color_list[i])
(note: I added 100 so it wasn't absolutely at the bottom)
If you are using Guava and all you want to do is iterate through your values:
for(SyndEntry entry: Iterables.filter(sf.getEntries(), SyndEntry.class){
...
}
If you need an actual List you can use
List<SyndEntry> list = Lists.newArrayList(
Iterables.filter(sf.getEntries(), SyndEntry.class));
or
List<SyndEntry> list = ImmutableList.copyOf(
Iterables.filter(sf.getEntries(), SyndEntry.class));
Setting isBodyHtml
to true
allows you to use HTML tags in the message body:
msg = new MailMessage("[email protected]",
"[email protected]", "Message from PSSP System",
"This email sent by the PSSP system<br />" +
"<b>this is bold text!</b>");
msg.IsBodyHtml = true;
Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.
We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.
We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.
When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.
This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).
I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.
Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.
copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,
A cs class will be generated use that cs file as below:
var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
where RootObject is the name of the generated cs file;
The list of encodings that node supports natively is rather short:
If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:
Use iconv-lite to recode files:
var iconvlite = require('iconv-lite');
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
return iconvlite.decode(content, encoding);
}
Alternatively, use iconv:
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
var iconv = new Iconv(encoding, 'UTF-8');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
}
The only character that needs escaping is <
. (>
is meaningless outside of a tag).
Therefore, your "magic" code is:
safestring = unsafestring.replace(/</g,'<');
$where.= '(';
$where.= 'admin_trek.trek='."%$search%".' AND ';
$where.= 'admin_trek.state_id='."$search".' OR ';
$where.= 'admin_trek.difficulty='."$search".' OR ';
$where.= 'admin_trek.month='."$search".' AND ';
$where.= 'admin_trek.status = 1)';
$this->db->select('*');
$this->db->from('admin_trek');
$this->db->join('admin_difficulty',admin_difficulty.difficulty_id = admin_trek.difficulty');
$this->db->where($where);
$query = $this->db->get();
I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}
QFile file("test.txt");
/*
*If file does not exist, it will be created
*/
if (!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::ReadWrite))
{
qDebug() << "FAILED TO CREATE FILE / FILE DOES NOT EXIST";
}
/*for Reading line by line from text file*/
while (!file.atEnd()) {
QByteArray line = file.readLine();
qDebug() << "read output - " << line;
}
/*for writing line by line to text file */
if (file.open(QIODevice::ReadWrite))
{
QTextStream stream(&file);
stream << "1_XYZ"<<endl;
stream << "2_XYZ"<<endl;
}
For Swift 3.0+
extension String {
func SizeOf_String( font: UIFont) -> CGSize {
let fontAttribute = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttribute) // for Single Line
return size;
}
}
Use it like...
let Str = "ABCDEF"
let Font = UIFont.systemFontOfSize(19.0)
let SizeOfString = Str.SizeOfString(font: Font!)
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
For instance:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
Use inspect.getmembers
to get all the variables/classes/functions etc. in a module, and pass in inspect.isfunction
as the predicate to get just the functions:
from inspect import getmembers, isfunction
from my_project import my_module
functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]
getmembers
returns a list of (object_name, object)
tuples sorted alphabetically by name.
You can replace isfunction
with any of the other isXXX
functions in the inspect
module.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Use _.forOwn()
.
_.forOwn(obj, function(value, key) { } );
https://lodash.com/docs#forOwn
Note that forOwn
checks hasOwnProperty
, as you usually need to do when looping over an object's properties. forIn
does not do this check.
You can use header files.
Good practice.
You can create a file called player.h
declare all functions that are need by other cpp files in that header file and include it when needed.
player.h
#ifndef PLAYER_H // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H
#include "stdafx.h"
#include <SFML/Graphics.hpp>
int playerSprite();
#endif
player.cpp
#include "player.h" // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"
int playerSprite(){
sf::Texture Texture;
if(!Texture.loadFromFile("player.png")){
return 1;
}
sf::Sprite Sprite;
Sprite.setTexture(Texture);
return 0;
}
main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h" //Here. Again player.h must be in the current directory. or use relative or absolute path to it.
int main()
{
// ...
int p = playerSprite();
//...
Not such a good practice but works for small projects. declare your function in main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"
int playerSprite(); // Here
int main()
{
// ...
int p = playerSprite();
//...
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){
$username= $_POST['username'];
$password= md5($_POST['password']);
$query = "SELECT password FROM tbl WHERE username = '$username'";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
if($password == $row['password']){
session_start();
$_SESSION['logged in'] = true;
echo "Logged in";
}
}
In my case I didn't need entryComponents at all - just the basic setup as described in the link below, but I needed to include the import in both the main app module and the enclosing module.
imports: [
NgbModule.forRoot(),
...
]
https://medium.com/@sunilk/getting-started-angular-6-and-ng-bootstrap-4-4b314e015c1c
You only need to add it to entryComponents if a component will be included in the modal. From the docs:
You can pass an existing component as content of the modal window. In this case remember to add content component as an entryComponents section of your NgModule.
Simple socket server app example
I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.
This example app runs a server that returns a ROT-1 cypher of the input.
You would then need to add an Exit
button + some sleep delays, but this should get you started.
To play with it:
netcat $PHONE_IP 12345
Android sockets are the same as Java's, except we have to deal with some permission issues.
src/com/cirosantilli/android_cheat/socket/Main.java
package com.cirosantilli.android_cheat.socket;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Activity {
static final String TAG = "AndroidCheatSocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Main.TAG, "onCreate");
Main.this.startService(new Intent(Main.this, MyService.class));
}
public static class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Main.TAG, "onHandleIntent");
final int port = 12345;
ServerSocket listener = null;
try {
listener = new ServerSocket(port);
Log.d(Main.TAG, String.format("listening on port = %d", port));
while (true) {
Log.d(Main.TAG, "waiting for client");
Socket socket = listener.accept();
Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
for (String inputLine; (inputLine = in.readLine()) != null;) {
Log.d(Main.TAG, "received");
Log.d(Main.TAG, inputLine);
StringBuilder outputStringBuilder = new StringBuilder("");
char inputLineChars[] = inputLine.toCharArray();
for (char c : inputLineChars)
outputStringBuilder.append(Character.toChars(c + 1));
out.println(outputStringBuilder);
}
}
} catch(IOException e) {
Log.d(Main.TAG, e.toString());
}
}
}
}
We need a Service
or other background method or else: How do I fix android.os.NetworkOnMainThreadException?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cirosantilli.android_cheat.socket"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="AndroidCheatsocket">
<activity android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Main$MyService" />
</application>
</manifest>
We must add: <uses-permission android:name="android.permission.INTERNET" />
or else: Java socket IOException - permission denied
On GitHub with a build.xml
: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket
The simple way to get any row in csv file
import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
csvFileArray.append(row)
print(csvFileArray[0])
array_slice() is best thing to try, following are the examples:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
Unfortunately, the meaning of things like ( and \( are swapped between Emacs style regular expressions and most other styles. So if you try to escape these you may be doing the opposite of what you want.
So you really have to know what style you are trying to quote.
In chrome you can find easily not only your JS version but also a flash version. All you need is to type chrome://version/
in a command line and you will get something like this:
No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.
The simplest one line that worked for me:
filter: opacity(0.5) drop-shadow(0 0 0 blue);
You can adjust opacity from 0 to 1 to make color lighter or darker.
If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:
<div ng-controller="Ctrl">
<div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
thing {{thing}}
</div>
</div>
function Ctrl($scope) {
$scope.things = [
'A', 'B', 'C'
];
}
angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last){
// iteration is complete, do whatever post-processing
// is necessary
element.parent().css('border', '1px solid black');
}
};
});
COPY your table (Name, Latitude, Longitude) FROM 'C:\Temp\your file.csv' DELIMITERS ',' CSV HEADER;
Use c:\Temp\"Your File"\
.
export
is a Bash builtin, echo
is an executable in your $PATH
. So export
is interpreted by Bash as is, without spawning a new process.
You need to get Bash to interpret your command, which you can pass as a string with the -c
option:
bash -c "export foo=bar; echo \$foo"
ALSO:
Each invocation of bash -c
starts with a fresh environment. So something like:
bash -c "export foo=bar"
bash -c "echo \$foo"
will not work. The second invocation does not remember foo
.
Instead, you need to chain commands separated by ;
in a single invocation of bash -c
:
bash -c "export foo=bar; echo \$foo"
For windows, everybody said you should set environment variables for nodejs and npm modules, but do you know why? For some modules, they have command line tool, after installed the module, there'are [module].cmd file in C:\Program Files\nodejs, and it's used for launch in window command. So if you don't add the path containing the cmd file to environment variables %PATH% , you won't launch them successfully through command window.
Check out SQLCMD command line tool that comes with SQL Server. http://technet.microsoft.com/en-us/library/ms162773.aspx
Premise to my answer:
Approach
Additionally, the base image can be upgraded/ the container with a complete new base image can be built at regular intervals, as the maintainer feels necessary
Advantages
You can grant system privileges with or without the admin option. The default being without admin option.
GRANT CREATE SESSION TO username
or with admin option:
GRANT CREATE SESSION TO username WITH ADMIN OPTION
The Grantee with the ADMIN OPTION
can grant and revoke privileges to other users
I believe the best solution will be using head()
Considering your example:
+---+---+
| A| B|
+---+---+
|1.0|4.0|
|2.0|5.0|
|3.0|6.0|
+---+---+
Using agg and max method of python we can get the value as following :
from pyspark.sql.functions import max
df.agg(max(df.A)).head()[0]
This will return:
3.0
Make sure you have the correct import:
from pyspark.sql.functions import max
The max function we use here is the pySPark sql library function, not the default max function of python.
We've recently updated from IntelliJ 12 to IntelliJ 14 Ultimate and we've encountered this problem too. Our solution was to disable the proxy in the settings. We also stopped remembering the passwords once, but might not sure if that helps. Proxy settings are under File-Settings-Apearance & Behavior-System settings-HTTP Proxy.
I doubt css understands left
by itself. You need to use it specifying position. You are using .css() correctly
position: relative/absolute/whatever;
left: 900px;
heres a fiddle of it working
and without the position here's what you get
Change your if statement to be like this - with quotes around -900px
var n = $("items").css("left");
if(n == '-900px'){
$(".items span").fadeOut("slow");
}
I am not an expert but try white-space:nowrap;
The white-space property is supported in all major browsers.
Note: The value "inherit"
is not supported in IE7 and earlier. IE8 requires a !DOCTYPE
. IE9 supports "inherit"
.
functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design
Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
If you don't mind using numpy, you can use numpy.random.choice.
For example:
import numpy
items = [["item1", 0.2], ["item2", 0.3], ["item3", 0.45], ["item4", 0.05]
elems = [i[0] for i in items]
probs = [i[1] for i in items]
trials = 1000
results = [0] * len(items)
for i in range(trials):
res = numpy.random.choice(items, p=probs) #This is where the item is selected!
results[items.index(res)] += 1
results = [r / float(trials) for r in results]
print "item\texpected\tactual"
for i in range(len(probs)):
print "%s\t%0.4f\t%0.4f" % (items[i], probs[i], results[i])
If you know how many selections you need to make in advance, you can do it without a loop like this:
numpy.random.choice(items, trials, p=probs)
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
r = ((double) rand() / (RAND_MAX)) + 1;
In you app config file change the url
to localhost/example/public
Then when you want to link to something
<a href="{{ url('page') }}">Some Text</a>
without blade
<a href="<?php echo url('page') ?>">Some Text</a>
It would depend on why you want it to restart itself.
If you are just looking for a way to have the service clean itself out periodically then you could have a timer running in the service that periodically causes a purge routine.
If you are looking for a way to restart on failure - the service host itself can provide that ability when it is setup.
So why do you need to restart the server? What are you trying to achieve?
try this
document.getElementById("datapicker").addEventListener("submit", function())
Per the comment of Larson, this is now possible with the save-actions plugin.
System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));
If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.
JupyterLab notebooks have the following features and more:
What I did to achieve the goal was to make this..
# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):
and below the save() method is this..
# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
# your logic here
so when i edit some fields but not editing the image, I put this..
Model.save("skip creating photo thumbnail")
you can replace the "skip creating photo thumbnail"
with "im just editing the description"
or a more formal text.
Hope this one helps!
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
You need to understand the difference between the visible address of an email, and the delivery.
msg["To"]
is essentially what is printed on the letter. It doesn't actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.
The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.
There are various reasons for this. For example forwarding. The To:
header field doesn't change on forwarding, however the email is dropped into a different mailbox.
The smtp.sendmail
command now takes care of the actual delivery. email.Message
is the contents of the letter only, not the delivery.
In low-level SMTP
, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.
For the header, it can also contain for example the name, e.g. To: First Last <[email protected]>, Other User <[email protected]>
. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on ,
you still not not have the valid adresses!
I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.
Simple and easy:
$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();
The real reason because set
does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.
In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:
SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1
And not:
SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1
I created a small class to grab data from the provided url, then extract html elements of your choice. The class makes use of CURL and DOMDocument.
php class:
class crawler {
public static $timeout = 2;
public static $agent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
public static function http_request($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, self::$agent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public static function strip_whitespace($data) {
$data = preg_replace('/\s+/', ' ', $data);
return trim($data);
}
public static function extract_elements($tag, $data) {
$response = array();
$dom = new DOMDocument;
@$dom->loadHTML($data);
foreach ( $dom->getElementsByTagName($tag) as $index => $element ) {
$response[$index]['text'] = self::strip_whitespace($element->nodeValue);
foreach ( $element->attributes as $attribute ) {
$response[$index]['attributes'][strtolower($attribute->nodeName)] = self::strip_whitespace($attribute->nodeValue);
}
}
return $response;
}
}
example usage:
$data = crawler::http_request('https://stackoverflow.com/questions/2313107/how-do-i-make-a-simple-crawler-in-php');
$links = crawler::extract_elements('a', $data);
if ( count($links) > 0 ) {
file_put_contents('links.json', json_encode($links, JSON_PRETTY_PRINT));
}
example response:
[
{
"text": "Stack Overflow",
"attributes": {
"href": "https:\/\/stackoverflow.com",
"class": "-logo js-gps-track",
"data-gps-track": "top_nav.click({is_current:false, location:2, destination:8})"
}
},
{
"text": "Questions",
"attributes": {
"id": "nav-questions",
"href": "\/questions",
"class": "-link js-gps-track",
"data-gps-track": "top_nav.click({is_current:true, location:2, destination:1})"
}
},
{
"text": "Developer Jobs",
"attributes": {
"id": "nav-jobs",
"href": "\/jobs?med=site-ui&ref=jobs-tab",
"class": "-link js-gps-track",
"data-gps-track": "top_nav.click({is_current:false, location:2, destination:6})"
}
}
]
I've just solved this problem myself. I found the solution on MSDN: http://msdn.microsoft.com/en-us/library/ms155391.aspx.
The format basically is
http://<server>/reportserver?/<path>/<report>&rs:Command=Render&<parameter>=<value>
git config --list
git config -l
will display your username and email together, along with other info
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
If you run your playbook with ansible-playbook -vvv
you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).
I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this
# fails
- name: Add all instance public IPs to host group
add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
loop: "{{ ec2.instances }}"
but that fails too.
So this is not an answer. Just some debugging help and things not to try.
>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'
Another solution is by using .animate() and appropriate CSS.
e.g.
$('#mydiv').animate({ marginLeft: "100%"} , 4000);
Thanks to this post, my full css for cross browser happiness is:
<style>
.backgroundpic {
background-image: url('img/home.jpg');
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='img/home.jpg',
sizingMethod='scale');
}
</style>
It's been so long since I've worked on this piece of code, but I'd like to add for more browser compatibility I've appended this to my CSS for more browser compatibility:
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
I would instead write a helper bash script that runs svn commit
on all the files you need to and none of the ones you don't. This way you have much more control.
For example, with one line, you can commit all files with extension .h
and .cpp
to which you made changes (and which wouldn't cause a conflict):
svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`
Change / add extensions to the [h|cpp]
part. Add a log message in between the quotes of -m ""
if needed.
The new version of Qt Creator also has a "profile" build option between debug and release. Here's how I'm detecting that:
CONFIG(debug, debug|release) { DEFINES += DEBUG_MODE }
else:CONFIG(force_debug_info) { DEFINES += PROFILE_MODE }
else { DEFINES += RELEASE_MODE }