text
stringlengths
2
1.04M
meta
dict
/* $NetBSD: hack.engrave.c,v 1.14 2011/08/07 06:03:45 dholland Exp $ */ /* * Copyright (c) 1985, Stichting Centrum voor Wiskunde en Informatica, * Amsterdam * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Stichting Centrum voor Wiskunde en * Informatica, nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1982 Jay Fenlason <hack@gnu.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> #ifndef lint __RCSID("$NetBSD: hack.engrave.c,v 1.14 2011/08/07 06:03:45 dholland Exp $"); #endif /* not lint */ #include <stdlib.h> #include "hack.h" #include "extern.h" struct engr { struct engr *nxt_engr; char *engr_txt; xchar engr_x, engr_y; unsigned engr_lth; /* for save & restore; not length of * text */ long engr_time; /* moment engraving was (will be) * finished */ xchar engr_type; #define DUST 1 #define ENGRAVE 2 #define BURN 3 }; static struct engr *head_engr; static void del_engr(struct engr *); static struct engr * engr_at(xchar x, xchar y) { struct engr *ep = head_engr; while (ep) { if (x == ep->engr_x && y == ep->engr_y) return (ep); ep = ep->nxt_engr; } return ((struct engr *) 0); } int sengr_at(const char *s, xchar x, xchar y) { struct engr *ep = engr_at(x, y); char *t; size_t n; if (ep && ep->engr_time <= moves) { t = ep->engr_txt; /* if(!strcmp(s,t)) return(1); */ n = strlen(s); while (*t) { if (!strncmp(s, t, n)) return (1); t++; } } return (0); } void u_wipe_engr(int cnt) { if (!u.uswallow && !Levitation) wipe_engr_at(u.ux, u.uy, cnt); } void wipe_engr_at(xchar x, xchar y, xchar cnt) { struct engr *ep = engr_at(x, y); int pos; char ch; size_t lth; if (ep) { if ((ep->engr_type != DUST) || Levitation) { cnt = rn2(1 + 50 / (cnt + 1)) ? 0 : 1; } lth = strlen(ep->engr_txt); if (lth && cnt > 0) { while (cnt--) { pos = rn2(lth); if ((ch = ep->engr_txt[pos]) == ' ') continue; ep->engr_txt[pos] = (ch != '?') ? '?' : ' '; } } while (lth && ep->engr_txt[lth - 1] == ' ') ep->engr_txt[--lth] = 0; while (ep->engr_txt[0] == ' ') ep->engr_txt++; if (!ep->engr_txt[0]) del_engr(ep); } } void read_engr_at(int x, int y) { struct engr *ep = engr_at(x, y); if (ep && ep->engr_txt[0]) { switch (ep->engr_type) { case DUST: pline("Something is written here in the dust."); break; case ENGRAVE: pline("Something is engraved here on the floor."); break; case BURN: pline("Some text has been burned here in the floor."); break; default: impossible("Something is written in a very strange way."); } pline("You read: \"%s\".", ep->engr_txt); } } void make_engr_at(int x, int y, const char *s) { struct engr *ep; if ((ep = engr_at(x, y)) != NULL) del_engr(ep); ep = alloc(sizeof(*ep) + strlen(s) + 1); ep->nxt_engr = head_engr; head_engr = ep; ep->engr_x = x; ep->engr_y = y; ep->engr_txt = (char *) (ep + 1); (void) strcpy(ep->engr_txt, s); ep->engr_time = 0; ep->engr_type = DUST; ep->engr_lth = strlen(s) + 1; } int doengrave(void) { int len; char *sp; struct engr *ep, *oep = engr_at(u.ux, u.uy); char buf[BUFSZ]; xchar type; int spct; /* number of leading spaces */ struct obj *otmp; multi = 0; if (u.uswallow) { pline("You're joking. Hahaha!"); /* riv05!a3 */ return (0); } /* one may write with finger, weapon or wand */ otmp = getobj("#-)/", "write with"); if (!otmp) return (0); if (otmp == &zeroobj) otmp = 0; if (otmp && otmp->otyp == WAN_FIRE && otmp->spe) { type = BURN; otmp->spe--; } else { /* first wield otmp */ if (otmp != uwep) { if (uwep && uwep->cursed) { /* Andreas Bormann */ pline("Since your weapon is welded to your hand,"); pline("you use the %s.", aobjnam(uwep, NULL)); otmp = uwep; } else { if (!otmp) pline("You are now empty-handed."); else if (otmp->cursed) pline("The %s %s to your hand!", aobjnam(otmp, "weld"), (otmp->quan == 1) ? "itself" : "themselves"); else pline("You now wield %s.", doname(otmp)); setuwep(otmp); } } if (!otmp) type = DUST; else if (otmp->otyp == DAGGER || otmp->otyp == TWO_HANDED_SWORD || otmp->otyp == CRYSKNIFE || otmp->otyp == LONG_SWORD || otmp->otyp == AXE) { type = ENGRAVE; if ((int) otmp->spe <= -3) { type = DUST; pline("Your %s too dull for engraving.", aobjnam(otmp, "are")); if (oep && oep->engr_type != DUST) return (1); } } else type = DUST; } if (Levitation && type != BURN) { /* riv05!a3 */ pline("You can't reach the floor!"); return (1); } if (oep && oep->engr_type == DUST) { pline("You wipe out the message that was written here."); del_engr(oep); oep = 0; } if (type == DUST && oep) { pline("You cannot wipe out the message that is %s in the rock.", (oep->engr_type == BURN) ? "burned" : "engraved"); return (1); } pline("What do you want to %s on the floor here? ", (type == ENGRAVE) ? "engrave" : (type == BURN) ? "burn" : "write"); getlin(buf); clrlin(); spct = 0; sp = buf; while (*sp == ' ') spct++, sp++; len = strlen(sp); if (!len || *buf == '\033') { if (type == BURN) otmp->spe++; return (0); } switch (type) { case DUST: case BURN: if (len > 15) { multi = -(len / 10); nomovemsg = "You finished writing."; } break; case ENGRAVE: /* here otmp != 0 */ { int len2 = (otmp->spe + 3) * 2 + 1; pline("Your %s dull.", aobjnam(otmp, "get")); if (len2 < len) { len = len2; sp[len] = 0; otmp->spe = -3; nomovemsg = "You cannot engrave more."; } else { otmp->spe -= len / 2; nomovemsg = "You finished engraving."; } multi = -len; } break; } if (oep) len += strlen(oep->engr_txt) + spct; ep = alloc(sizeof(*ep) + len + 1); ep->nxt_engr = head_engr; head_engr = ep; ep->engr_x = u.ux; ep->engr_y = u.uy; sp = (char *) (ep + 1); /* (char *)ep + sizeof(struct engr) */ ep->engr_txt = sp; if (oep) { (void) strcpy(sp, oep->engr_txt); (void) strcat(sp, buf); del_engr(oep); } else (void) strcpy(sp, buf); ep->engr_lth = len + 1; ep->engr_type = type; ep->engr_time = moves - multi; /* kludge to protect pline against excessively long texts */ if (len > BUFSZ - 20) sp[BUFSZ - 20] = 0; return (1); } void save_engravings(int fd) { struct engr *ep = head_engr; while (ep) { if (!ep->engr_lth || !ep->engr_txt[0]) { ep = ep->nxt_engr; continue; } bwrite(fd, &(ep->engr_lth), sizeof(ep->engr_lth)); bwrite(fd, ep, sizeof(struct engr) + ep->engr_lth); ep = ep->nxt_engr; } bwrite(fd, nul, sizeof(unsigned)); head_engr = 0; } void rest_engravings(int fd) { struct engr *ep; unsigned lth; head_engr = 0; while (1) { mread(fd, &lth, sizeof(unsigned)); if (lth == 0) return; ep = alloc(sizeof(*ep) + lth); mread(fd, ep, sizeof(*ep) + lth); ep->nxt_engr = head_engr; ep->engr_txt = (char *) (ep + 1); /* Andreas Bormann */ head_engr = ep; } } static void del_engr(struct engr *ep) { struct engr *ept; if (ep == head_engr) head_engr = ep->nxt_engr; else { for (ept = head_engr; ept; ept = ept->nxt_engr) { if (ept->nxt_engr == ep) { ept->nxt_engr = ep->nxt_engr; goto fnd; } } impossible("Error in del_engr?"); return; fnd: ; } free(ep); }
{ "content_hash": "30389346680d3d9d76c3e74f9466dc2e", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 78, "avg_line_length": 25.842105263157894, "alnum_prop": 0.6090582872660266, "repo_name": "execunix/vinos", "id": "cd82725d5793d00952118f167e84b09ed9a6f41e", "size": "10311", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "games/hack/hack.engrave.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<table id="arial-black"> <thead> <th><abbr title="Operating System">OS</abbr></th> <th> <span class="legend supported"><span class="icon-supported" aria-hidden="true"></span> Supported</span> <span class="legend aliased"><span class="icon-aliased" aria-hidden="true"></span>Aliased</span> <span class="legend unsupported"><span class="icon-unsupported" aria-hidden="true"></span> <abbr title="Operating System">OS</abbr> Default</span></th> </thead> <tbody> <tr class="supported"> <td><a href="os/os-x-snow-leopard"><span class="icon-os-x-snow-leopard" aria-hidden="true"></span><span class="a11y-hidden">Mac OS X</span> <span class="version">Snow Leopard 10.6.8</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/os-x-lion"><span class="icon-os-x-lion" aria-hidden="true"></span><span class="a11y-hidden">Mac OS X</span> <span class="version">Lion 10.7.5</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/os-x-mountain-lion"><span class="icon-os-x-mountain-lion" aria-hidden="true"></span><span class="a11y-hidden">Mac OS X</span> <span class="version">Mountain Lion 10.8.5</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/os-x-mavericks"><span class="icon-os-x-mavericks" aria-hidden="true"></span><span class="a11y-hidden">Mac OS X</span> <span class="version">Mavericks 10.9.5</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/win-xp-sp3"><span class="icon-win-xp-sp3" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">XP (NT 5.1 SP3)</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/win-xp"><span class="icon-win-xp" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">XP (NT 5.2)</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/win-7"><span class="icon-win-7" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">7 (NT 6.1)</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/win-8"><span class="icon-win-8" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">8 (NT 6.2)</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class="supported"> <td><a href="os/win-8-1"><span class="icon-win-8-1" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">8.1 (NT 6.3)</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class=" unsupported"> <td><a href="os/ios-5-1-iphone"><span class="icon-ios-5-1-iphone" aria-hidden="true"></span><span class="a11y-hidden">iOS-iPhone</span> <span class="version">5.1</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/ios-6-iphone"><span class="icon-ios-6-iphone" aria-hidden="true"></span><span class="a11y-hidden">iOS-iPhone</span> <span class="version">6.0</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/ios-7-iphone"><span class="icon-ios-7-iphone" aria-hidden="true"></span><span class="a11y-hidden">iOS-iPhone</span> <span class="version">7.0.3</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/ios-8-1-iphone"><span class="icon-ios-8-1-iphone" aria-hidden="true"></span><span class="a11y-hidden">iOS-iPhone</span> <span class="version">8.1</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/ios-9-3-iphone"><span class="icon-ios-9-3-iphone" aria-hidden="true"></span><span class="a11y-hidden">iOS-iPhone</span> <span class="version">9.3</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/android-4-2-2"><span class="icon-android-4-2-2" aria-hidden="true"></span><span class="a11y-hidden">Android</span> <span class="version">Jelly Bean 4.2.2</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/android-4-4"><span class="icon-android-4-4" aria-hidden="true"></span><span class="a11y-hidden">Android</span> <span class="version">KitKat 4.4.2</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/android-5-0"><span class="icon-android-5-0" aria-hidden="true"></span><span class="a11y-hidden">Android</span> <span class="version">Lollipop 5.0.2</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/android-6-0"><span class="icon-android-6-0" aria-hidden="true"></span><span class="a11y-hidden">Android</span> <span class="version">Marshmallow 6.0.1</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class="supported"> <td><a href="os/win-phone-7-5"><span class="icon-win-phone-7-5" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">Phone 7.5</span></a></td> <td style="font-family: 'Arial Black'"> <span class="icon-supported" aria-hidden="true"></span><span class="a11y-hidden">Supported</span> Arial Black </td> </tr> <tr class=" unsupported"> <td><a href="os/win-phone-8"><span class="icon-win-phone-8" aria-hidden="true"></span><span class="a11y-hidden">Windows</span> <span class="version">Phone 8.0</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/ubuntu-14"><span class="icon-ubuntu-14" aria-hidden="true"></span><span class="a11y-hidden">Linux</span> <span class="version">Ubuntu 14.04</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> <tr class=" unsupported"> <td><a href="os/fedora-20"><span class="icon-fedora-20" aria-hidden="true"></span><span class="a11y-hidden">Linux</span> <span class="version">Fedora 20</span></a></td> <td> <span class="icon-unsupported" aria-hidden="true"></span><span class="a11y-hidden">unsupported</span> </td> </tr> </tbody> </table>
{ "content_hash": "865534b3b8b659b126abd904a0b1fa22", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 204, "avg_line_length": 38.60344827586207, "alnum_prop": 0.6079723090665475, "repo_name": "zachleat/font-family-reunion", "id": "d2455aa30be0b5a250b27afe872a50f661101eab", "size": "8956", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fontfamily.io/results/arial-black.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3777" }, { "name": "CSS", "bytes": "7363" }, { "name": "HTML", "bytes": "9283570" }, { "name": "JavaScript", "bytes": "20996" }, { "name": "PHP", "bytes": "3620" }, { "name": "Shell", "bytes": "64" } ], "symlink_target": "" }
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ❤️ **Donate:** Enjoying MagicMirror²? [Please consider a donation!](https://magicmirror.builders/donate) With your help we can continue to improve the MagicMirror² ## [2.11.0] - 2020-04-01 🚨 READ THIS BEFORE UPDATING 🚨 In the past years the project has grown a lot. This came with a huge downside: poor maintainability. If I let the project continue the way it was, it would eventually crash and burn. More important: I would completely lose the drive and interest to continue the project. Because of this the decision was made to simplify the core by removing all side features like automatic installers and support for exotic platforms. This release (2.11.0) is the first real release that will reflect (parts) of these changes. As a result of this, some things might break. So before you continue make sure to backup your installation. Your config, your modules or better yet: your full MagicMirror folder. In other words: update at your own risk. For more information regarding this major change, please check issue [#1860](https://github.com/MichMich/MagicMirror/issues/1860). ### Deleted - Remove installers. - Remove externalized scripts. - Remove jshint dependency, instead eslint checks your config file now ### Added - Brazilian translation for "FEELS". - Ukrainian translation. - Finnish translation for "PRECIP", "UPDATE_INFO_MULTIPLE" and "UPDATE_INFO_SINGLE". - Added the ability to hide the temp label and weather icon in the `currentweather` module to allow showing only information such as wind and sunset/rise. - The `clock` module now optionally displays sun and moon data, including rise/set times, remaining daylight, and percent of moon illumination. - Added Hebrew translation. - Add HTTPS support and update config.js.sample - Run tests on long term support and latest stable version of nodejs - Added the ability to configure a list of modules that shouldn't be update checked. - Run linters on git commits - Added date functionality to compliments: display birthday wishes or celebrate an anniversary ### Fixed - Force declaration of public ip address in config file (ISSUE #1852) - Fixes `run-start.sh`: If running in docker-container, don't check the environment, just start electron (ISSUE #1859) - Fix calendar time offset for recurring events crossing Daylight Savings Time (ISSUE #1798) - Fix regression in currentweather module causing 'undefined' to show up when config.hideTemp is false - Fix FEELS translation for Croatian - Fixed weather tests [#1840](https://github.com/MichMich/MagicMirror/issues/1840) - Fixed Socket.io can't be used with Reverse Proxy in serveronly mode [#1934](https://github.com/MichMich/MagicMirror/issues/1934) - Fix update checking skipping 3rd party modules the first time ### Changed - Remove documentation from core repository and link to new dedicated docs site: [docs.magicmirror.builders](https://docs.magicmirror.builders). - Updated config.js.sample: Corrected some grammar on `config.js.sample` comment section. - Removed `run-start.sh` script and update start commands: - To start using electron, use `npm run start`. - To start in server only mode, use `npm run server`. - Remove redundant logging from modules. - Timestamp in log output now also contains the date - Turkish translation. - Option to configure the size of the currentweather module. ## [2.10.1] - 2020-01-10 ### Changed - Updated README.md: Added links to the official documentation website and remove links to broken installer. ## [2.10.0] - 2020-01-01 Special thanks to @sdetweil for all his great contributions! ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install`. ### Added - Timestamps in log output. - Padding in dateheader mode of the calendar module. - New upgrade script to help users consume regular updates installers/upgrade-script.sh. - New script to help setup pm2, without install installers/fixuppm2.sh. ### Updated - Updated lower bound of `lodash` and `helmet` dependencies for security patches. - Updated compliments.js to handle newline in text, as textfields to not interpolate contents. - Updated raspberry.sh installer script to handle new platform issues, split node/npm, pm2, and screen saver changes. - Improve handling for armv6l devices, where electron support has gone away, add optional serveronly config option. - Improved run-start.sh to handle for serveronly mode, by choice, or when electron not available. - Only check for xwindows running if not on macOS. ### Fixed - Fixed issue in weatherforecast module where predicted amount of rain was not using the decimal symbol specified in config.js. - Module header now updates correctly, if a module need to dynamically show/hide its header based on a condition. - Fix handling of config.js for serverOnly mode commented out. - Fixed issue in calendar module where the debug script didn't work correctly with authentication. - Fixed issue that some full day events were not correctly recognized as such. - Display full day events lasting multiple days as happening today instead of some days ago if they are still ongoing. ## [2.9.0] - 2019-10-01 ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install`. If you are having issues running Electron, make sure your [Raspbian is up to date](https://www.raspberrypi.org/documentation/raspbian/updating.md). ### Added - Spanish translation for "PRECIP". - Adding a Malay (Malaysian) translation for MagicMirror². - Add test check URLs of vendors 200 and 404 HTTP CODE. - Add tests for new weather module and helper to stub ajax requests. ### Updated - Updatenotification module: Display update notification for a limited (configurable) time. - Enabled e2e/vendor_spec.js tests. - The css/custom.css will be rename after the next release. We've add into `run-start.sh` a instruction by GIT to ignore with `--skip-worktree` and `rm --cached`. [#1540](https://github.com/MichMich/MagicMirror/issues/1540) - Disable sending of notification CLOCK_SECOND when displaySeconds is false. ### Fixed - Updatenotification module: Properly handle race conditions, prevent crash. - Send `NEWS_FEED` notification also for the first news messages which are shown. - Fixed issue where weather module would not refresh data after a network or API outage. [#1722](https://github.com/MichMich/MagicMirror/issues/1722) - Fixed weatherforecast module not displaying rain amount on fallback endpoint. - Notifications CLOCK_SECOND & CLOCK_MINUTE being from startup instead of matched against the clock and avoid drifting. ## [2.8.0] - 2019-07-01 ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install`. If you are having issues running Electron, make sure your [Raspbian is up to date](https://www.raspberrypi.org/documentation/raspbian/updating.md). ### Added - Option to show event location in calendar - Finnish translation for "Feels" and "Weeks" - Russian translation for “Feels” - Calendar module: added `nextDaysRelative` config option - Add `broadcastPastEvents` config option for calendars to include events from the past `maximumNumberOfDays` in event broadcasts - Added feature to broadcast news feed items `NEWS_FEED` and updated news items `NEWS_FEED_UPDATED` in default [newsfeed](https://github.com/MichMich/MagicMirror/tree/develop/modules/default/newsfeed) module (when news is updated) with documented default and `config.js` options in [README.md](https://github.com/MichMich/MagicMirror/blob/develop/modules/default/newsfeed/README.md) - Added notifications to default `clock` module broadcasting `CLOCK_SECOND` and `CLOCK_MINUTE` for the respective time elapsed. - Added UK Met Office Datapoint feed as a provider in the default weather module. - Added new provider class - Added suncalc.js dependency to calculate sun times (not provided in UK Met Office feed) - Added "tempUnits" and "windUnits" to allow, for example, temp in metric (i.e. celsius) and wind in imperial (i.e. mph). These will override "units" if specified, otherwise the "units" value will be used. - Use Feels Like temp from feed if present - Optionally display probability of precipitation (PoP) in current weather (UK Met Office data) - Automatically try to fix eslint errors by passing `--fix` option to it - Added sunrise and sunset times to weathergov weather provider [#1705](https://github.com/MichMich/MagicMirror/issues/1705) - Added "useLocationAsHeader" to display "location" in `config.js` as header when location name is not returned - Added to `newsfeed.js`: in order to design the news article better with css, three more class-names were introduced: newsfeed-desc, newsfeed-desc, newsfeed-desc ### Updated - English translation for "Feels" to "Feels like" - Fixed the example calender url in `config.js.sample` - Update `ical.js` to solve various calendar issues. - Update weather city list url [#1676](https://github.com/MichMich/MagicMirror/issues/1676) - Only update clock once per minute when seconds aren't shown ### Fixed - Fixed uncaught exception, race condition on module update - Fixed issue [#1696](https://github.com/MichMich/MagicMirror/issues/1696), some ical files start date to not parse to date type - Allowance HTML5 autoplay-policy (policy is changed from Chrome 66 updates) - Handle SIGTERM messages - Fixes sliceMultiDayEvents so it respects maximumNumberOfDays - Minor types in default NewsFeed [README.md](https://github.com/MichMich/MagicMirror/blob/develop/modules/default/newsfeed/README.md) - Fix typos and small syntax errors, cleanup dependencies, remove multiple-empty-lines, add semi-rule - Fixed issues with calendar not displaying one-time changes to repeating events - Updated the fetchedLocationName variable in currentweather.js so that city shows up in the header ### Updated installer - give non-pi2+ users (pi0, odroid, jetson nano, mac, windows, ...) option to continue install - use current username vs hardcoded 'pi' to support non-pi install - check for npm installed. node install doesn't do npm anymore - check for mac as part of PM2 install, add install option string - update pm2 config with current username instead of hard coded 'pi' - check for screen saver config, "/etc/xdg/lxsession", bypass if not setup ## [2.7.1] - 2019-04-02 Fixed `package.json` version number. ## [2.7.0] - 2019-04-01 ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install`. If you are having issues running Electron, make sure your [Raspbian is up to date](https://www.raspberrypi.org/documentation/raspbian/updating.md). ### Added - Italian translation for "Feels" - Basic Klingon (tlhIngan Hol) translations - Disabled the screensaver on raspbian with installation script - Added option to truncate the number of vertical lines a calendar item can span if `wrapEvents` is enabled. - Danish translation for "Feels" and "Weeks" - Added option to split multiple day events in calendar to separate numbered events - Slovakian translation - Alerts now can contain Font Awesome icons - Notifications display time can be set in request - Newsfeed: added support for `ARTICLE_INFO_REQUEST` notification - Add `name` config option for calendars to be sent along with event broadcasts ### Updated - Bumped the Electron dependency to v3.0.13 to support the most recent Raspbian. [#1500](https://github.com/MichMich/MagicMirror/issues/1500) - Updated modernizr code in alert module, fixed a small typo there too - More verbose error message on console if the config is malformed - Updated installer script to install Node.js version 10.x ### Fixed - Fixed temperature displays in currentweather and weatherforecast modules [#1503](https://github.com/MichMich/MagicMirror/issues/1503), [#1511](https://github.com/MichMich/MagicMirror/issues/1511). - Fixed unhandled error on bad git data in updatenotification module [#1285](https://github.com/MichMich/MagicMirror/issues/1285). - Weather forecast now works with openweathermap in new weather module. Daily data are displayed, see issue [#1504](https://github.com/MichMich/MagicMirror/issues/1504). - Fixed analogue clock border display issue where non-black backgrounds used (previous fix for issue 611) - Fixed compatibility issues caused when modules request different versions of Font Awesome, see issue [#1522](https://github.com/MichMich/MagicMirror/issues/1522). MagicMirror now uses [Font Awesome 5 with v4 shims included for backwards compatibility](https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4#shims). - Installation script problems with raspbian - Calendar: only show repeating count if the event is actually repeating [#1534](https://github.com/MichMich/MagicMirror/pull/1534) - Calendar: Fix exdate handling when multiple values are specified (comma separated) - Calendar: Fix relative date handling for fulldate events, calculate difference always from start of day [#1572](https://github.com/MichMich/MagicMirror/issues/1572) - Fix null dereference in moduleNeedsUpdate when the module isn't visible - Calendar: Fixed event end times by setting default calendarEndTime to "LT" (Local time format). [#1479] - Calendar: Fixed missing calendar fetchers after server process restarts [#1589](https://github.com/MichMich/MagicMirror/issues/1589) - Notification: fixed background color (was white text on white background) - Use getHeader instead of data.header when creating the DOM so overwriting the function also propagates into it - Fix documentation of `useKMPHwind` option in currentweather ### New weather module - Fixed weather forecast table display [#1499](https://github.com/MichMich/MagicMirror/issues/1499). - Dimmed loading indicator for weather forecast. - Implemented config option `decimalSymbol` [#1499](https://github.com/MichMich/MagicMirror/issues/1499). - Aligned indoor values in current weather vertical [#1499](https://github.com/MichMich/MagicMirror/issues/1499). - Added humidity support to nunjuck unit filter. - Do not display degree symbol for temperature in Kelvin [#1503](https://github.com/MichMich/MagicMirror/issues/1503). - Weather forecast now works with openweathermap for both, `/forecast` and `/forecast/daily`, in new weather module. If you use the `/forecast`-weatherEndpoint, the hourly data are converted to daily data, see issues [#1504](https://github.com/MichMich/MagicMirror/issues/1504), [#1513](https://github.com/MichMich/MagicMirror/issues/1513). - Added fade, fadePoint and maxNumberOfDays properties to the forecast mode [#1516](https://github.com/MichMich/MagicMirror/issues/1516) - Fixed Loading string and decimalSymbol string replace [#1538](https://github.com/MichMich/MagicMirror/issues/1538) - Show Snow amounts in new weather module [#1545](https://github.com/MichMich/MagicMirror/issues/1545) - Added weather.gov as a new weather provider for US locations ## [2.6.0] - 2019-01-01 ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install`. If you are having issues updating, make sure you are running the latest version of Node. ### ✨ Experimental ✨ - New default [module weather](modules/default/weather). This module will eventually replace the current `currentweather` and `weatherforecast` modules. The new module is still pretty experimental, but it's included so you can give it a try and help us improve this module. Please give us you feedback using [this forum post](https://forum.magicmirror.builders/topic/9335/default-weather-module-refactoring). A huge, huge, huge thanks to user @fewieden for all his hard work on the new `weather` module! ### Added - Possibility to add classes to the cell of symbol, title and time of the events of calendar. - Font-awesome 5, still has 4 for backwards compatibility. - Missing `showEnd` in calendar documentation - Screenshot for the new feed module - Screenshot for the compliments module - Screenshot for the clock module - Screenshot for the current weather - Screenshot for the weather forecast module - Portuguese translation for "Feels" - Croatian translation - Fading for dateheaders timeFormat in Calendar [#1464](https://github.com/MichMich/MagicMirror/issues/1464) - Documentation for the existing `scale` option in the Weather Forecast module. ### Fixed - Allow to parse recurring calendar events where the start date is before 1900 - Fixed Polish translation for Single Update Info - Ignore entries with unparseable details in the calendar module - Bug showing FullDayEvents one day too long in calendar fixed - Bug in newsfeed when `removeStartTags` is used on the description [#1478](https://github.com/MichMich/MagicMirror/issues/1478) ### Updated - The default calendar setting `showEnd` is changed to `false`. ### Changed - The Weather Forecast module by default displays the &deg; symbol after every numeric value to be consistent with the Current Weather module. ## [2.5.0] - 2018-10-01 ### Added - Romanian translation for "Feels" - Support multi-line compliments - Simplified Chinese translation for "Feels" - Polish translate for "Feels" - French translate for "Feels" - Translations for newsfeed module - Support for toggling news article in fullscreen - Hungarian translation for "Feels" and "Week" - Spanish translation for "Feels" - Add classes instead of inline style to the message from the module Alert - Support for events having a duration instead of an end - Support for showing end of events through config parameters showEnd and dateEndFormat ### Fixed - Fixed gzip encoded calendar loading issue #1400. - Mixup between german and spanish translation for newsfeed. - Fixed close dates to be absolute, if no configured in the config.js - module Calendar - Fixed the updatenotification module message about new commits in the repository, so they can be correctly localized in singular and plural form. - Fix for weatherforecast rainfall rounding [#1374](https://github.com/MichMich/MagicMirror/issues/1374) - Fix calendar parsing issue for Midori on RasperryPi Zero w, related to issue #694. - Fix weather city ID link in sample config - Fixed issue with clientonly not updating with IP address and port provided on command line. ### Updated - Updated Simplified Chinese translation - Swedish translations - Hungarian translations for the updatenotification module - Updated Norsk bokmål translation - Updated Norsk nynorsk translation - Consider multi days event as full day events ## [2.4.1] - 2018-07-04 ### Fixed - Fix weather parsing issue #1332. ## [2.4.0] - 2018-07-01 ⚠️ **Warning:** This release includes an updated version of Electron. This requires a Raspberry Pi configuration change to allow the best performance and prevent the CPU from overheating. Please read the information on the [MagicMirror Wiki](https://github.com/michmich/magicmirror/wiki/configuring-the-raspberry-pi#enable-the-open-gl-driver-to-decrease-electrons-cpu-usage). ℹ️ **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Added - Enabled translation of feelsLike for module currentweather - Added support for on-going calendar events - Added scroll up in fullscreen newsfeed article view - Changed fullscreen newsfeed width from 100% to 100vw (better results) - Added option to calendar module that colors only the symbol instead of the whole line - Added option for new display format in the calendar module with date headers with times/events below. - Ability to fetch compliments from a remote server - Add regex filtering to calendar module - Customize classes for table - Added option to newsfeed module to only log error parsing a news article if enabled - Add update translations for Português Brasileiro ### Changed - Upgrade to Electron 2.0.0. - Remove yarn-or-npm which breaks production builds. - Invoke module suspend even if no dom content. [#1308](https://github.com/MichMich/MagicMirror/issues/1308) ### Fixed - Fixed issue where wind chill could not be displayed in Fahrenheit. [#1247](https://github.com/MichMich/MagicMirror/issues/1247) - Fixed issues where a module crashes when it tries to dismiss a non existing alert. [#1240](https://github.com/MichMich/MagicMirror/issues/1240) - In default module currentWeather/currentWeather.js line 296, 300, self.config.animationSpeed can not be found because the notificationReceived function does not have "self" variable. - Fixed browser-side code to work on the Midori browser. - Fixed issue where heat index was reporting incorrect values in Celsius and Fahrenheit. [#1263](https://github.com/MichMich/MagicMirror/issues/1263) - Fixed weatherforecast to use dt_txt field instead of dt to handle timezones better - Newsfeed now remembers to show the description when `"ARTICLE_LESS_DETAILS"` is called if the user wants to always show the description. [#1282](https://github.com/MichMich/MagicMirror/issues/1282) - `clientonly/*.js` is now linted, and one linting error is fixed - Fix issue #1196 by changing underscore to hyphen in locale id, in align with momentjs. - Fixed issue where heat index and wind chill were reporting incorrect values in Kelvin. [#1263](https://github.com/MichMich/MagicMirror/issues/1263) ### Updated - Updated Italian translation - Updated German translation - Updated Dutch translation ## [2.3.1] - 2018-04-01 ### Fixed - Downgrade electron to 1.4.15 to solve the black screen issue.[#1243](https://github.com/MichMich/MagicMirror/issues/1243) ## [2.3.0] - 2018-04-01 ### Added - Add new settings in compliments module: setting time intervals for morning and afternoon - Add system notification `MODULE_DOM_CREATED` for notifying each module when their Dom has been fully loaded. - Add types for module. - Implement Danger.js to notify contributors when CHANGELOG.md is missing in PR. - Allow to scroll in full page article view of default newsfeed module with gesture events from [MMM-Gestures](https://github.com/thobach/MMM-Gestures) - Changed 'compliments.js' - update DOM if remote compliments are loaded instead of waiting one updateInterval to show custom compliments - Automated unit tests utils, deprecated, translator, cloneObject(lockstrings) - Automated integration tests translations - Add advanced filtering to the excludedEvents configuration of the default calendar module - New currentweather module config option: `showFeelsLike`: Shows how it actually feels like. (wind chill or heat index) - New currentweather module config option: `useKMPHwind`: adds an option to see wind speed in Kmph instead of just m/s or Beaufort. - Add dc:date to parsing in newsfeed module, which allows parsing of more rss feeds. ### Changed - Add link to GitHub repository which contains the respective Dockerfile. - Optimized automated unit tests cloneObject, cmpVersions - Update notifications use now translation templates instead of normal strings. - Yarn can be used now as an installation tool - Changed Electron dependency to v1.7.13. ### Fixed - News article in fullscreen (iframe) is now shown in front of modules. - Forecast respects maxNumberOfDays regardless of endpoint. - Fix exception on translation of objects. ## [2.2.2] - 2018-01-02 ### Added - Add missing `package-lock.json`. ### Changed - Changed Electron dependency to v1.7.10. ## [2.2.1] - 2018-01-01 ### Fixed - Fixed linting errors. ## [2.2.0] - 2018-01-01 **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Changed - Calender week is now handled with a variable translation in order to move number language specific. - Reverted the Electron dependency back to 1.4.15 since newer version don't seem to work on the Raspberry Pi very well. ### Added - Add option to use [Nunjucks](https://mozilla.github.io/nunjucks/) templates in modules. (See `helloworld` module as an example.) - Add Bulgarian translations for MagicMirror² and Alert module. - Add graceful shutdown of modules by calling `stop` function of each `node_helper` on SIGINT before exiting. - Link update subtext to Github diff of current version versus tracking branch. - Add Catalan translation. - Add ability to filter out newsfeed items based on prohibited words found in title (resolves #1071) - Add options to truncate description support of a feed in newsfeed module - Add reloadInterval option for particular feed in newsfeed module - Add no-cache entries of HTTP headers in newsfeed module (fetcher) - Add Czech translation. - Add option for decimal symbols other than the decimal point for temperature values in both default weather modules: WeatherForecast and CurrentWeather. ### Fixed - Fixed issue with calendar module showing more than `maximumEntries` allows - WeatherForecast and CurrentWeather are now using HTTPS instead of HTTP - Correcting translation for Indonesian language - Fix issue where calendar icons wouldn't align correctly ## [2.1.3] - 2017-10-01 **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Changed - Remove Roboto fonts files inside `fonts` and these are installed by npm install command. ### Added - Add `clientonly` script to start only the electron client for a remote server. - Add symbol and color properties of event when `CALENDAR_EVENTS` notification is broadcasted from `default/calendar` module. - Add `.vscode/` folder to `.gitignore` to keep custom Visual Studio Code config out of git. - Add unit test the capitalizeFirstLetter function of newsfeed module. - Add new unit tests for function `shorten` in calendar module. - Add new unit tests for function `getLocaleSpecification` in calendar module. - Add unit test for js/class.js. - Add unit tests for function `roundValue` in currentweather module. - Add test e2e showWeek feature in spanish language. - Add warning Log when is used old authentication method in the calendar module. - Add test e2e for helloworld module with default config text. - Add ability for `currentweather` module to display indoor humidity via INDOOR_HUMIDITY notification. - Add Welsh (Cymraeg) translation. - Add Slack badge to Readme. ### Updated - Changed 'default.js' - listen on all attached interfaces by default. - Add execution of `npm list` after the test are ran in Travis CI. - Change hooks for the vendors e2e tests. - Add log when clientonly failed on starting. - Add warning color when are using full ip whitelist. - Set version of the `express-ipfilter` on 0.3.1. ### Fixed - Fixed issue with incorrect alignment of analog clock when displayed in the center column of the MM. - Fixed ipWhitelist behaviour to make empty whitelist ([]) allow any and all hosts access to the MM. - Fixed issue with calendar module where 'excludedEvents' count towards 'maximumEntries'. - Fixed issue with calendar module where global configuration of maximumEntries was not overridden by calendar specific config (see module doc). - Fixed issue where `this.file(filename)` returns a path with two hashes. - Workaround for the WeatherForecast API limitation. ## [2.1.2] - 2017-07-01 ### Changed - Revert Docker related changes in favor of [docker-MagicMirror](https://github.com/bastilimbach/docker-MagicMirror). All Docker images are outsourced. ([#856](https://github.com/MichMich/MagicMirror/pull/856)) - Change Docker base image (Debian + Node) to an arm based distro (AlpineARM + Node) ([#846](https://github.com/MichMich/MagicMirror/pull/846)) - Fix the dockerfile to have it running from the first time. ### Added - Add in option to wrap long calendar events to multiple lines using `wrapEvents` configuration option. - Add test e2e `show title newsfeed` for newsfeed module. - Add task to check configuration file. - Add test check URLs of vendors. - Add test of match current week number on clock module with showWeek configuration. - Add test default modules present modules/default/defaultmodules.js. - Add unit test calendar_modules function capFirst. - Add test for check if exists the directories present in defaults modules. - Add support for showing wind direction as an arrow instead of abbreviation in currentWeather module. - Add support for writing translation functions to support flexible word order - Add test for check if exits the directories present in defaults modules. - Add calendar option to set a separate date format for full day events. - Add ability for `currentweather` module to display indoor temperature via INDOOR_TEMPERATURE notification - Add ability to change the path of the `custom.css`. - Add translation Dutch to Alert module. - Added Romanian translation. ### Updated - Added missing keys to Polish translation. - Added missing key to German translation. - Added better translation with flexible word order to Finnish translation. ### Fixed - Fix instruction in README for using automatically installer script. - Bug of duplicated compliments as described in [here](https://forum.magicmirror.builders/topic/2381/compliments-module-stops-cycling-compliments). - Fix double message about port when server is starting - Corrected Swedish translations for TODAY/TOMORROW/DAYAFTERTOMORROW. - Removed unused import from js/electron.js - Made calendar.js respect config.timeFormat irrespective of locale setting. - Fixed alignment of analog clock when a large calendar is displayed in the same side bar. ## [2.1.1] - 2017-04-01 **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Changed - Add `anytime` group for Compliments module. - Compliments module can use remoteFile without default daytime arrays defined. - Installer: Use init config.js from config.js.sample. - Switched out `rrule` package for `rrule-alt` and fixes in `ical.js` in order to fix calendar issues. ([#565](https://github.com/MichMich/MagicMirror/issues/565)) - Make mouse events pass through the region fullscreen_above to modules below. - Scaled the splash screen down to make it a bit more subtle. - Replace HTML tables with markdown tables in README files. - Added `DAYAFTERTOMORROW`, `UPDATE_NOTIFICATION` and `UPDATE_NOTIFICATION_MODULE` to Finnish translations. - Run `npm test` on Travis automatically. - Show the splash screen image even when is reboot or halted. - Added some missing translation strings in the sv.json file. - Run task jsonlint to check translation files. - Restructured Test Suite. ### Added - Added Docker support (Pull Request [#673](https://github.com/MichMich/MagicMirror/pull/673)). - Calendar-specific support for `maximumEntries`, and ` maximumNumberOfDays`. - Add loaded function to modules, providing an async callback. - Made default newsfeed module aware of gesture events from [MMM-Gestures](https://github.com/thobach/MMM-Gestures) - Add use pm2 for manager process into Installer RaspberryPi script. - Russian Translation. - Afrikaans Translation. - Add postinstall script to notify user that MagicMirror installed successfully despite warnings from NPM. - Init tests using mocha. - Option to use RegExp in Calendar's titleReplace. - Hungarian Translation. - Icelandic Translation. - Add use a script to prevent when is run by SSH session set DISPLAY environment. - Enable ability to set configuration file by the environment variable called MM_CONFIG_FILE. - Option to give each calendar a different color. - Option for colored min-temp and max-temp. - Add test e2e helloworld. - Add test e2e environment. - Add `chai-as-promised` npm module to devDependencies. - Basic set of tests for clock module. - Run e2e test in Travis. - Estonian Translation. - Add test for compliments module for parts of day. - Korean Translation. - Added console warning on startup when deprecated config options are used. - Add option to display temperature unit label to the current weather module. - Added ability to disable wrapping of news items. - Added in the ability to hide events in the calendar module based on simple string filters. - Updated Norwegian translation. - Added hideLoading option for News Feed module. - Added configurable dateFormat to clock module. - Added multiple calendar icon support. - Added tests for Translations, dev argument, version, dev console. - Added test anytime feature compliments module. - Added test ipwhitelist configuration directive. - Added test for calendar module: default, basic-auth, backward compatibility, fail-basic-auth. - Added meta tags to support fullscreen mode on iOS (for server mode) - Added `ignoreOldItems` and `ignoreOlderThan` options to the News Feed module - Added test for MM_PORT environment variable. - Added a configurable Week section to the clock module. ### Fixed - Update .gitignore to not ignore default modules folder. - Remove white flash on boot up. - Added `update` in Raspberry Pi installation script. - Fix an issue where the analog clock looked scrambled. ([#611](https://github.com/MichMich/MagicMirror/issues/611)) - If units is set to imperial, the showRainAmount option of weatherforecast will show the correct unit. - Module currentWeather: check if temperature received from api is defined. - Fix an issue with module hidden status changing to `true` although lock string prevented showing it. - Fix newsfeed module bug (removeStartTags) - Fix when is set MM_PORT environment variable. - Fixed missing animation on `this.show(speed)` when module is alone in a region. ## [2.1.0] - 2016-12-31 **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Added - Finnish translation. - Danish translation. - Turkish translation. - Option to limit access to certain IP addresses based on the value of `ipWhitelist` in the `config.js`, default is access from localhost only (Issue [#456](https://github.com/MichMich/MagicMirror/issues/456)). - Added ability to change the point of time when calendar events get relative. - Add Splash screen on boot. - Add option to show humidity in currentWeather module. - Add VSCode IntelliSense support. - Module API: Add Visibility locking to module system. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules#visibility-locking) for more information. - Module API: Method to overwrite the module's header. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules#getheader) for more information. - Module API: Option to define the minimum MagicMirror version to run a module. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules#requiresversion) for more information. - Calendar module now broadcasts the event list to all other modules using the notification system. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules/default/calendar) for more information. - Possibility to use the the calendar feed as the source for the weather (currentweather & weatherforecast) location data. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules/default/weatherforecast) for more information. - Added option to show rain amount in the weatherforecast default module - Add module `updatenotification` to get an update whenever a new version is available. [See documentation](https://github.com/MichMich/MagicMirror/tree/develop/modules/default/updatenotification) for more information. - Add the ability to set timezone on the date display in the Clock Module - Ability to set date format in calendar module - Possibility to use currentweather for the compliments - Added option `disabled` for modules. - Added option `address` to set bind address. - Added option `onlyTemp` for currentweather module to show show only current temperature and weather icon. - Added option `remoteFile` to compliments module to load compliment array from filesystem. - Added option `zoom` to scale the whole mirror display with a given factor. - Added option `roundTemp` for currentweather and weatherforecast modules to display temperatures rounded to nearest integer. - Added ability set the classes option to compliments module for style and text size of compliments. - Added ability to configure electronOptions - Calendar module: option to hide private events - Add root_path for global vars ### Updated - Modified translations for Frysk. - Modified core English translations. - Updated package.json as a result of Snyk security update. - Improve object instantiation to prevent reference errors. - Improve logger. `Log.log()` now accepts multiple arguments. - Remove extensive logging in newsfeed node helper. - Calendar times are now uniformly capitalized. - Modules are now secure, and Helmet is now used to prevent abuse of the Mirror's API. ### Fixed - Solve an issue where module margins would appear when the first module of a section was hidden. - Solved visual display errors on chrome, if all modules in one of the right sections are hidden. - Global and Module default config values are no longer modified when setting config values. - Hide a region if all modules in a region are hidden. Prevention unwanted margins. - Replaced `electron-prebuilt` package with `electron` in order to fix issues that would happen after 2017. - Documentation of alert module ## [2.0.5] - 2016-09-20 ### Added - Added ability to remove tags from the beginning or end of newsfeed items in 'newsfeed.js'. - Added ability to define "the day after tomorrow" for calendar events (Definition for German and Dutch already included). - Added CII Badge (we are compliant with the CII Best Practices) - Add support for doing http basic auth when loading calendars - Add the ability to turn off and on the date display in the Clock Module ### Fixed - Fix typo in installer. - Add message to unsupported Pi error to mention that Pi Zeros must use server only mode, as ARMv6 is unsupported. Closes #374. - Fix API url for weather API. ### Updated - Force fullscreen when kioskmode is active. - Update the .github templates and information with more modern information. - Update the Gruntfile with a more functional StyleLint implementation. ## [2.0.4] - 2016-08-07 ### Added - Brazilian Portuguese Translation. - Option to enable Kiosk mode. - Added ability to start the app with Dev Tools. - Added ability to turn off the date display in `clock.js` when in analog mode. - Greek Translation ### Fixed - Prevent `getModules()` selectors from returning duplicate entries. - Append endpoints of weather modules with `/` to retrieve the correct data. (Issue [#337](https://github.com/MichMich/MagicMirror/issues/337)) - Corrected grammar in `module.js` from 'suspend' to 'suspended'. - Fixed openweathermap.org URL in config sample. - Prevent currentweather module from crashing when received data object is incorrect. - Fix issue where translation loading prevented the UI start-up when the language was set to 'en'. (Issue [#388](https://github.com/MichMich/MagicMirror/issues/388)) ### Updated - Updated package.json to fix possible vulnerabilities. (Using Snyk) - Updated weathericons - Updated default weatherforecast to work with the new icons. - More detailed error message in case config file couldn't be loaded. ## [2.0.3] - 2016-07-12 ### Added - Add max newsitems parameter to the newsfeed module. - Translations for Simplified Chinese, Traditional Chinese and Japanese. - Polish Translation - Add an analog clock in addition to the digital one. ### Fixed - Edit Alert Module to display title & message if they are provided in the notification (Issue [#300](https://github.com/MichMich/MagicMirror/issues/300)) - Removed 'null' reference from updateModuleContent(). This fixes recent Edge and Internet Explorer browser displays (Issue [#319](https://github.com/MichMich/MagicMirror/issues/319)) ### Changed - Added default string to calendar titleReplace. ## [2.0.2] - 2016-06-05 ### Added - Norwegian Translations (nb and nn) - Portuguese Translation - Swedish Translation ### Fixed - Added reference to Italian Translation. - Added the missing NE translation to all languages. [#344](https://github.com/MichMich/MagicMirror/issues/344) - Added proper User-Agent string to calendar call. ### Changed - Add option to use locationID in weather modules. ## [2.0.1] - 2016-05-18 ### Added - Changelog - Italian Translation ### Changed - Improve the installer by fetching the latest Node.js without any 3rd party interferences. ## [2.0.0] - 2016-05-03 ### Initial release of MagicMirror² It includes (but is not limited to) the following features: - Modular system allowing 3rd party plugins. - An Node/Electron based application taking away the need for external servers or browsers. - A complete development API documentation. - Small cute fairies that kiss you while you sleep. ## [1.0.0] - 2014-02-16 ### Initial release of MagicMirror. This was part of the blogpost: [http://michaelteeuw.nl/post/83916869600/magic-mirror-part-vi-production-of-the](http://michaelteeuw.nl/post/83916869600/magic-mirror-part-vi-production-of-the)
{ "content_hash": "f7f9cb3a93da95d0cef074dbf11eae63", "timestamp": "", "source": "github", "line_count": 702, "max_line_length": 731, "avg_line_length": 58.65242165242165, "alnum_prop": 0.7805411181813766, "repo_name": "n8many/MagicMirror", "id": "0c952791e1fd17a742a7d6b6a4648b20986ac6e2", "size": "41255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "78282" }, { "name": "HTML", "bytes": "2896" }, { "name": "JavaScript", "bytes": "290217" }, { "name": "PHP", "bytes": "4065" }, { "name": "Shell", "bytes": "6756" }, { "name": "TypeScript", "bytes": "1040" } ], "symlink_target": "" }
package util // Flags represents a set of boolean flags as a bit mask. type Flags uint64 const ( FlagNone Flags = 0 ) // HasFlag return true func (fs Flags) HasFlag(f Flags) bool { return fs&f > 0 }
{ "content_hash": "2097815b56ef862e410f42d29b27cbd2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 57, "avg_line_length": 16.692307692307693, "alnum_prop": 0.6589861751152074, "repo_name": "andreasstrack/util", "id": "78664743005139136ddc1d27108e37a38fc4bc74", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flags.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "30462" } ], "symlink_target": "" }
package com.example.scoop.basics.common.time; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; public class Iso8601Formatter { public static SimpleDateFormat create() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return simpleDateFormat; } }
{ "content_hash": "7479a61fd50c3aef3f87b551bc18b3b8", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 104, "avg_line_length": 30.5, "alnum_prop": 0.7423887587822015, "repo_name": "lyft/scoop", "id": "04865dcccff3aea5e31e9c4515b5257b3d01e18c", "size": "427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scoop-basics/src/main/java/com/example/scoop/basics/common/time/Iso8601Formatter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "153059" }, { "name": "Shell", "bytes": "746" } ], "symlink_target": "" }
package com.commonsware.cwac.saferoom.test; import androidx.annotation.NonNull; import com.commonsware.dbtest.ClosedDatabaseTests; import com.commonsware.dbtest.FactoryProvider; public class SafeClosedDatabaseTests extends ClosedDatabaseTests { @NonNull @Override protected FactoryProvider buildFactoryProvider() { return new SafeFactoryProvider(); } }
{ "content_hash": "603c8ce1e978d11b4462d18570bf01a2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 29.153846153846153, "alnum_prop": 0.7941952506596306, "repo_name": "commonsguy/cwac-saferoom", "id": "77d66592294f864f7065aca86418534a785ce2a4", "size": "379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "saferoom/src/androidTest/java/com/commonsware/cwac/saferoom/test/SafeClosedDatabaseTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "120283" } ], "symlink_target": "" }
<?php /** * sfI18N wraps the core i18n classes for a symfony context. * * @package symfony * @subpackage i18n * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: sfI18N.class.php 29520 2010-05-19 11:47:08Z fabien $ */ class sfI18N { protected $configuration = null, $dispatcher = null, $cache = null, $options = array(), $culture = 'en', $messageSource = null, $messageFormat = null; /** * Class constructor. * * @see initialize() */ public function __construct(sfApplicationConfiguration $configuration, sfCache $cache = null, $options = array()) { $this->initialize($configuration, $cache, $options); } /** * Initializes this class. * * Available options: * * * culture: The culture * * source: The i18n source (XLIFF by default) * * debug: Whether to enable debug or not (false by default) * * database: The database name (default by default) * * untranslated_prefix: The prefix to use when a message is not translated * * untranslated_suffix: The suffix to use when a message is not translated * * @param sfApplicationConfiguration $configuration A sfApplicationConfiguration instance * @param sfCache $cache A sfCache instance * @param array $options An array of options */ public function initialize(sfApplicationConfiguration $configuration, sfCache $cache = null, $options = array()) { $this->configuration = $configuration; $this->dispatcher = $configuration->getEventDispatcher(); $this->cache = $cache; if (isset($options['culture'])) { $this->setCulture($options['culture']); unset($options['culture']); } $this->options = array_merge(array( 'source' => 'XLIFF', 'debug' => false, 'database' => 'default', 'untranslated_prefix' => '[T]', 'untranslated_suffix' => '[/T]', ), $options); $this->dispatcher->connect('user.change_culture', array($this, 'listenToChangeCultureEvent')); if($this->isMessageSourceFileBased($this->options['source'])) { $this->dispatcher->connect('controller.change_action', array($this, 'listenToChangeActionEvent')); } } /** * Returns the initialization options * * @return array The options used to initialize sfI18n */ public function getOptions() { return $this->options; } /** * Returns the configuration instance. * * @return sfApplicationConfiguration An sfApplicationConfiguration instance */ public function getConfiguration() { return $this->configuration; } /** * Sets the message source. * * @param mixed $dirs An array of i18n directories if message source is a sfMessageSource_File subclass, null otherwise * @param string $culture The culture */ public function setMessageSource($dirs, $culture = null) { if (null === $dirs) { $this->messageSource = $this->createMessageSource(); } else { $this->messageSource = sfMessageSource::factory('Aggregate', array_map(array($this, 'createMessageSource'), $dirs)); } if (null !== $this->cache) { $this->messageSource->setCache($this->cache); } if (null !== $culture) { $this->setCulture($culture); } else { $this->messageSource->setCulture($this->culture); } $this->messageFormat = null; } /** * Returns a new message source. * * @param mixed $dir An array of i18n directories to create a XLIFF or gettext message source, null otherwise * * @return sfMessageSource A sfMessageSource object */ public function createMessageSource($dir = null) { return sfMessageSource::factory($this->options['source'], self::isMessageSourceFileBased($this->options['source']) ? $dir : $this->options['database']); } /** * Gets the current culture for i18n format objects. * * @return string The culture */ public function getCulture() { return $this->culture; } /** * Sets the current culture for i18n format objects. * * @param string $culture The culture */ public function setCulture($culture) { $this->culture = $culture; // change user locale for formatting, collation, and internal error messages setlocale(LC_ALL, 'en_US.utf8', 'en_US.UTF8', 'en_US.utf-8', 'en_US.UTF-8'); setlocale(LC_COLLATE, $culture.'.utf8', $culture.'.UTF8', $culture.'.utf-8', $culture.'.UTF-8'); setlocale(LC_CTYPE, $culture.'.utf8', $culture.'.UTF8', $culture.'.utf-8', $culture.'.UTF-8'); setlocale(LC_MONETARY, $culture.'.utf8', $culture.'.UTF8', $culture.'.utf-8', $culture.'.UTF-8'); setlocale(LC_TIME, $culture.'.utf8', $culture.'.UTF8', $culture.'.utf-8', $culture.'.UTF-8'); if ($this->messageSource) { $this->messageSource->setCulture($culture); $this->messageFormat = null; } } /** * Gets the message source. * * @return sfMessageSource A sfMessageSource object */ public function getMessageSource() { if (!isset($this->messageSource)) { $dirs = ($this->isMessageSourceFileBased($this->options['source'])) ? $this->configuration->getI18NGlobalDirs() : null; $this->setMessageSource($dirs, $this->culture); } return $this->messageSource; } /** * Gets the message format. * * @return sfMessageFormat A sfMessageFormat object */ public function getMessageFormat() { if (!isset($this->messageFormat)) { $this->messageFormat = new sfMessageFormat($this->getMessageSource(), sfConfig::get('sf_charset')); if ($this->options['debug']) { $this->messageFormat->setUntranslatedPS(array($this->options['untranslated_prefix'], $this->options['untranslated_suffix'])); } } return $this->messageFormat; } /** * Gets the translation for the given string * * @param string $string The string to translate * @param array $args An array of arguments for the translation * @param string $catalogue The catalogue name * * @return string The translated string */ public function __($string, $args = array(), $catalogue = 'messages') { return $this->getMessageFormat()->format($string, $args, $catalogue); } /** * Gets a country name. * * @param string $iso The ISO code * @param string $culture The culture for the translation * * @return string The country name */ public function getCountry($iso, $culture = null) { $c = sfCultureInfo::getInstance(null === $culture ? $this->culture : $culture); $countries = $c->getCountries(); return (array_key_exists($iso, $countries)) ? $countries[$iso] : ''; } /** * Gets a native culture name. * * @param string $culture The culture * * @return string The culture name */ public function getNativeName($culture) { return sfCultureInfo::getInstance($culture)->getNativeName(); } /** * Returns a timestamp from a date with time formatted with a given culture. * * @param string $dateTime The formatted date with time as string * @param string $culture The culture * * @return integer The timestamp */ public function getTimestampForCulture($dateTime, $culture = null) { list($day, $month, $year) = $this->getDateForCulture($dateTime, null === $culture ? $this->culture : $culture); list($hour, $minute) = $this->getTimeForCulture($dateTime, null === $culture ? $this->culture : $culture); return null === $day ? null : mktime($hour, $minute, 0, $month, $day, $year); } /** * Returns the day, month and year from a date formatted with a given culture. * * @param string $date The formatted date as string * @param string $culture The culture * * @return array An array with the day, month and year */ public function getDateForCulture($date, $culture = null) { if (!$date) { return null; } $dateFormatInfo = @sfDateTimeFormatInfo::getInstance(null === $culture ? $this->culture : $culture); $dateFormat = $dateFormatInfo->getShortDatePattern(); // We construct the regexp based on date format $dateRegexp = preg_replace('/[dmy]+/i', '(\d+)', preg_quote($dateFormat)); // We parse date format to see where things are (m, d, y) $a = array( 'd' => strpos($dateFormat, 'd'), 'm' => strpos($dateFormat, 'M'), 'y' => strpos($dateFormat, 'y'), ); $tmp = array_flip($a); ksort($tmp); $i = 0; $c = array(); foreach ($tmp as $value) $c[++$i] = $value; $datePositions = array_flip($c); // We find all elements if (preg_match("~$dateRegexp~", $date, $matches)) { // We get matching timestamp return array($matches[$datePositions['d']], $matches[$datePositions['m']], $matches[$datePositions['y']]); } else { return null; } } /** * Returns the hour, minute from a date formatted with a given culture. * * @param string $time The formatted date as string * @param string $culture The culture * * @return array An array with the hour and minute */ public function getTimeForCulture($time, $culture = null) { if (!$time) return 0; $culture = null === $culture ? $this->culture : $culture; $timeFormatInfo = @sfDateTimeFormatInfo::getInstance($culture); $timeFormat = $timeFormatInfo->getShortTimePattern(); // We construct the regexp based on time format $timeRegexp = preg_replace(array('/[hm]+/i', '/a/'), array('(\d+)', '(\w+)'), preg_quote($timeFormat)); // We parse time format to see where things are (h, m) $timePositions = array( 'h' => strpos($timeFormat, 'H') !== false ? strpos($timeFormat, 'H') : strpos($timeFormat, 'h'), 'm' => strpos($timeFormat, 'm'), 'a' => strpos($timeFormat, 'a') ); asort($timePositions); $i = 0; // normalize positions to 0, 1, ... // positions that don't exist in the pattern remain false foreach ($timePositions as $key => $value) { if ($value !== false) { $timePositions[$key] = ++$i; } } // We find all elements if (preg_match("~$timeRegexp~", $time, $matches)) { // repect am/pm setting if present if ($timePositions['a'] !== false) { if (strcasecmp($matches[$timePositions['a']], $timeFormatInfo->getAMDesignator()) == 0) { $hour = $matches[$timePositions['h']]; } else if (strcasecmp($matches[$timePositions['a']], $timeFormatInfo->getPMDesignator()) == 0) { $hour = $matches[$timePositions['h']] + 12; } else { // am/pm marker is invalid // return null; would be the preferred solution but this might break a lot of code $hour = $matches[$timePositions['h']]; } } else { $hour = $matches[$timePositions['h']]; } // We get matching timestamp return array($hour, $matches[$timePositions['m']]); } else { return null; } } /** * Returns true if messages are stored in a file. * * @param string $source The source name * * @return Boolean true if messages are stored in a file, false otherwise */ static public function isMessageSourceFileBased($source) { $class = 'sfMessageSource_'.$source; return class_exists($class) && is_subclass_of($class, 'sfMessageSource_File'); } /** * Listens to the user.change_culture event. * * @param sfEvent $event An sfEvent instance * */ public function listenToChangeCultureEvent(sfEvent $event) { // change the message format object with the new culture $this->setCulture($event['culture']); } /** * Listens to the controller.change_action event. * * @param sfEvent $event An sfEvent instance * */ public function listenToChangeActionEvent(sfEvent $event) { // change message source directory to our module $this->setMessageSource($this->configuration->getI18NDirs($event['module'])); } }
{ "content_hash": "7d0226ce887fcb6bec261375034759c2", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 156, "avg_line_length": 29.76923076923077, "alnum_prop": 0.588520867590635, "repo_name": "studiodev/archives", "id": "a754cdb3533ab409302063ace5fa28d31cd42318", "size": "13031", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "2012 - Portfolio V5/lib/vendor/symfony/lib/i18n/sfI18N.class.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "278127" }, { "name": "ApacheConf", "bytes": "17574" }, { "name": "CSS", "bytes": "947736" }, { "name": "ColdFusion", "bytes": "42028" }, { "name": "HTML", "bytes": "9820794" }, { "name": "Java", "bytes": "30831" }, { "name": "JavaScript", "bytes": "7757772" }, { "name": "Lasso", "bytes": "24527" }, { "name": "PHP", "bytes": "21467673" }, { "name": "Perl", "bytes": "39266" }, { "name": "Python", "bytes": "26247" }, { "name": "Smarty", "bytes": "196757" } ], "symlink_target": "" }
int main(int argc, char *argv[]) { @autoreleasepool { int retVal = UIApplicationMain(argc, argv, nil, nil); return retVal; } }
{ "content_hash": "7927c213512e68f9266b036ed9f7f836", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 61, "avg_line_length": 22.285714285714285, "alnum_prop": 0.5705128205128205, "repo_name": "spectralmind/sonarflow-ios", "id": "7beaf47d59f5e4aef74adcc2f2739f487b707913", "size": "320", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sonarflow/sonarflow/shared/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "95" }, { "name": "HTML", "bytes": "31708" }, { "name": "Objective-C", "bytes": "1360140" }, { "name": "Shell", "bytes": "3192" } ], "symlink_target": "" }
package AliTV; use 5.010000; use strict; use warnings; use parent 'AliTV::Base'; use POSIX qw(ceil floor); use YAML; use Hash::Merge; use AliTV::Genome; use AliTV::Tree; use File::Copy; use JSON; sub _initialize { my $self = shift; # initialize the yml settings using the default config $self->{_yml_import} = $self->get_default_settings(); $self->{_file} = undef; $self->{_project} = undef; $self->{_genomes} = {}; $self->{_linkcounter} = 0; $self->{_linkfeaturecounter} = 0; $self->{_links} = {}; $self->{_max_total_seq_length_included_into_json} = 1000000; $self->{_ticks_every_num_of_bases} = undef; $self->{_links_min_len} = 1000000000; # just a huge value $self->{_links_max_len} = 0; # just a tiny value $self->{_links_max_id} = 0; # just a zero $self->{_links_min_id} = 100; # just the maximum $self->{_tree} = undef; } =pod =head1 Method run =head2 run the generation script =cut sub run { my $self = shift; ################################################################# # # Import genomes # ################################################################# # Import the given genomes $self->_import_genomes(); ################################################################# # # Create uniq sequence names # ################################################################# # if the names are already uniq, the sequences names will be used # as unique names, otherwise the sequences will be numbered to # generate unique names $self->_make_and_set_uniq_seq_names(); ################################################################# # # Create sequence set # ################################################################# # Prepare a sequence set for the alignment # determine the module to load from the alignment program my $alignment_module = sprintf('AliTV::Alignment::%s', $self->{_yml_import}{alignment}{program}); unless (eval "require $alignment_module") { $self->_logdie("Unable to load alignment module '$alignment_module'"); } my $alignment_parameter = $self->{_yml_import}{alignment}{parameter}; my $aln_obj = "$alignment_module"->new(-parameters => $alignment_parameter, -callback => sub{ $self->_import_links(@_); } ); $aln_obj->run($self->_generate_seq_set()); $aln_obj->export_to_genome(); ################################################################# # # Import tree # ################################################################# if (exists $self->{_yml_import}{tree} && defined $self->{_yml_import}{tree}) { my $tree_obj = AliTV::Tree->new(-file => ($self->{_yml_import}{tree})); $tree_obj->ladderize(); $tree_obj->balance_node_depth(); $self->{_tree} = $tree_obj->tree_2_json_structure(); # store the order $self->{_tree_genome_order} = $tree_obj->get_genome_order(); } my $json_text = $self->get_json(); return $json_text; } sub get_json { my $self = shift; my %data = (); $data{data}{links} = $self->{_links}; my $features = {}; my $chromosomes = {}; # cycle though all genomes end extract feature and chromosome information foreach my $genome ( values %{$self->{_genomes}} ) { $features = $genome->get_features($features); $chromosomes = $genome->get_chromosomes($chromosomes); } # collect the sequence length of all chromosomes my @chromosome_length = sort { $a <=> $b } map {$chromosomes->{$_}{length}} (keys %{$chromosomes}); # calculate the complete sequence length my $complete_seq_length = 0; foreach (@chromosome_length) { $complete_seq_length += $_; } # if the sequence length is longer than (default) 1 Mb, skip all sequence information from the JSON file if ($complete_seq_length > $self->maximum_seq_length_in_json()) { $self->_info(sprintf("Number of bases (%d) is longer than the maximum allowed (%d), therefore sequences will be excluded from JSON file", $complete_seq_length, $self->maximum_seq_length_in_json())); foreach (keys %{$chromosomes}) { $chromosomes->{$_}{seq} = ""; } } my $tick_distance = $self->_calculate_tick_distance(\@chromosome_length); $self->ticks_every_num_of_bases($tick_distance); $self->_info(sprintf("Ticks will be drawn every %d basepair", $self->ticks_every_num_of_bases())); $data{data}{features} = $features; $data{data}{karyo}{chromosomes} = $chromosomes; $data{data}{tree} = $self->{_tree}; $data{conf} = { 'circular' => { 'tickSize' => 5 }, 'features' => { 'fallbackStyle' => { 'color' => '#787878', 'form' => 'rect', 'height' => 30, 'visible' => JSON::false }, 'showAllFeatures' => JSON::false, 'supportedFeatures' => { }, }, 'graphicalParameters' => { 'buttonWidth' => 90, 'canvasHeight' => 900, 'canvasWidth' => 900, 'fade' => 0.1, 'genomeLabelWidth' => 200, 'karyoDistance' => 5000, 'karyoHeight' => 30, 'linkKaryoDistance' => 20, 'tickDistance' => $self->ticks_every_num_of_bases(), 'tickLabelFrequency' => 10, 'treeWidth' => 200 }, 'labels' => { 'chromosome' => { 'showChromosomeLabels' => JSON::false }, 'features' => { 'showFeatureLabels' => JSON::false }, 'genome' => { 'color' => '#000000', 'showGenomeLabels' => JSON::true, 'size' => 25 }, 'showAllLabels' => JSON::false, 'ticks' => { 'color' => '#000000', 'showTickLabels' => JSON::true, 'showTicks' => JSON::true, 'size' => 10 } }, 'layout' => 'linear', 'linear' => { 'drawAllLinks' => JSON::false, 'endLineColor' => '#1d91c0', 'hideHalfVisibleLinks' => JSON::false, 'startLineColor' => '#1d91c0' }, 'maxLinkIdentity' => 100, 'maxLinkIdentityColor' => '#1DAD0A', 'maxLinkLength' => 5000, 'midLinkIdentity' => 85, 'midLinkIdentityColor' => '#FFEE05', 'minLinkIdentity' => 70, 'minLinkIdentityColor' => '#D21414', 'minLinkLength' => 100, 'offset' => { 'distance' => 1000, 'isSet' => JSON::false }, 'tree' => { 'drawTree' => JSON::true, 'orientation' => 'left' } }; # add all features but links foreach my $feat (grep {$_ ne $self->_link_feature_name()} (keys %{$data{data}{features}})) { if (exists $self->{_yml_import}{features}{$feat}) { $data{conf}{features}{supportedFeatures}{$feat}{color} = $self->{_yml_import}{features}{$feat}{color}; $data{conf}{features}{supportedFeatures}{$feat}{form} = $self->{_yml_import}{features}{$feat}{form}; $data{conf}{features}{supportedFeatures}{$feat}{height} = $self->{_yml_import}{features}{$feat}{height}; $data{conf}{features}{supportedFeatures}{$feat}{visible} = ($self->{_yml_import}{features}{$feat}{visible}) ? JSON::true : JSON::false; } else { $data{conf}{features}{supportedFeatures}{$feat} = { color => '#EBCE20', form => 'rect', height => 30, visible => JSON::true } } } $data{filters} = { 'features' => { 'invisibleFeatures' => {} }, 'karyo' => { 'chromosomes' => {}, 'genome_order' => [], 'order' => [] }, 'links' => { 'invisibleLinks' => {}, 'maxLinkIdentity' => ceil($self->{_links_max_id}), 'maxLinkLength' => $self->{_links_max_len}+0, 'minLinkIdentity' => floor($self->{_links_min_id}), 'minLinkLength' => $self->{_links_min_len}+0 }, 'onlyShowAdjacentLinks' => JSON::true, 'showAllChromosomes' => JSON::false, 'showIntraGenomeLinks' => JSON::false, 'skipChromosomesWithoutLinks' => JSON::false, 'skipChromosomesWithoutVisibleLinks' => JSON::false }; # adding information about the chromosomes # first sort the chromosomes my @chromosomelist_sorted = sort { $data{data}{karyo}{chromosomes}{$a}{genome_id} cmp $data{data}{karyo}{chromosomes}{$b}{genome_id} || $data{data}{karyo}{chromosomes}{$a}{length} <=> $data{data}{karyo}{chromosomes}{$b}{length} } keys %{$data{data}{karyo}{chromosomes}}; # set each chromosome to visible foreach my $chromosome (@chromosomelist_sorted) { $data{filters}{karyo}{chromosomes}{$chromosome} = { visible => JSON::true, reverse => JSON::false }; } $data{filters}{karyo}{order} = \@chromosomelist_sorted; # need to define a genome order # easy to implement: alphabetically sorted or if a tree exists use the order from the tree if (exists $self->{_tree_genome_order}) { # ordered by the tree $data{filters}{karyo}{genome_order} = $self->{_tree_genome_order}; } else { # alphabetically sorted my %genomes = map { $data{data}{karyo}{chromosomes}{$_}{genome_id} => 1 } (keys %{$data{data}{karyo}{chromosomes}}); $data{filters}{karyo}{genome_order} = [sort keys %genomes]; } return JSON->new->utf8(1)->canonical->encode(\%data); } sub _import_links { my $self = shift; my ($entry) = @_; my @linkdat = (); # find the correct sequence foreach my $seq ( @{$entry->{seqs}} ) { my $seqname = $seq->{id}; my $corr_genome = undef; foreach my $curr_genome ( values %{$self->{_genomes}} ) { if ($curr_genome->seq_exists($seqname)) #exists $self->{_genomes}{$genome}{_seq}{$seqname}) { # genome with sequence with correct name was found # add the feature my $linkfeature_name = sprintf("linkfeature%06d", ++$self->{_linkfeaturecounter}); my $returned_linkfeature_name = $curr_genome->_store_feature($self->_link_feature_name(), $seqname, $seq->{start}+0, $seq->{end}+0, $seq->{strand}, $linkfeature_name); push(@linkdat, {genome => $curr_genome->name(), feature => $returned_linkfeature_name}); last; } } } # add a new link to the link-list $self->_logdie("unable to create features") unless (@linkdat == 2); $self->{_linkcounter}++; my $genome1 = $linkdat[0]{genome}; my $genome2 = $linkdat[1]{genome}; # sort the genomes alphabetically if ($genome2 lt $genome1) { ($genome1, $genome2) = ($genome2, $genome1); } my $linkname = sprintf("link%06d", $self->{_linkcounter}); my $dataset = { source => $linkdat[0]{feature}, identity => sprintf("%.2f", $entry->{identity})+0, target => $linkdat[1]{feature} }; # check if an existing link exists my $link_already_existing = 0; # search the links foreach my $existing_linkname (keys %{$self->{_links}{$genome1}{$genome2}}) { my $existing_dataset = $self->{_links}{$genome1}{$genome2}{$existing_linkname}; if ( $existing_dataset->{source} eq $dataset->{source} && $existing_dataset->{identity} eq $dataset->{identity} && $existing_dataset->{target} eq $dataset->{target} ) { $self->_debug("Existing link will be skipped"); $link_already_existing++; } } # add the new link if not already existing unless ($link_already_existing) { $self->{_links}{$genome1}{$genome2}{$linkname} = $dataset; } # track minimum and maximum link length and identity if ($self->{_links_min_len} > $entry->{len}) { $self->{_links_min_len} = $entry->{len}+0; } if ($self->{_links_max_len} < $entry->{len}) { $self->{_links_max_len} = $entry->{len}+0; } if ($self->{_links_min_id} > $entry->{identity}) { $self->{_links_min_id} = $entry->{identity}+0; } if ($self->{_links_max_id} < $entry->{identity}) { $self->{_links_max_id} = $entry->{identity}+0; } } =pod =head2 Method $alitv_obj->project() This methods returns the name of the current project. If an additional parameter is given, this value will be set as new project name. Those names are allowed to contain only characters from [A-Za-z0-9_]. In case they contain other characters, an exception will be raised. =cut sub project { my $self = shift; # is another parameter given? if (@_) { $self->{_project} = shift; if ($self->{_project} =~ /[^A-Za-z0-9_]/) { $self->_logdie('Only characters from character class [A-Za-z0-9_] are allowed in project name'); } } return $self->{_project}; } sub file { my $self = shift; # is another parameter given? if (@_) { $self->{_file} = shift; my $default = $self->get_default_settings(); # try to import the YAML file my $settings; eval { $settings = YAML::LoadFile($self->{_file}) }; if ($@) { $self->_logdie("Unable to import the YAML file '".$self->{_file}."': $@"); } Hash::Merge::set_behavior( 'RIGHT_PRECEDENT' ); if (exists $settings->{alignment}) { delete $default->{alignment}; } $self->{_yml_import} = Hash::Merge::merge($default, $settings); } return $self->{_file}; } sub _import_genomes { my $self = shift; # check if a file attribute is set and not undef unless (exists $self->{_file} && defined $self->{_file}) { $self->_logdie("No file attribute exists"); } foreach my $curr_genome (@{$self->{_yml_import}{genomes}}) { my $genome = AliTV::Genome->new(%{$curr_genome}); # check that the genome name is not already existing if (exists $self->{_genomes}{$genome->name()}) { $self->_logdie(sprintf("Genome-ID '%s' is not uniq", $genome->name())); } $self->{_genomes}{$genome->name()} = $genome; } } sub get_default_settings { my $default_yml_content = ' --- # this is the default yml file alignment: program: lastz parameter: - "--format=maf" - "--noytrim" - "--ambiguous=iupac" - "--gapped" - "--strand=both" '; # try to import the default YAML my $default = YAML::Load($default_yml_content); return $default; } sub _make_and_set_uniq_seq_names { my $self = shift; # get a list of all sequence names my @all_seq_ids = (); foreach my $genome_id (sort keys %{$self->{_genomes}}) { push(@all_seq_ids, map { {name => $_, genome => $genome_id} } (sort $self->{_genomes}{$genome_id}->get_seq_names())); } # check if the sequence names are uniq my %seen = (); foreach my $curr (@all_seq_ids) { $seen{$curr->{name}}++; } # if the number of keys is equal to the number of total sequences, # they should be uniq, but we need to guarantee, that the name # contains only alphanumeric or "word" characters and that the # name is not longer than $max_seq_length characters my $max_seq_length = 8; my $uniq_names = ((keys %seen) == @all_seq_ids); my $only_word_characters = ((grep {$_->{name} =~ /\W/} @all_seq_ids) == 0); my $comply_maximum_id_length = ((grep {length($_->{name}) > $max_seq_length} @all_seq_ids) == 0); if ( $uniq_names && $only_word_characters && $comply_maximum_id_length) { # sequence names are uniq and can be used as uniq names @all_seq_ids = map { {name => $_->{name}, genome => $_->{genome}, uniq_name => $_->{name}} } (@all_seq_ids); } elsif (! $uniq_names) { $self->_info("Sequence names are not unique and will be replaced by unique sequence names\n"); } elsif (! $only_word_characters) { $self->_info( sprintf("Sequence names contain non-word-characters and will be replaced by unique sequence names. Failing sequence names are: %s\n", join(", ", map {"'$_->{name}'"} grep {$_->{name} =~ /\W/} @all_seq_ids ) ) ); } elsif (! $comply_maximum_id_length) { $self->_info( sprintf("Sequence names are longer then maximum allowed length (%d characters) and will be replaced by unique sequence names. Failing sequence names are: %s\n", $max_seq_length, join(", ", map {"'$_->{name}'"} grep {length($_->{name}) > $max_seq_length} @all_seq_ids ) ) ); } else { $self->_logdie("Should never be reached"); # uncoverable statement } # sequences names are not uniq! Therefore, generate new names unless ( $uniq_names && $only_word_characters && $comply_maximum_id_length) { my $counter = 0; @all_seq_ids = map { {name => $_->{name}, genome => $_->{genome}, uniq_name => "seq".$counter++ } } (@all_seq_ids); } # set the new uniq names for each genome foreach my $genome_id (keys %{$self->{_genomes}}) { my @set_list = map { $_->{uniq_name} => $_->{name} } grep {$_->{genome} eq $genome_id } @all_seq_ids; $self->{_genomes}{$genome_id}->set_uniq_seq_names(@set_list); } $self->_write_mapping_file(\@all_seq_ids); } =pod =head2 Method $alitv_obj->_write_mapping_file() This internal method stores a file containing old and new sequence names for the complete sequence set. If the file already exists, it will be backed up. If this is not possible an exception will be raised. =cut sub _write_mapping_file { my $self = shift; unless (@_) { $self->_logdie("Need to call _write_mapping_file() with an array reference as parameter"); } my $ref_to_seqs = shift; unless (ref($ref_to_seqs) eq "ARRAY") { $self->_logdie("Need to call _write_mapping_file() with an array reference as parameter but found other type"); } if ($self->project()) { my $outputfilename = $self->project().".map"; if (-e $outputfilename) { $self->_logwarn("The file '$outputfilename' exists. Therefore, a backup will be created named '$outputfilename".'.bak'."' and the old file will overwritten."); if (-e $outputfilename.".bak") { $self->_logdie("Unable to backup the file '$outputfilename' to '$outputfilename".".bak' due to it already exists!"); } copy($outputfilename, $outputfilename.".bak") || $self->_logdie("Unable to backup the file '$outputfilename' to '$outputfilename".".bak': $!"); } open(FH, ">", $outputfilename) || $self->_logdie("Unable to open file '$outputfilename' for writing: $!"); print FH "#", join("\t", qw(genome old_name new_name)), "\n"; foreach my $seq (@{$ref_to_seqs}) { print FH join("\t", ($seq->{genome}, $seq->{name}, $seq->{uniq_name})), "\n"; } close(FH) || $self->_logdie("Unable to open file '$outputfilename' for writing: $!"); } } sub _generate_seq_set { my $self = shift; my @seqs = (); # generate a list od all sequences foreach my $genome_id (keys %{$self->{_genomes}}) { my @new_seqs = $self->{_genomes}{$genome_id}->get_sequences(); push(@seqs, @new_seqs); } # finally, sort the sequences by id and sequence @seqs = sort {$a->id() cmp $b->id() || $a->seq() cmp $b->seq()} (@seqs); # store the sequence set as attribute $self->{_seq_set} = \@seqs; # and return it return $self->{_seq_set}; } =pod =head3 C<$obj-E<gt>maximum_seq_length_in_json()> =head4 I<Parameters> If one single integer value is provided, it will be used as threshold for the maximal sequence length inside the produced JSON file. =head4 I<Output> Returns the current value of the maximal sequence length inside the produced JSON file. =head4 I<Description> none =cut sub maximum_seq_length_in_json { my $self = shift; if (@_) { my $parameter = shift; unless ($parameter =~ /^\d+$/) { $self->_logdie("Parameter needs to be an unsigned integer value"); } $self->{_max_total_seq_length_included_into_json} = $parameter; } return $self->{_max_total_seq_length_included_into_json}; } =pod =head3 C<$obj-E<gt>ticks_every_num_of_bases()> =head4 I<Parameters> If one single integer value is provided, it will be determine how many ticks are drawn. =head4 I<Output> Returns the current value of the class value. =head4 I<Description> none =cut sub ticks_every_num_of_bases { my $self = shift; if (@_) { my $parameter = shift; unless ($parameter =~ /^\d+$/) { $self->_logdie("Parameter needs to be an unsigned integer value"); } $self->{_ticks_every_num_of_bases} = $parameter; } return defined $self->{_ticks_every_num_of_bases} ? int($self->{_ticks_every_num_of_bases}) : undef; } =pod =head3 C<$obj-E<gt>_calculate_tick_distance()> =head4 I<Parameters> Requires a reference to a list of sequence length. =head4 I<Output> Returns the calculated value =head4 I<Description> The value for tick distance is calculated as follows: We want to achieve at least 20 ticks in the sequence with the median length. The number of bases should be a power of ten. =cut sub _calculate_tick_distance { my $self = shift; unless (@_ == 1 && ref($_[0]) eq "ARRAY") { $self->_logdie("Need to provide a reference to an array of integers as parameter"); } my $list = shift; @{$list} = sort {$a <=> $b} @{$list}; # calculate the length of the longest chromosome my $longest_chromosome_length = $list->[@{$list}-1]; # inside the median chromosome, we want to have at least 20 Ticks, but we want to have a power of 10 my $ticks_every_num_of_bases = int(log($longest_chromosome_length/20)/log(10)); $ticks_every_num_of_bases = 10**$ticks_every_num_of_bases; return $ticks_every_num_of_bases; } 1; =pod =head1 NAME AliTV - Perl class for the alitv script which generates the JSON input for AliTV =head1 SYNOPSIS use AliTV; =head1 DESCRIPTION The class AliTV implements the functionality for the alitv.pl script. =head1 SEE ALSO =head1 AUTHOR Frank FE<246>ster E<lt>foersterfrank@gmx.deE<gt> =head1 COPYRIGHT AND LICENSE See the F<LICENCE> file for information about the licence. =cut
{ "content_hash": "65b4a7e153d85531abeb3f2e26d67220", "timestamp": "", "source": "github", "line_count": 806, "max_line_length": 199, "avg_line_length": 27.450372208436725, "alnum_prop": 0.5741468926553672, "repo_name": "greatfireball/AliTV-perl-interface", "id": "57d143363b45df8a11b1cc1036a9692d2bab0785", "size": "22125", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/AliTV.pm", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "35517" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Enkodi remote controller</title> <script> (function() { if (!process.env.HOT) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = './dist/style.css'; document.write(link.outerHTML); } }()); </script> </head> <body> <div id="root"></div> <script> { const script = document.createElement('script'); const port = process.env.PORT || 3000; script.src = (process.env.HOT) ? 'http://localhost:' + port + '/dist/bundle.js' : './dist/bundle.js'; document.write(script.outerHTML); } </script> </body> </html>
{ "content_hash": "9e9414ff92daa1b65b732c5fbb3b26d7", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 58, "avg_line_length": 23.12121212121212, "alnum_prop": 0.5163826998689384, "repo_name": "qgadrian/enkodi-desktop", "id": "fda7c32d96028de6b6dd549d4e0ba938eb03be16", "size": "763", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/app.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14434" }, { "name": "HTML", "bytes": "763" }, { "name": "JavaScript", "bytes": "95467" } ], "symlink_target": "" }
<nav> <ul> <li class="recieving-nav"><a href="<?php echo Yii::$app->getUrlManager()->getBaseUrl();?>/receiving/index"><i class="fa fa-download"></i> <span>Receiving</span></a></li> <li class="dispatching-nav"><a href="<?php echo Yii::$app->getUrlManager()->getBaseUrl();?>/dispatching/index"><i class="fa fa-share-square-o"></i> <span>Dispatching</span></a></li> <li class="weight-nav"><a href="<?php echo Yii::$app->getUrlManager()->getBaseUrl();?>/weight-capture/index"><i class="fa fa-anchor"></i> <span>Weight Capture</span></a></li> <!--<li class="admin-nav"><a href="admin_tools.php"><i class="fa fa-cogs"></i> <span>Admin Tools</span></a></li>--> <li class="logout-nav"><a href="<?php echo Yii::$app->getUrlManager()->getBaseUrl();?>/site/login"><i class="fa fa-sign-out"></i> <span>Log out</span></a></li> </ul> </nav>
{ "content_hash": "c863a8fc60f74e25635364faaa901f7b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 185, "avg_line_length": 95.22222222222223, "alnum_prop": 0.6207701283547258, "repo_name": "ybanezmi/brds", "id": "29ded4dee7731377f108168d53d58d62f5602c27", "size": "857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/layouts/standard-navigation.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "112" }, { "name": "CSS", "bytes": "42605" }, { "name": "JavaScript", "bytes": "17202" }, { "name": "PHP", "bytes": "250554" }, { "name": "Shell", "bytes": "1041" } ], "symlink_target": "" }
Rails.application.routes.draw do root 'home#index' # get '/about' => 'home#about', as: 'about' get '/photos/:id/:style/:device' => 'buildings#photo', as: 'photo' get '/forge' => 'forge#index', as: 'forge' get '/forge/list' => 'forge#list', as: 'forge_list' devise_for :users, path: 'u', skip: [ :registerable, :confirmable ], controllers: { sessions: "sessions" } #, omniauth_callbacks: "omniauth_callbacks" } resources :users do member do put 'enable' put 'disable' put 'disable_and_reset' get 'mask' end collection do get 'stats' end resource :user_account resources :roles end resources :street_conversions resources :buildings do collection do get :unpeopled get :unreviewed get :uninvestigated get :advanced_search_filters end member do put :review end end concern :people_directory do collection do get :advanced_search_filters get :building_autocomplete get :unreviewed get :unhoused end member do put :save_as put :reviewed end end # get '/census_records', to: redirect('/census/1910') # get '/census_records/new', to: redirect('census/1910/new') # post '/census_records' => 'people/census_records_nineteen_ten#create' # get '/census_records/:id', to: redirect('/census/1910/%{id}') # get '/census_records/:id/edit', to: redirect('/census/1910/%{id}/edit') # patch '/census_records/:id' => 'people/census_records_nineteen_ten#update' # resources :census_records, # concerns: [:people_directory], # controller: 'people/census_records_nineteen_ten', # as: 'census1910_records' resources :census_1900_records, concerns: [:people_directory], controller: 'people/census_records_nineteen_aught', path: 'census/1900', as: 'census1900_records' resources :census_1910_records, concerns: [:people_directory], controller: 'people/census_records_nineteen_ten', path: 'census/1910', as: 'census1910_records' resources :census_1920_records, concerns: [:people_directory], controller: 'people/census_records_nineteen_twenty', path: 'census/1920', as: 'census1920_records' resources :census_1930_records, concerns: [:people_directory], controller: 'people/census_records_nineteen_thirty', path: 'census/1930', as: 'census1930_records' get '/maps/activity' => 'audits#for_map_model', as: "maps_activity" resources :maps do member do post 'map_type' get 'export' get 'warp' get 'clip' post 'rectify' get 'align' get 'warped' get 'metadata' get 'comments' get 'delete' get 'status' get 'publish' get 'unpublish' post 'save_mask_and_warp' delete 'delete_mask' post 'warp_aligned' get 'gcps' get 'rough_state' => 'maps#get_rough_state' post 'rough_state' => 'maps#set_rough_state' get 'rough_centroid'=> 'maps#get_rough_centroid' post 'rough_centroid' => 'maps#set_rough_centroid' get 'id' get 'trace' get 'idland' end collection do get 'tag' end resources :layers end get '/maps/thumb/:id' => 'maps#thumb', as: 'thumb_map' get '/gcps/' => 'gcp#index', as: "gcps" get '/gcps/:id' => 'gcps#show', as: "gcp" delete '/gcps/:id/destroy' => 'gcps#destroy', as: "destroy_gcp" post '/gcps/add/:mapid' => 'gcps#add', as: "add_gcp" put '/gcps/update/:id' => 'gcps#update', as: "update_gcp" put '/gcps/update_field/:id' => 'gcps#update_field', as: "update_field_gcp" get '/maps/wms/:id' => "wms/map#wms", as: 'wms_map' get '/maps/tile/:id/:z/:x/:y' => "wms/map#tile", as: 'tile_map' get '/layers/:id/wms' => "wms/layer#wms", as: "wms_layer" get '/layers/:id/tile/:z/:x/:y' => "wms/layer#tile", as: 'tile_layer' resources :layers do member do get 'merge' get 'publish' patch 'toggle_visibility' post 'update_year' get 'maps' get 'export' get 'metadata' get 'delete' get 'id' get 'trace' get 'idland' end end put '/layers/:id/remove_map/:map_id' => 'layers#remove_map', as: 'remove_layer_map' put '/layers/:id/merge' => 'layers#merge', as: 'do_merge_layer' get '/users/:user_id/maps' => 'my_maps#list', as: 'my_maps' post '/users/:user_id/maps/create/:map_id' => 'my_maps#create', as: 'add_my_map' post '/users/:user_id/maps/destroy/:map_id' => 'my_maps#destroy', as: 'destroy_my_map' get '/users/:id/activity' => 'audits#for_user', as: 'user_activity' get '/maps/acitvity.:format' => 'audits#for_map_model', as: "formatted_maps_activity" get '/maps/:id/activity' => 'audits#for_map', as: "map_activity" get '/maps/:id/activity.:format' => 'audits#for_map', as: "formatted_map_activity" get '/activity' => 'audits#index', as: "activity" get '/activity/:id' => 'audits#show', as: "activity_details" get '/activity.:format' => 'audits#index', as: "formatted_activity" resources :imports do member do get 'maps' get 'start' get 'status' end end end
{ "content_hash": "20289a97f0bf320de4c16273c52944e9", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 96, "avg_line_length": 29.224043715846996, "alnum_prop": 0.5914360508601346, "repo_name": "dfurber/historyforge", "id": "ce7e99660d62daeedd2d6bdbe23617edc993c889", "size": "5348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/routes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29045" }, { "name": "CoffeeScript", "bytes": "32378" }, { "name": "Dockerfile", "bytes": "1405" }, { "name": "HTML", "bytes": "162348" }, { "name": "JavaScript", "bytes": "64650" }, { "name": "Ruby", "bytes": "348617" }, { "name": "Shell", "bytes": "1726" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c696f4ead90467f96ecb0b95d12b814b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "4391ec2a442fb957d82e6f0b5bde41d2f826fdb4", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Xanthostemon/Xanthostemon myrtifolius/ Syn. Xanthostemon integrifolium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/*! * wavesurfer.js 2.1.1 (2018-11-19) * https://github.com/katspaugh/wavesurfer.js * @license BSD-3-Clause */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("spectrogram", [], factory); else if(typeof exports === 'object') exports["spectrogram"] = factory(); else root["WaveSurfer"] = root["WaveSurfer"] || {}, root["WaveSurfer"]["spectrogram"] = factory(); })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "localhost:8080/dist/plugin/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/plugin/spectrogram.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./src/plugin/spectrogram.js": /*!***********************************!*\ !*** ./src/plugin/spectrogram.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * Calculate FFT - Based on https://github.com/corbanbrook/dsp.js */ /* eslint-disable complexity, no-redeclare, no-var, one-var */ var FFT = function FFT(bufferSize, sampleRate, windowFunc, alpha) { this.bufferSize = bufferSize; this.sampleRate = sampleRate; this.bandwidth = 2 / bufferSize * (sampleRate / 2); this.sinTable = new Float32Array(bufferSize); this.cosTable = new Float32Array(bufferSize); this.windowValues = new Float32Array(bufferSize); this.reverseTable = new Uint32Array(bufferSize); this.peakBand = 0; this.peak = 0; switch (windowFunc) { case 'bartlett': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = 2 / (bufferSize - 1) * ((bufferSize - 1) / 2 - Math.abs(i - (bufferSize - 1) / 2)); } break; case 'bartlettHann': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = 0.62 - 0.48 * Math.abs(i / (bufferSize - 1) - 0.5) - 0.38 * Math.cos(Math.PI * 2 * i / (bufferSize - 1)); } break; case 'blackman': alpha = alpha || 0.16; for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = (1 - alpha) / 2 - 0.5 * Math.cos(Math.PI * 2 * i / (bufferSize - 1)) + alpha / 2 * Math.cos(4 * Math.PI * i / (bufferSize - 1)); } break; case 'cosine': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = Math.cos(Math.PI * i / (bufferSize - 1) - Math.PI / 2); } break; case 'gauss': alpha = alpha || 0.25; for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = Math.pow(Math.E, -0.5 * Math.pow((i - (bufferSize - 1) / 2) / (alpha * (bufferSize - 1) / 2), 2)); } break; case 'hamming': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = (0.54 - 0.46) * Math.cos(Math.PI * 2 * i / (bufferSize - 1)); } break; case 'hann': case undefined: for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = 0.5 * (1 - Math.cos(Math.PI * 2 * i / (bufferSize - 1))); } break; case 'lanczoz': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = Math.sin(Math.PI * (2 * i / (bufferSize - 1) - 1)) / (Math.PI * (2 * i / (bufferSize - 1) - 1)); } break; case 'rectangular': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = 1; } break; case 'triangular': for (var i = 0; i < bufferSize; i++) { this.windowValues[i] = 2 / bufferSize * (bufferSize / 2 - Math.abs(i - (bufferSize - 1) / 2)); } break; default: throw Error("No such window function '" + windowFunc + "'"); } var limit = 1; var bit = bufferSize >> 1; var i; while (limit < bufferSize) { for (i = 0; i < limit; i++) { this.reverseTable[i + limit] = this.reverseTable[i] + bit; } limit = limit << 1; bit = bit >> 1; } for (i = 0; i < bufferSize; i++) { this.sinTable[i] = Math.sin(-Math.PI / i); this.cosTable[i] = Math.cos(-Math.PI / i); } this.calculateSpectrum = function (buffer) { // Locally scope variables for speed up var bufferSize = this.bufferSize, cosTable = this.cosTable, sinTable = this.sinTable, reverseTable = this.reverseTable, real = new Float32Array(bufferSize), imag = new Float32Array(bufferSize), bSi = 2 / this.bufferSize, sqrt = Math.sqrt, rval, ival, mag, spectrum = new Float32Array(bufferSize / 2); var k = Math.floor(Math.log(bufferSize) / Math.LN2); if (Math.pow(2, k) !== bufferSize) { throw 'Invalid buffer size, must be a power of 2.'; } if (bufferSize !== buffer.length) { throw 'Supplied buffer is not the same size as defined FFT. FFT Size: ' + bufferSize + ' Buffer Size: ' + buffer.length; } var halfSize = 1, phaseShiftStepReal, phaseShiftStepImag, currentPhaseShiftReal, currentPhaseShiftImag, off, tr, ti, tmpReal; for (var i = 0; i < bufferSize; i++) { real[i] = buffer[reverseTable[i]] * this.windowValues[reverseTable[i]]; imag[i] = 0; } while (halfSize < bufferSize) { phaseShiftStepReal = cosTable[halfSize]; phaseShiftStepImag = sinTable[halfSize]; currentPhaseShiftReal = 1; currentPhaseShiftImag = 0; for (var fftStep = 0; fftStep < halfSize; fftStep++) { var i = fftStep; while (i < bufferSize) { off = i + halfSize; tr = currentPhaseShiftReal * real[off] - currentPhaseShiftImag * imag[off]; ti = currentPhaseShiftReal * imag[off] + currentPhaseShiftImag * real[off]; real[off] = real[i] - tr; imag[off] = imag[i] - ti; real[i] += tr; imag[i] += ti; i += halfSize << 1; } tmpReal = currentPhaseShiftReal; currentPhaseShiftReal = tmpReal * phaseShiftStepReal - currentPhaseShiftImag * phaseShiftStepImag; currentPhaseShiftImag = tmpReal * phaseShiftStepImag + currentPhaseShiftImag * phaseShiftStepReal; } halfSize = halfSize << 1; } for (var i = 0, N = bufferSize / 2; i < N; i++) { rval = real[i]; ival = imag[i]; mag = bSi * sqrt(rval * rval + ival * ival); if (mag > this.peak) { this.peakBand = i; this.peak = mag; } spectrum[i] = mag; } return spectrum; }; }; /* eslint-enable complexity, no-redeclare, no-var, one-var */ /** * @typedef {Object} SpectrogramPluginParams * @property {string|HTMLElement} container Selector of element or element in * which to render * @property {number} fftSamples=512 number of samples to fetch to FFT. Must be * a power of 2. * @property {number} noverlap Size of the overlapping window. Must be < * fftSamples. Auto deduced from canvas size by default. * @property {string} windowFunc='hann' The window function to be used. One of * these: `'bartlett'`, `'bartlettHann'`, `'blackman'`, `'cosine'`, `'gauss'`, * `'hamming'`, `'hann'`, `'lanczoz'`, `'rectangular'`, `'triangular'` * @property {?number} alpha Some window functions have this extra value. * (Between 0 and 1) * @property {number} pixelRatio=wavesurfer.params.pixelRatio to control the * size of the spectrogram in relation with its canvas. 1 = Draw on the whole * canvas. 2 = Draw on a quarter (1/2 the length and 1/2 the width) * @property {?boolean} deferInit Set to true to manually call * `initPlugin('spectrogram')` */ /** * Render a spectrogram visualisation of the audio. * * @implements {PluginClass} * @extends {Observer} * @example * // es6 * import SpectrogramPlugin from 'wavesurfer.spectrogram.js'; * * // commonjs * var SpectrogramPlugin = require('wavesurfer.spectrogram.js'); * * // if you are using <script> tags * var SpectrogramPlugin = window.WaveSurfer.spectrogram; * * // ... initialising wavesurfer with the plugin * var wavesurfer = WaveSurfer.create({ * // wavesurfer options ... * plugins: [ * SpectrogramPlugin.create({ * // plugin options ... * }) * ] * }); */ var SpectrogramPlugin = /*#__PURE__*/ function () { _createClass(SpectrogramPlugin, null, [{ key: "create", /** * Spectrogram plugin definition factory * * This function must be used to create a plugin definition which can be * used by wavesurfer to correctly instantiate the plugin. * * @param {SpectrogramPluginParams} params parameters use to initialise the plugin * @return {PluginDefinition} an object representing the plugin */ value: function create(params) { return { name: 'spectrogram', deferInit: params && params.deferInit ? params.deferInit : false, params: params, staticProps: { FFT: FFT }, instance: SpectrogramPlugin }; } }]); function SpectrogramPlugin(params, ws) { var _this = this; _classCallCheck(this, SpectrogramPlugin); this.params = params; this.wavesurfer = ws; this.util = ws.util; this.frequenciesDataUrl = params.frequenciesDataUrl; this._onScroll = function (e) { _this.updateScroll(e); }; this._onReady = function () { var drawer = _this.drawer = ws.drawer; _this.container = 'string' == typeof params.container ? document.querySelector(params.container) : params.container; if (!_this.container) { throw Error('No container for WaveSurfer spectrogram'); } _this.width = drawer.width; _this.pixelRatio = _this.params.pixelRatio || ws.params.pixelRatio; _this.fftSamples = _this.params.fftSamples || ws.params.fftSamples || 512; _this.height = _this.fftSamples / 2; _this.noverlap = params.noverlap; _this.windowFunc = params.windowFunc; _this.alpha = params.alpha; _this.createWrapper(); _this.createCanvas(); _this.render(); drawer.wrapper.addEventListener('scroll', _this._onScroll); ws.on('redraw', function () { return _this.render(); }); }; } _createClass(SpectrogramPlugin, [{ key: "init", value: function init() { // Check if ws is ready if (this.wavesurfer.isReady) { this._onReady(); } this.wavesurfer.on('ready', this._onReady); } }, { key: "destroy", value: function destroy() { this.unAll(); this.wavesurfer.un('ready', this._onReady); this.drawer.wrapper.removeEventListener('scroll', this._onScroll); this.wavesurfer = null; this.util = null; this.params = null; if (this.wrapper) { this.wrapper.parentNode.removeChild(this.wrapper); this.wrapper = null; } } }, { key: "createWrapper", value: function createWrapper() { var _this2 = this; var prevSpectrogram = this.container.querySelector('spectrogram'); if (prevSpectrogram) { this.container.removeChild(prevSpectrogram); } var wsParams = this.wavesurfer.params; this.wrapper = document.createElement('spectrogram'); // if labels are active if (this.params.labels) { var labelsEl = this.labelsEl = document.createElement('canvas'); labelsEl.classList.add('spec-labels'); this.drawer.style(labelsEl, { left: 0, position: 'absolute', zIndex: 9, height: "".concat(this.height / this.pixelRatio, "px"), width: "".concat(55 / this.pixelRatio, "px") }); this.wrapper.appendChild(labelsEl); // can be customized in next version this.loadLabels('rgba(68,68,68,0.5)', '12px', '10px', '', '#fff', '#f7f7f7', 'center', '#specLabels'); } this.drawer.style(this.wrapper, { display: 'block', position: 'relative', userSelect: 'none', webkitUserSelect: 'none', height: "".concat(this.height / this.pixelRatio, "px") }); if (wsParams.fillParent || wsParams.scrollParent) { this.drawer.style(this.wrapper, { width: '100%', overflowX: 'hidden', overflowY: 'hidden' }); } this.container.appendChild(this.wrapper); this.wrapper.addEventListener('click', function (e) { e.preventDefault(); var relX = 'offsetX' in e ? e.offsetX : e.layerX; _this2.fireEvent('click', relX / _this2.scrollWidth || 0); }); } }, { key: "createCanvas", value: function createCanvas() { var canvas = this.canvas = this.wrapper.appendChild(document.createElement('canvas')); this.spectrCc = canvas.getContext('2d'); this.util.style(canvas, { position: 'absolute', zIndex: 4 }); } }, { key: "render", value: function render() { this.updateCanvasStyle(); if (this.frequenciesDataUrl) { this.loadFrequenciesData(this.frequenciesDataUrl); } else { this.getFrequencies(this.drawSpectrogram); } } }, { key: "updateCanvasStyle", value: function updateCanvasStyle() { var width = Math.round(this.width / this.pixelRatio) + 'px'; this.canvas.width = this.width; this.canvas.height = this.height; this.canvas.style.width = width; } }, { key: "drawSpectrogram", value: function drawSpectrogram(frequenciesData, my) { var spectrCc = my.spectrCc; var length = my.wavesurfer.backend.getDuration(); var height = my.height; var pixels = my.resample(frequenciesData); var heightFactor = my.buffer ? 2 / my.buffer.numberOfChannels : 1; var i; var j; for (i = 0; i < pixels.length; i++) { for (j = 0; j < pixels[i].length; j++) { var colorValue = 255 - pixels[i][j]; my.spectrCc.fillStyle = 'rgb(' + colorValue + ', ' + colorValue + ', ' + colorValue + ')'; my.spectrCc.fillRect(i, height - j * heightFactor, 1, heightFactor); } } } }, { key: "getFrequencies", value: function getFrequencies(callback) { var fftSamples = this.fftSamples; var buffer = this.buffer = this.wavesurfer.backend.buffer; var channelOne = buffer.getChannelData(0); var bufferLength = buffer.length; var sampleRate = buffer.sampleRate; var frequencies = []; if (!buffer) { this.fireEvent('error', 'Web Audio buffer is not available'); return; } var noverlap = this.noverlap; if (!noverlap) { var uniqueSamplesPerPx = buffer.length / this.canvas.width; noverlap = Math.max(0, Math.round(fftSamples - uniqueSamplesPerPx)); } var fft = new FFT(fftSamples, sampleRate, this.windowFunc, this.alpha); var maxSlicesCount = Math.floor(bufferLength / (fftSamples - noverlap)); var currentOffset = 0; while (currentOffset + fftSamples < channelOne.length) { var segment = channelOne.slice(currentOffset, currentOffset + fftSamples); var spectrum = fft.calculateSpectrum(segment); var array = new Uint8Array(fftSamples / 2); var j = void 0; for (j = 0; j < fftSamples / 2; j++) { array[j] = Math.max(-255, Math.log10(spectrum[j]) * 45); } frequencies.push(array); currentOffset += fftSamples - noverlap; } callback(frequencies, this); } }, { key: "loadFrequenciesData", value: function loadFrequenciesData(url) { var _this3 = this; var ajax = this.util.ajax({ url: url }); ajax.on('success', function (data) { return _this3.drawSpectrogram(JSON.parse(data), _this3); }); ajax.on('error', function (e) { return _this3.fireEvent('error', 'XHR error: ' + e.target.statusText); }); return ajax; } }, { key: "freqType", value: function freqType(freq) { return freq >= 1000 ? (freq / 1000).toFixed(1) : Math.round(freq); } }, { key: "unitType", value: function unitType(freq) { return freq >= 1000 ? 'KHz' : 'Hz'; } }, { key: "loadLabels", value: function loadLabels(bgFill, fontSizeFreq, fontSizeUnit, fontType, textColorFreq, textColorUnit, textAlign, container) { var frequenciesHeight = this.height; bgFill = bgFill || 'rgba(68,68,68,0)'; fontSizeFreq = fontSizeFreq || '12px'; fontSizeUnit = fontSizeUnit || '10px'; fontType = fontType || 'Helvetica'; textColorFreq = textColorFreq || '#fff'; textColorUnit = textColorUnit || '#fff'; textAlign = textAlign || 'center'; container = container || '#specLabels'; var getMaxY = frequenciesHeight || 512; var labelIndex = 5 * (getMaxY / 256); var freqStart = 0; var step = (this.wavesurfer.backend.ac.sampleRate / 2 - freqStart) / labelIndex; var ctx = this.labelsEl.getContext('2d'); this.labelsEl.height = this.height; this.labelsEl.width = 55; ctx.fillStyle = bgFill; ctx.fillRect(0, 0, 55, getMaxY); ctx.fill(); var i; for (i = 0; i <= labelIndex; i++) { ctx.textAlign = textAlign; ctx.textBaseline = 'middle'; var freq = freqStart + step * i; var index = Math.round(freq / (this.sampleRate / 2) * this.fftSamples); var label = this.freqType(freq); var units = this.unitType(freq); var x = 16; var yLabelOffset = 2; if (i == 0) { ctx.fillStyle = textColorUnit; ctx.font = fontSizeUnit + ' ' + fontType; ctx.fillText(units, x + 24, getMaxY + i - 10); ctx.fillStyle = textColorFreq; ctx.font = fontSizeFreq + ' ' + fontType; ctx.fillText(label, x, getMaxY + i - 10); } else { ctx.fillStyle = textColorUnit; ctx.font = fontSizeUnit + ' ' + fontType; ctx.fillText(units, x + 24, getMaxY - i * 50 + yLabelOffset); ctx.fillStyle = textColorFreq; ctx.font = fontSizeFreq + ' ' + fontType; ctx.fillText(label, x, getMaxY - i * 50 + yLabelOffset); } } } }, { key: "updateScroll", value: function updateScroll(e) { if (this.wrapper) { this.wrapper.scrollLeft = e.target.scrollLeft; } } }, { key: "resample", value: function resample(oldMatrix) { var columnsNumber = this.width; var newMatrix = []; var oldPiece = 1 / oldMatrix.length; var newPiece = 1 / columnsNumber; var i; for (i = 0; i < columnsNumber; i++) { var column = new Array(oldMatrix[0].length); var j = void 0; for (j = 0; j < oldMatrix.length; j++) { var oldStart = j * oldPiece; var oldEnd = oldStart + oldPiece; var newStart = i * newPiece; var newEnd = newStart + newPiece; var overlap = oldEnd <= newStart || newEnd <= oldStart ? 0 : Math.min(Math.max(oldEnd, newStart), Math.max(newEnd, oldStart)) - Math.max(Math.min(oldEnd, newStart), Math.min(newEnd, oldStart)); var k = void 0; /* eslint-disable max-depth */ if (overlap > 0) { for (k = 0; k < oldMatrix[0].length; k++) { if (column[k] == null) { column[k] = 0; } column[k] += overlap / newPiece * oldMatrix[j][k]; } } /* eslint-enable max-depth */ } var intColumn = new Uint8Array(oldMatrix[0].length); var m = void 0; for (m = 0; m < oldMatrix[0].length; m++) { intColumn[m] = column[m]; } newMatrix.push(intColumn); } return newMatrix; } }]); return SpectrogramPlugin; }(); exports.default = SpectrogramPlugin; module.exports = exports.default; /***/ }) /******/ }); }); //# sourceMappingURL=wavesurfer.spectrogram.js.map
{ "content_hash": "08e2124b9e85ccf86d078e1dc7f413bc", "timestamp": "", "source": "github", "line_count": 753, "max_line_length": 317, "avg_line_length": 32.27091633466136, "alnum_prop": 0.5762139917695474, "repo_name": "extend1994/cdnjs", "id": "120a5fa42f5f31dcc25b0ce61ffc8da455aae59f", "size": "24300", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ajax/libs/wavesurfer.js/2.1.1/plugin/wavesurfer.spectrogram.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
if [ "$1" != "" ] && [ "$1" = "-h" ]; then echo "Shipyard Deploy uses the following environment variables:" echo " ACTION: this is the action to use (deploy, upgrade, node, remove)" echo " DISCOVERY: discovery system used by Swarm (only if using 'node' action)" echo " IMAGE: this overrides the default Shipyard image" echo " PREFIX: prefix for container names" echo " SHIPYARD_ARGS: these are passed to the Shipyard controller container as controller args" echo " TLS_CERT_PATH: path to certs to enable TLS for Shipyard" echo " PORT: specify the listen port for the controller (default: 8080)" echo " IP: specify the address at which the controller or node will be available (default: eth0 ip)" echo " PROXY_PORT: port to run docker proxy (default: 2375)" exit 1 fi if [ -z "`which docker`" ]; then echo "You must have the Docker CLI installed on your \$PATH" echo " See http://docs.docker.com for details" exit 1 fi ACTION=${ACTION:-deploy} IMAGE=${IMAGE:-shipyard/shipyard:latest} PREFIX=${PREFIX:-shipyard} echo $PREFIX SHIPYARD_ARGS=${SHIPYARD_ARGS:-""} TLS_CERT_PATH=${TLS_CERT_PATH:-} CERT_PATH="/etc/shipyard" PROXY_PORT=${PROXY_PORT:-2375} SWARM_PORT=3375 SHIPYARD_PROTOCOL=http SHIPYARD_PORT=${PORT:-8080} echo $SHIPYARD_PORT SHIPYARD_IP=${IP} DISCOVERY_BACKEND=etcd DISCOVERY_PORT=4001 DISCOVERY_PEER_PORT=7001 ENABLE_TLS=0 CERT_FINGERPRINT="" LOCAL_CA_CERT="" LOCAL_SSL_CERT="" LOCAL_SSL_KEY="" LOCAL_SSL_CLIENT_CERT="" LOCAL_SSL_CLIENT_KEY="" SSL_CA_CERT="" SSL_CERT="" SSL_KEY="" SSL_CLIENT_CERT="" SSL_CLIENT_KEY="" show_cert_help() { echo "To use TLS in Shipyard, you must have existing certificates." echo "The certs must be named ca.pem, server.pem, server-key.pem, cert.pem and key.pem" echo "If you need to generate certificates, see https://github.com/ehazlett/certm for examples." } check_certs() { if [ -z "$TLS_CERT_PATH" ]; then return fi if [ ! -e $TLS_CERT_PATH ]; then echo "Error: unable to find certificates in $TLS_CERT_PATH" show_cert_help exit 1 fi if [ "$PROXY_PORT" = "2375" ]; then PROXY_PORT=2376 fi SWARM_PORT=3376 SHIPYARD_PROTOCOL=https LOCAL_SSL_CA_CERT="$TLS_CERT_PATH/ca.pem" LOCAL_SSL_CERT="$TLS_CERT_PATH/server.pem" LOCAL_SSL_KEY="$TLS_CERT_PATH/server-key.pem" LOCAL_SSL_CLIENT_CERT="$TLS_CERT_PATH/cert.pem" LOCAL_SSL_CLIENT_KEY="$TLS_CERT_PATH/key.pem" SSL_CA_CERT="$CERT_PATH/ca.pem" SSL_CERT="$CERT_PATH/server.pem" SSL_KEY="$CERT_PATH/server-key.pem" SSL_CLIENT_CERT="$CERT_PATH/cert.pem" SSL_CLIENT_KEY="$CERT_PATH/key.pem" CERT_FINGERPRINT=$(openssl x509 -noout -in $LOCAL_SSL_CERT -fingerprint -sha256 | awk -F= '{print $2;}') if [ ! -e $LOCAL_SSL_CA_CERT ] || [ ! -e $LOCAL_SSL_CERT ] || [ ! -e $LOCAL_SSL_KEY ] || [ ! -e $LOCAL_SSL_CLIENT_CERT ] || [ ! -e $LOCAL_SSL_CLIENT_KEY ]; then echo "Error: unable to find certificates" show_cert_help exit 1 fi ENABLE_TLS=1 } # container functions start_certs() { ID=$(docker run \ -ti \ -d \ --restart=always \ --name $PREFIX-certs \ -v $CERT_PATH \ alpine \ sh) if [ $ENABLE_TLS = 1 ]; then docker cp $LOCAL_SSL_CA_CERT $PREFIX-certs:$SSL_CA_CERT docker cp $LOCAL_SSL_CERT $PREFIX-certs:$SSL_CERT docker cp $LOCAL_SSL_KEY $PREFIX-certs:$SSL_KEY docker cp $LOCAL_SSL_CLIENT_CERT $PREFIX-certs:$SSL_CLIENT_CERT docker cp $LOCAL_SSL_CLIENT_KEY $PREFIX-certs:$SSL_CLIENT_KEY fi } remove_certs() { docker rm -fv $PREFIX-certs > /dev/null 2>&1 } get_ip() { if [ -z "$SHIPYARD_IP" ]; then SHIPYARD_IP=`docker run --rm --net=host alpine ip route get 8.8.8.8 | awk '{ print $7; }'` fi } start_discovery() { get_ip ID=$(docker run \ -ti \ -d \ -p 4001:4001 \ -p 7001:7001 \ --restart=always \ --name $PREFIX-discovery \ microbox/etcd:latest -addr $SHIPYARD_IP:$DISCOVERY_PORT -peer-addr $SHIPYARD_IP:$DISCOVERY_PEER_PORT) } remove_discovery() { docker rm -fv $PREFIX-discovery > /dev/null 2>&1 } start_rethinkdb() { ID=$(docker run \ -ti \ -d \ --restart=always \ --name $PREFIX-rethinkdb \ rethinkdb) } remove_rethinkdb() { docker rm -fv $PREFIX-rethinkdb > /dev/null 2>&1 } start_proxy() { TLS_OPTS="" if [ $ENABLE_TLS = 1 ]; then TLS_OPTS="-e SSL_CA=$SSL_CA_CERT -e SSL_CERT=$SSL_CERT -e SSL_KEY=$SSL_KEY -e SSL_SKIP_VERIFY=1" fi # Note: we add SSL_SKIP_VERIFY=1 to skip verification of the client # certificate in the proxy image. this will pass it to swarm that # does verify. this helps with performance and avoids certificate issues # when running through the proxy. ultimately if the cert is invalid # swarm will fail to return. ID=$(docker run \ -ti \ -d \ -p $PROXY_PORT:$PROXY_PORT \ --hostname=$HOSTNAME \ --restart=always \ --name $PREFIX-proxy \ -v /var/run/docker.sock:/var/run/docker.sock \ -e PORT=$PROXY_PORT \ --volumes-from=$PREFIX-certs $TLS_OPTS\ shipyard/docker-proxy:latest) } remove_proxy() { docker rm -fv $PREFIX-proxy > /dev/null 2>&1 } start_swarm_manager() { get_ip TLS_OPTS="" if [ $ENABLE_TLS = 1 ]; then TLS_OPTS="--tlsverify --tlscacert=$SSL_CA_CERT --tlscert=$SSL_CERT --tlskey=$SSL_KEY" fi EXTRA_RUN_OPTS="" if [ -z "$DISCOVERY" ]; then DISCOVERY="$DISCOVERY_BACKEND://discovery:$DISCOVERY_PORT" EXTRA_RUN_OPTS="--link $PREFIX-discovery:discovery" fi ID=$(docker run \ -ti \ -d \ --restart=always \ --name $PREFIX-swarm-manager \ --volumes-from=$PREFIX-certs $EXTRA_RUN_OPTS \ swarm:latest \ m --replication --addr $SHIPYARD_IP:$SWARM_PORT --host tcp://0.0.0.0:$SWARM_PORT $TLS_OPTS $DISCOVERY) } remove_swarm_manager() { docker rm -fv $PREFIX-swarm-manager > /dev/null 2>&1 } start_swarm_agent() { get_ip if [ -z "$DISCOVERY" ]; then DISCOVERY="$DISCOVERY_BACKEND://discovery:$DISCOVERY_PORT" EXTRA_RUN_OPTS="--link $PREFIX-discovery:discovery" fi ID=$(docker run \ -ti \ -d \ --restart=always \ --name $PREFIX-swarm-agent $EXTRA_RUN_OPTS \ swarm:latest \ j --addr $SHIPYARD_IP:$PROXY_PORT $DISCOVERY) } remove_swarm_agent() { docker rm -fv $PREFIX-swarm-agent > /dev/null 2>&1 } start_controller() { #-v $CERT_PATH:/etc/docker:ro \ TLS_OPTS="" if [ $ENABLE_TLS = 1 ]; then TLS_OPTS="--tls-ca-cert $SSL_CA_CERT --tls-cert=$SSL_CERT --tls-key=$SSL_KEY --shipyard-tls-ca-cert=$SSL_CA_CERT --shipyard-tls-cert=$SSL_CERT --shipyard-tls-key=$SSL_KEY" fi ID=$(docker run \ -ti \ -d \ --restart=always \ --name $PREFIX-controller \ --link $PREFIX-rethinkdb:rethinkdb \ --link $PREFIX-swarm-manager:swarm \ -p $SHIPYARD_PORT:$SHIPYARD_PORT \ --volumes-from=$PREFIX-certs \ $IMAGE \ --debug \ server \ --listen :$SHIPYARD_PORT \ -d tcp://swarm:$SWARM_PORT $TLS_OPTS $SHIPYARD_ARGS) } wait_for_available() { set +e IP=$1 PORT=$2 echo Waiting for Shipyard on $IP:$PORT docker pull ehazlett/curl > /dev/null 2>&1 TLS_OPTS="" if [ $ENABLE_TLS = 1 ]; then TLS_OPTS="-k" fi until $(docker run --rm ehazlett/curl --output /dev/null --connect-timeout 1 --silent --head --fail $TLS_OPTS $SHIPYARD_PROTOCOL://$IP:$PORT/ > /dev/null 2>&1); do printf '.' sleep 1 done printf '\n' } remove_controller() { docker rm -fv $PREFIX-controller > /dev/null 2>&1 } if [ "$ACTION" = "deploy" ]; then set -e check_certs get_ip echo "Deploying Shipyard" echo " -> Starting Database" start_rethinkdb echo " -> Starting Discovery" start_discovery echo " -> Starting Cert Volume" start_certs echo " -> Starting Proxy" start_proxy echo " -> Starting Swarm Manager" start_swarm_manager echo " -> Starting Swarm Agent" start_swarm_agent echo " -> Starting Controller" start_controller wait_for_available $SHIPYARD_IP $SHIPYARD_PORT echo "Shipyard available at $SHIPYARD_PROTOCOL://$SHIPYARD_IP:$SHIPYARD_PORT" if [ $ENABLE_TLS = 1 ] && [ ! -z "$CERT_FINGERPRINT" ]; then echo "SSL SHA-256 Fingerprint: $CERT_FINGERPRINT" fi echo "Username: admin Password: shipyard" elif [ "$ACTION" = "node" ]; then set -e if [ -z "$DISCOVERY" ]; then echo "You must set the DISCOVERY environment variable" echo "with the discovery system used with Swarm" exit 1 fi check_certs echo "Adding Node" echo " -> Starting Cert Volume" start_certs echo " -> Starting Proxy" start_proxy echo " -> Starting Swarm Manager" start_swarm_manager $DISCOVERY echo " -> Starting Swarm Agent" start_swarm_agent echo "Node added to Swarm: $SHIPYARD_IP" elif [ "$ACTION" = "upgrade" ]; then set -e check_certs get_ip echo "Upgrading Shipyard" echo " -> Pulling $IMAGE" docker pull $IMAGE echo " -> Upgrading Controller" remove_controller start_controller wait_for_available $SHIPYARD_IP $SHIPYARD_PORT echo "Shipyard controller updated" elif [ "$ACTION" = "remove" ]; then # ignore errors set +e echo "Removing Shipyard" echo " -> Removing Database" remove_rethinkdb echo " -> Removing Discovery" remove_discovery echo " -> Removing Cert Volume" remove_certs echo " -> Removing Proxy" remove_proxy echo " -> Removing Swarm Agent" remove_swarm_agent echo " -> Removing Swarm Manager" remove_swarm_manager echo " -> Removing Controller" remove_controller echo "Done" else echo "Unknown action $ACTION" exit 1 fi
{ "content_hash": "d91dff423110cf0f2f3d4f074a9e2d87", "timestamp": "", "source": "github", "line_count": 371, "max_line_length": 179, "avg_line_length": 27.328840970350406, "alnum_prop": 0.6084426472038662, "repo_name": "MarsBighead/mustang", "id": "d24b5a1735a66473c499ac0b97497e2d7255c1ae", "size": "10152", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker/shipyard_deploy.sh", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "622" }, { "name": "C++", "bytes": "15533" }, { "name": "CSS", "bytes": "2525" }, { "name": "Dockerfile", "bytes": "499" }, { "name": "Erlang", "bytes": "5855" }, { "name": "Go", "bytes": "3879" }, { "name": "HTML", "bytes": "3879" }, { "name": "Java", "bytes": "541" }, { "name": "JavaScript", "bytes": "7858" }, { "name": "Julia", "bytes": "2223" }, { "name": "Makefile", "bytes": "650" }, { "name": "Modula-3", "bytes": "43" }, { "name": "PHP", "bytes": "771" }, { "name": "PLpgSQL", "bytes": "4642" }, { "name": "Perl", "bytes": "46253" }, { "name": "Python", "bytes": "110755" }, { "name": "Raku", "bytes": "378" }, { "name": "Shell", "bytes": "22680" } ], "symlink_target": "" }
package org.elasticsearch.cluster.routing.allocation; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.test.ElasticsearchTestCase; import org.junit.Test; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; import static org.elasticsearch.cluster.routing.allocation.RoutingAllocationTests.newNode; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.hamcrest.Matchers.equalTo; /** */ public class PreferPrimaryAllocationTests extends ElasticsearchTestCase { private final ESLogger logger = Loggers.getLogger(PreferPrimaryAllocationTests.class); @Test public void testPreferPrimaryAllocationOverReplicas() { logger.info("create an allocation with 1 initial recoveries"); AllocationService strategy = new AllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 1) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 1) .build()); logger.info("create several indices with no replicas, and wait till all are allocated"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test1").numberOfShards(10).numberOfReplicas(0)) .put(IndexMetaData.builder("test2").numberOfShards(10).numberOfReplicas(0)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test1")) .addAsNew(metaData.index("test2")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("adding two nodes and performing rerouting till all are allocated"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); while (!clusterState.routingNodes().shardsWithState(INITIALIZING).isEmpty()) { routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); } logger.info("increasing the number of replicas to 1, and perform a reroute (to get the replicas allocation going)"); routingTable = RoutingTable.builder(routingTable).updateNumberOfReplicas(1).build(); metaData = MetaData.builder(clusterState.metaData()).updateNumberOfReplicas(1).build(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metaData(metaData).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("2 replicas should be initializing now for the existing indices (we throttle to 1)"); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(2)); logger.info("create a new index"); metaData = MetaData.builder(clusterState.metaData()) .put(IndexMetaData.builder("new_index").numberOfShards(4).numberOfReplicas(0)) .build(); routingTable = RoutingTable.builder(clusterState.routingTable()) .addAsNew(metaData.index("new_index")) .build(); clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build(); logger.info("reroute, verify that primaries for the new index primary shards are allocated"); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingTable().index("new_index").shardsWithState(INITIALIZING).size(), equalTo(2)); } }
{ "content_hash": "ef435095b9fb3d474875467b7e8b4d5f", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 143, "avg_line_length": 51.96511627906977, "alnum_prop": 0.7290221526068472, "repo_name": "andrewvc/elasticsearch", "id": "36a20bc3f0f00416c466a49715fc938f0cf3c1bc", "size": "5274", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/elasticsearch/cluster/routing/allocation/PreferPrimaryAllocationTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18745334" }, { "name": "Python", "bytes": "21889" }, { "name": "Shell", "bytes": "26370" } ], "symlink_target": "" }
#include "stdafx.h" #include "actor.h" #include "weapon.h" #include "mercuryball.h" #include "inventory.h" #include "hudmanager.h" #include "character_info.h" #include "xr_level_controller.h" #include "UsableScriptObject.h" #include "customzone.h" #include "GameMtlLib.h" #include "ui/UIMainIngameWnd.h" #include "Grenade.h" #include "clsid_game.h" #include "game_cl_base.h" #include "Level.h" #define PICKUP_INFO_COLOR 0xFFDDDDDD //AAAAAA void CActor::feel_touch_new (CObject* O) { } void CActor::feel_touch_delete (CObject* O) { CPhysicsShellHolder* sh=smart_cast<CPhysicsShellHolder*>(O); if(sh&&sh->character_physics_support()) m_feel_touch_characters--; } BOOL CActor::feel_touch_contact (CObject *O) { CInventoryItem *item = smart_cast<CInventoryItem*>(O); CInventoryOwner *inventory_owner = smart_cast<CInventoryOwner*>(O); if (item && item->Useful() && !item->object().H_Parent()) return TRUE; if(inventory_owner && inventory_owner != smart_cast<CInventoryOwner*>(this)) { CPhysicsShellHolder* sh=smart_cast<CPhysicsShellHolder*>(O); if(sh&&sh->character_physics_support()) m_feel_touch_characters++; return TRUE; } return (FALSE); } BOOL CActor::feel_touch_on_contact (CObject *O) { CCustomZone *custom_zone = smart_cast<CCustomZone*>(O); if (!custom_zone) return (TRUE); Fsphere sphere; sphere.P = Position(); sphere.R = EPS_L; if (custom_zone->inside(sphere)) return (TRUE); return (FALSE); } void CActor::PickupModeOn() { m_bPickupMode = true; } void CActor::PickupModeOff() { m_bPickupMode = false; } ICF static BOOL info_trace_callback(collide::rq_result& result, LPVOID params) { BOOL& bOverlaped = *(BOOL*)params; if(result.O){ if (Level().CurrentEntity()!=result.O){ bOverlaped = TRUE; return FALSE; }else{ return TRUE; } }else{ //ïîëó÷èòü òðåóãîëüíèê è óçíàòü åãî ìàòåðèàë CDB::TRI* T = Level().ObjectSpace.GetStaticTris()+result.element; if (GMLib.GetMaterialByIdx(T->material)->Flags.is(SGameMtl::flPassable)) return TRUE; } bOverlaped = TRUE; return FALSE; } BOOL CActor::CanPickItem(const CFrustum& frustum, const Fvector& from, CObject* item) { BOOL bOverlaped = FALSE; Fvector dir,to; item->Center (to); float range = dir.sub(to,from).magnitude(); if (range>0.25f){ if (frustum.testSphere_dirty(to,item->Radius())){ dir.div (range); collide::ray_defs RD(from, dir, range, CDB::OPT_CULL, collide::rqtBoth); VERIFY (!fis_zero(RD.dir.square_magnitude())); RQR.r_clear (); Level().ObjectSpace.RayQuery(RQR,RD, info_trace_callback, &bOverlaped, NULL, item); } } return !bOverlaped; } void CActor::PickupModeUpdate() { if(!m_bPickupMode) return; if (GameID() != GAME_SINGLE) return; //ïîäáèðàíèå îáúåêòà if(inventory().m_pTarget && inventory().m_pTarget->Useful() && m_pUsableObject && m_pUsableObject->nonscript_usable()) { NET_Packet P; u_EventGen(P,GE_OWNERSHIP_TAKE, ID()); P.w_u16(inventory().m_pTarget->object().ID()); u_EventSend(P); } //. ????? GetNearest ????? feel_touch_update (Position(), /*inventory().GetTakeDist()*/m_fPickupInfoRadius); CFrustum frustum; frustum.CreateFromMatrix(Device.mFullTransform,FRUSTUM_P_LRTB|FRUSTUM_P_FAR); //. slow (ray-query test) for(xr_vector<CObject*>::iterator it = feel_touch.begin(); it != feel_touch.end(); it++) if (CanPickItem(frustum,Device.vCameraPosition,*it)) PickupInfoDraw(*it); } #include "../CameraBase.h" BOOL g_b_COD_PickUpMode = FALSE; void CActor::PickupModeUpdate_COD () { if (Level().CurrentViewEntity() != this || !g_b_COD_PickUpMode) return; if (!g_Alive() || eacFirstEye != cam_active) { HUD().GetUI()->UIMainIngameWnd->SetPickUpItem(NULL); return; }; CFrustum frustum; frustum.CreateFromMatrix(Device.mFullTransform,FRUSTUM_P_LRTB|FRUSTUM_P_FAR); //--------------------------------------------------------------------------- ISpatialResult.clear_not_free (); g_SpatialSpace->q_frustum(ISpatialResult, 0, STYPE_COLLIDEABLE, frustum); //--------------------------------------------------------------------------- float maxlen = 1000.0f; CInventoryItem* pNearestItem = NULL; for (u32 o_it=0; o_it<ISpatialResult.size(); o_it++) { ISpatial* spatial = ISpatialResult[o_it]; CInventoryItem* pIItem = smart_cast<CInventoryItem*> (spatial->dcast_CObject ()); if (0 == pIItem) continue; if (pIItem->object().H_Parent() != NULL) continue; if (!pIItem->CanTake()) continue; if (pIItem->object().CLS_ID == CLSID_OBJECT_G_RPG7 || pIItem->object().CLS_ID == CLSID_OBJECT_G_FAKE) continue; CGrenade* pGrenade = smart_cast<CGrenade*> (spatial->dcast_CObject ()); if (pGrenade && !pGrenade->Useful()) continue; CMissile* pMissile = smart_cast<CMissile*> (spatial->dcast_CObject ()); if (pMissile && !pMissile->Useful()) continue; Fvector A, B, tmp; pIItem->object().Center (A); if (A.distance_to_sqr(Position())>4) continue; tmp.sub(A, cam_Active()->vPosition); B.mad(cam_Active()->vPosition, cam_Active()->vDirection, tmp.dotproduct(cam_Active()->vDirection)); float len = B.distance_to_sqr(A); if (len > 1) continue; if (maxlen>len && !pIItem->object().getDestroy()) { maxlen = len; pNearestItem = pIItem; }; } if(pNearestItem) { CFrustum frustum; frustum.CreateFromMatrix (Device.mFullTransform,FRUSTUM_P_LRTB|FRUSTUM_P_FAR); if (!CanPickItem(frustum,Device.vCameraPosition,&pNearestItem->object())) pNearestItem = NULL; } HUD().GetUI()->UIMainIngameWnd->SetPickUpItem(pNearestItem); if (pNearestItem && m_bPickupMode) { //ïîäáèðàíèå îáúåêòà Game().SendPickUpEvent(ID(), pNearestItem->object().ID()); PickupModeOff(); } }; void CActor::PickupInfoDraw(CObject* object) { LPCSTR draw_str = NULL; CInventoryItem* item = smart_cast<CInventoryItem*>(object); //. CInventoryOwner* inventory_owner = smart_cast<CInventoryOwner*>(object); //. VERIFY(item || inventory_owner); if(!item) return; Fmatrix res; res.mul (Device.mFullTransform,object->XFORM()); Fvector4 v_res; Fvector shift; draw_str = item->Name/*Complex*/(); shift.set(0,0,0); res.transform(v_res,shift); if (v_res.z < 0 || v_res.w < 0) return; if (v_res.x < -1.f || v_res.x > 1.f || v_res.y<-1.f || v_res.y>1.f) return; float x = (1.f + v_res.x)/2.f * (Device.dwWidth); float y = (1.f - v_res.y)/2.f * (Device.dwHeight); HUD().Font().pFontLetterica16Russian->SetAligment (CGameFont::alCenter); HUD().Font().pFontLetterica16Russian->SetColor (PICKUP_INFO_COLOR); HUD().Font().pFontLetterica16Russian->Out (x,y,draw_str); } void CActor::feel_sound_new(CObject* who, int type, CSound_UserDataPtr user_data, const Fvector& Position, float power) { if(who == this) m_snd_noise = _max(m_snd_noise,power); }
{ "content_hash": "c42510f27016004852b8cd02a7cf5193", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 119, "avg_line_length": 27.81967213114754, "alnum_prop": 0.6624926340601061, "repo_name": "OLR-xray/XRay-NEW", "id": "c7e95a551c53b123a40da264cb3ddcc617f63308", "size": "6788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XRay/xr_3da/xrGame/Actor_Feel.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "62738" }, { "name": "Batchfile", "bytes": "7939" }, { "name": "C", "bytes": "24706439" }, { "name": "C++", "bytes": "42161717" }, { "name": "Groff", "bytes": "287360" }, { "name": "HTML", "bytes": "67830" }, { "name": "Lua", "bytes": "96997" }, { "name": "Makefile", "bytes": "16534" }, { "name": "Objective-C", "bytes": "175957" }, { "name": "Pascal", "bytes": "1259032" }, { "name": "Perl", "bytes": "9355" }, { "name": "PostScript", "bytes": "115918" }, { "name": "Shell", "bytes": "962" }, { "name": "TeX", "bytes": "2421274" }, { "name": "xBase", "bytes": "99233" } ], "symlink_target": "" }
package com.daniel.weixin.cp.bean; import org.testng.Assert; import org.testng.annotations.Test; @Test public class WxCpXmlOutImageMessageTest { public void test() { WxCpXmlOutImageMessage m = new WxCpXmlOutImageMessage(); m.setMediaId("ddfefesfsdfef"); m.setCreateTime(1122l); m.setFromUserName("from"); m.setToUserName("to"); String expected = "<xml>" + "<ToUserName><![CDATA[to]]></ToUserName>" + "<FromUserName><![CDATA[from]]></FromUserName>" + "<CreateTime>1122</CreateTime>" + "<MsgType><![CDATA[image]]></MsgType>" + "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>" + "</xml>"; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } public void testBuild() { WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build(); String expected = "<xml>" + "<ToUserName><![CDATA[to]]></ToUserName>" + "<FromUserName><![CDATA[from]]></FromUserName>" + "<CreateTime>1122</CreateTime>" + "<MsgType><![CDATA[image]]></MsgType>" + "<Image><MediaId><![CDATA[ddfefesfsdfef]]></MediaId></Image>" + "</xml>"; System.out.println(m.toXml()); Assert.assertEquals( m .toXml() .replaceAll("\\s", "") .replaceAll("<CreateTime>.*?</CreateTime>", ""), expected .replaceAll("\\s", "") .replaceAll("<CreateTime>.*?</CreateTime>", "") ); } }
{ "content_hash": "7ed4b2fe09e5e2f58857d370ec418310", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 120, "avg_line_length": 34.270833333333336, "alnum_prop": 0.5604863221884498, "repo_name": "danileyang/mmp", "id": "14e14defd12a9c72920594ed7fdfa9d9b923e988", "size": "1645", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "weixin-java-cp/src/test/java/com/daniel/weixin/cp/bean/WxCpXmlOutImageMessageTest.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "581507" } ], "symlink_target": "" }
package com.github.dmutti.annotations.strings; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface StringLength { /** tamanho minimo da string */ int min() default 0; /** tamanho maximo da string */ int max() default 0; }
{ "content_hash": "2fc28bfa2e03cba405ddb3c3fb189c89", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 19, "alnum_prop": 0.7039473684210527, "repo_name": "dmutti/object-validator", "id": "0f9f1f62b6fb817bd8a1fcdaad69b2ddb20f6a3f", "size": "920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/dmutti/annotations/strings/StringLength.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "62571" } ], "symlink_target": "" }
package com.mishiranu.dashchan.ui.preference; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.text.InputType; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.util.Pair; import android.view.View; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.ViewModelProvider; import chan.content.ChanMarkup; import chan.util.DataFile; import chan.util.StringUtils; import com.mishiranu.dashchan.C; import com.mishiranu.dashchan.R; import com.mishiranu.dashchan.content.CacheManager; import com.mishiranu.dashchan.content.Preferences; import com.mishiranu.dashchan.content.async.ExecutorTask; import com.mishiranu.dashchan.content.async.TaskViewModel; import com.mishiranu.dashchan.media.VideoPlayer; import com.mishiranu.dashchan.ui.FragmentHandler; import com.mishiranu.dashchan.ui.InstanceDialog; import com.mishiranu.dashchan.ui.preference.core.EditPreference; import com.mishiranu.dashchan.ui.preference.core.Preference; import com.mishiranu.dashchan.ui.preference.core.PreferenceFragment; import com.mishiranu.dashchan.util.ConcurrentUtils; import com.mishiranu.dashchan.util.IOUtils; import com.mishiranu.dashchan.util.ResourceUtils; import com.mishiranu.dashchan.util.SharedPreferences; import com.mishiranu.dashchan.widget.ProgressDialog; public class MediaFragment extends PreferenceFragment implements FragmentHandler.Callback { private static final String EXTRA_IN_STORAGE_REQUEST = "inStorageRequest"; private Preference<?> downloadUriTreePreference; private Preference<?> clearCachePreference; private boolean inStorageRequest; @Override protected SharedPreferences getPreferences() { return Preferences.PREFERENCES; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); inStorageRequest = savedInstanceState != null && savedInstanceState.getBoolean(EXTRA_IN_STORAGE_REQUEST); } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); addHeader(R.string.images); addList(Preferences.KEY_LOAD_THUMBNAILS, enumList(Preferences.NetworkMode.values(), v -> v.value), Preferences.DEFAULT_LOAD_THUMBNAILS.value, R.string.load_thumbnails, enumResList(Preferences.NetworkMode.values(), v -> v.titleResId)); addList(Preferences.KEY_LOAD_NEAREST_IMAGE, enumList(Preferences.NetworkMode.values(), v -> v.value), Preferences.DEFAULT_LOAD_NEAREST_IMAGE.value, R.string.load_nearest_image, enumResList(Preferences.NetworkMode.values(), v -> v.titleResId)); addHeader(R.string.downloads); addCheck(true, Preferences.KEY_DOWNLOAD_DETAIL_NAME, Preferences.DEFAULT_DOWNLOAD_DETAIL_NAME, R.string.detailed_file_name, R.string.detailed_file_name__summary); addCheck(true, Preferences.KEY_DOWNLOAD_ORIGINAL_NAME, Preferences.DEFAULT_DOWNLOAD_ORIGINAL_NAME, R.string.original_file_name, R.string.original_file_name__summary); if (C.USE_SAF) { downloadUriTreePreference = addButton(getString(R.string.download_directory), p -> DataFile.obtain(DataFile.Target.DOWNLOADS, null).getName()); downloadUriTreePreference.setOnClickListener(p -> { if (((FragmentHandler) requireActivity()).requestStorage()) { inStorageRequest = true; } }); } else { addEdit(Preferences.KEY_DOWNLOAD_PATH, null, R.string.download_path, C.DEFAULT_DOWNLOAD_PATH, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); } addList(Preferences.KEY_DOWNLOAD_SUBDIR, enumList(Preferences.DownloadSubdirMode.values(), v -> v.value), Preferences.DEFAULT_DOWNLOAD_SUBDIR.value, R.string.show_download_configuration_dialog, enumResList(Preferences.DownloadSubdirMode.values(), v -> v.titleResId)); EditPreference subdirectoryPreference = addEdit(Preferences.KEY_SUBDIR_PATTERN, Preferences.DEFAULT_SUBDIR_PATTERN, R.string.subdirectory_pattern, Preferences.DEFAULT_SUBDIR_PATTERN, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); String subdirectoryHtml = IOUtils.readRawResourceString(getResources(), R.raw.markup_subdirectory); subdirectoryPreference.setDescription(BUILDER_SUBDIRECTORY.fromHtmlReduced(subdirectoryHtml)); subdirectoryPreference.setNeutralButton(getString(R.string.more_info), () -> showSubdirectoryInfoDialog(getChildFragmentManager())); if (C.API_LOLLIPOP) { addCheck(true, Preferences.KEY_NOTIFY_DOWNLOAD_COMPLETE, Preferences.DEFAULT_NOTIFY_DOWNLOAD_COMPLETE, R.string.notify_when_download_is_completed, R.string.notify_when_download_is_completed__summary); } addHeader(R.string.video_player); Pair<Boolean, String> playerLoadResult = VideoPlayer.loadLibraries(requireContext()); if (!playerLoadResult.first) { if (playerLoadResult.second != null) { SpannableStringBuilder builder = new SpannableStringBuilder(playerLoadResult.second); if (builder.length() == 0) { builder.append(getString(R.string.unknown_error)); } builder.setSpan(new ForegroundColorSpan(ResourceUtils.getColor(requireContext(), R.attr.colorTextError)), 0, builder.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); addButton(null, builder).setSelectable(false); } else { addButton(0, R.string.requires_decoding_libraries__sentence).setSelectable(false); } } addCheck(true, Preferences.KEY_USE_VIDEO_PLAYER, Preferences.DEFAULT_USE_VIDEO_PLAYER, R.string.use_built_in_video_player, R.string.use_built_in_video_player__summary) .setEnabled(playerLoadResult.first); addList(Preferences.KEY_VIDEO_COMPLETION, enumList(Preferences.VideoCompletionMode.values(), o -> o.value), Preferences.DEFAULT_VIDEO_COMPLETION.value, R.string.action_on_playback_completion, enumResList(Preferences.VideoCompletionMode.values(), o -> o.titleResId)) .setEnabled(playerLoadResult.first); addCheck(true, Preferences.KEY_VIDEO_PLAY_AFTER_SCROLL, Preferences.DEFAULT_VIDEO_PLAY_AFTER_SCROLL, R.string.play_after_scroll, R.string.play_after_scroll__summary).setEnabled(playerLoadResult.first); addCheck(true, Preferences.KEY_VIDEO_SEEK_ANY_FRAME, Preferences.DEFAULT_VIDEO_SEEK_ANY_FRAME, R.string.seek_any_frame, R.string.seek_any_frame__summary).setEnabled(playerLoadResult.first); if (playerLoadResult.first) { addDependency(Preferences.KEY_VIDEO_COMPLETION, Preferences.KEY_USE_VIDEO_PLAYER, true); addDependency(Preferences.KEY_VIDEO_PLAY_AFTER_SCROLL, Preferences.KEY_USE_VIDEO_PLAYER, true); addDependency(Preferences.KEY_VIDEO_SEEK_ANY_FRAME, Preferences.KEY_USE_VIDEO_PLAYER, true); } addHeader(R.string.additional); addSeek(Preferences.KEY_CACHE_SIZE, Preferences.DEFAULT_CACHE_SIZE, getString(R.string.cache_size), "%d MB", null, Preferences.MIN_CACHE_SIZE, Preferences.MAX_CACHE_SIZE, Preferences.STEP_CACHE_SIZE); clearCachePreference = addButton(getString(R.string.clear_cache), p -> StringUtils.formatFileSizeMegabytes(CacheManager.getInstance().getCacheSize())); clearCachePreference.setOnClickListener(p -> { ClearCacheDialog dialog = new ClearCacheDialog(); dialog.show(getChildFragmentManager(), ClearCacheDialog.class.getName()); }); clearCachePreference.invalidate(); addDependency(Preferences.KEY_SUBDIR_PATTERN, Preferences.KEY_DOWNLOAD_SUBDIR, false, Preferences.DownloadSubdirMode.DISABLED.value); } @Override public void onDestroyView() { super.onDestroyView(); downloadUriTreePreference = null; clearCachePreference = null; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((FragmentHandler) requireActivity()).setTitleSubtitle(getString(R.string.media), null); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(EXTRA_IN_STORAGE_REQUEST, inStorageRequest); } @Override public void onStorageRequestResult() { if (inStorageRequest) { inStorageRequest = false; downloadUriTreePreference.invalidate(); } } private static void showSubdirectoryInfoDialog(FragmentManager fragmentManager) { new InstanceDialog(fragmentManager, null, provider -> { Context context = provider.getContext(); String html = IOUtils.readRawResourceString(context.getResources(), R.raw.markup_subdirectory_info); return new AlertDialog.Builder(context) .setTitle(R.string.subdirectory_pattern) .setMessage(BUILDER_SUBDIRECTORY.fromHtmlReduced(html)) .setPositiveButton(android.R.string.ok, null) .create(); }); } private static final ChanMarkup.MarkupBuilder BUILDER_SUBDIRECTORY = new ChanMarkup .MarkupBuilder(markup -> markup.addTag("b", ChanMarkup.TAG_BOLD)); public static class ClearCacheDialog extends DialogFragment { private static final String EXTRA_CHECKED_ITEMS = "checkedItems"; private boolean[] checkedItems; @NonNull @Override public AlertDialog onCreateDialog(Bundle savedInstanceState) { checkedItems = savedInstanceState != null ? savedInstanceState.getBooleanArray(EXTRA_CHECKED_ITEMS) : null; if (checkedItems == null) { checkedItems = new boolean[] {true, true}; } String[] items = {getString(R.string.thumbnails), getString(R.string.cached_files)}; return new AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.clear_cache)) .setMultiChoiceItems(items, checkedItems, (d, which, isChecked) -> checkedItems[which] = isChecked) .setPositiveButton(android.R.string.ok, (d, w) -> { ClearingDialog clearingDialog = new ClearingDialog(checkedItems[0], checkedItems[1]); clearingDialog.setTargetFragment(getParentFragment(), 0); clearingDialog.show(getParentFragment().getParentFragmentManager(), ClearingDialog.class.getName()); }) .setNegativeButton(android.R.string.cancel, null) .create(); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBooleanArray(EXTRA_CHECKED_ITEMS, checkedItems); } } public static class ClearingDialog extends DialogFragment { private static final String EXTRA_THUMBNAILS = "thumbnails"; private static final String EXTRA_MEDIA = "media"; public ClearingDialog() {} public ClearingDialog(boolean thumbnails, boolean media) { Bundle args = new Bundle(); args.putBoolean(EXTRA_THUMBNAILS, thumbnails); args.putBoolean(EXTRA_MEDIA, media); setArguments(args); } @NonNull @Override public ProgressDialog onCreateDialog(Bundle savedInstanceState) { ProgressDialog dialog = new ProgressDialog(requireContext(), null); dialog.setMessage(getString(R.string.clearing__ellipsis)); return dialog; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ClearCacheViewModel viewModel = new ViewModelProvider(this).get(ClearCacheViewModel.class); if (!viewModel.hasTaskOrValue()) { Bundle args = requireArguments(); boolean thumbnails = args.getBoolean(EXTRA_THUMBNAILS); boolean media = args.getBoolean(EXTRA_MEDIA); ClearCacheTask task = new ClearCacheTask(viewModel, thumbnails, media); task.execute(ConcurrentUtils.SEPARATE_EXECUTOR); viewModel.attach(task); } viewModel.observe(this, result -> { dismiss(); sendUpdateCacheSize(); }); } private void sendUpdateCacheSize() { ((MediaFragment) getTargetFragment()).clearCachePreference.invalidate(); } @Override public void onCancel(@NonNull DialogInterface dialog) { super.onCancel(dialog); sendUpdateCacheSize(); } } public static class ClearCacheViewModel extends TaskViewModel<ClearCacheTask, Object> {} private static class ClearCacheTask extends ExecutorTask<Void, Object> { private final ClearCacheViewModel viewModel; private final boolean thumbnails; private final boolean media; public ClearCacheTask(ClearCacheViewModel viewModel, boolean thumbnails, boolean media) { this.viewModel = viewModel; this.thumbnails = thumbnails; this.media = media; } @Override protected Void run() throws InterruptedException { if (thumbnails) { CacheManager.getInstance().eraseThumbnailsCache(); } if (isCancelled()) { return null; } if (media) { CacheManager.getInstance().eraseMediaCache(); } return null; } @Override protected void onComplete(Object result) { viewModel.handleResult(this); } } }
{ "content_hash": "0aef0095c27d8508205d58da78c17b73", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 110, "avg_line_length": 41.35294117647059, "alnum_prop": 0.7720088509562194, "repo_name": "Mishiranu/Dashchan", "id": "7f294c7492f0c6aa8a1f1505744bc8bff7af34b9", "size": "12654", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/mishiranu/dashchan/ui/preference/MediaFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "89128" }, { "name": "HTML", "bytes": "837" }, { "name": "Java", "bytes": "2403778" }, { "name": "JavaScript", "bytes": "4837" }, { "name": "Makefile", "bytes": "8511" } ], "symlink_target": "" }
package com.itheima.oschina.widget; import android.app.Activity; import android.support.v4.app.ShareCompat; import android.text.style.ClickableSpan; import android.view.View; public class EmailSpan extends ClickableSpan { private String email; public EmailSpan(String email) { this.email = email; } @Override public void onClick(View widget) { try { ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder .from((Activity)widget.getContext()); builder.setType("message/rfc822"); builder.addEmailTo(email); builder.setSubject(""); builder.setChooserTitle(""); builder.startChooser(); } catch (Exception e) { e.printStackTrace(); } } }
{ "content_hash": "602147c101192ee2b030af0919b9c3cf", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 64, "avg_line_length": 22.833333333333332, "alnum_prop": 0.7343065693430657, "repo_name": "CoderTang/Itheima72", "id": "872ca87923b4137e7300efd95ae2073b4b5f7ef6", "size": "685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "开源中国客户端T/src/com/itheima/oschina/widget/EmailSpan.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8121" }, { "name": "Java", "bytes": "548797" }, { "name": "JavaScript", "bytes": "488" } ], "symlink_target": "" }
<?php namespace model\database; use model\database\Connect\Connection; use PDO; class ProductImagesDao { //Make Singleton private static $instance; private $pdo; //Statements defined as constants const ADD_PRODUCT_IMAGE = "INSERT INTO images (image_url, product_id) VALUES (?, ?)"; const GET_PRODUCT_IMAGES = "SELECT image_url FROM images WHERE product_id = ?"; const GET_FIRST_IMAGE = "SELECT image_url FROM images WHERE product_id = ? LIMIT 1"; //Get connection in construct private function __construct() { $this->pdo = Connection::getInstance()->getConnection(); } public static function getInstance() { if (self::$instance === null) { self::$instance = new ProductImagesDao(); } return self::$instance; } /** * Function for adding product's image path to database. * @param ProductImage $image - Receives product's image path and product's ID. */ function addProductImage(ProductImage $image) { $statement = $this->pdo->prepare(self::ADD_PRODUCT_IMAGE); $statement->execute(array( $image->getImageUrl(), $image->getProductId())); } /** * Function for getting all images for product. * @param $productId - Receives product's ID. * @return array - Returns product's images in associative array. */ function getAllProductImages($productId) { $statement = $this->pdo->prepare(self::GET_PRODUCT_IMAGES); $statement->execute(array($productId)); $images = $statement->fetchAll(PDO::FETCH_ASSOC); return $images; } /** * Function for getting first product's image. * @param $productId - Receives product's ID. * @return mixed - Returns images path. */ function getFirstProductImage($productId) { $statement = $this->pdo->prepare(self::GET_FIRST_IMAGE); $statement->execute(array($productId)); $image = $statement->fetch(); return $image['image_url']; } }
{ "content_hash": "c0e870e38894ed961011291fb53b164c", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 89, "avg_line_length": 24.341176470588234, "alnum_prop": 0.6191396810053166, "repo_name": "lgadzhev/MagBuy", "id": "ce6ff689afd90601f95f38348c91ada5d6786f1b", "size": "2069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "model/database/ProductImagesDao.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "107250" }, { "name": "JavaScript", "bytes": "106302" }, { "name": "PHP", "bytes": "313316" } ], "symlink_target": "" }
DOUBTFUL #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "07539a497f4f7b54408abf13578e34cb", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "eaacfcf18c0f4c5373b054046498587afab9eaa2", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus dalmatinus/Rubus dalmatinus ardeatina/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
.. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .. _minimum-system-requirements: Minimum System Requirements --------------------------- Management Server, Database, and Storage System Requirements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The machines that will run the Management Server and MySQL database must meet the following requirements. The same machines can also be used to provide primary and secondary storage, such as via localdisk or NFS. The Management Server may be placed on a virtual machine. - Operating system: - Preferred: CentOS/RHEL 7.2+, CentOS/RHEL 6.8+ or Ubuntu 14.04(.2) or higher - 64-bit x86 CPU (more cores results in better performance) - 4 GB of memory - 250 GB of local disk (more results in better capability; 500 GB recommended) - At least 1 NIC - Statically allocated IP address - Fully qualified domain name as returned by the hostname command Host/Hypervisor System Requirements ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The host is where the cloud services run in the form of guest virtual machines. Each host is one machine that meets the following requirements: - Must support HVM (Intel-VT or AMD-V enabled). - 64-bit x86 CPU (more cores results in better performance) - Hardware virtualization support required - 4 GB of memory - 36 GB of local disk - At least 1 NIC - Latest hotfixes applied to hypervisor software - When you deploy CloudStack, the hypervisor host must not have any VMs already running - All hosts within a cluster must be homogeneous. The CPUs must be of the same type, count, and feature flags. Hosts have additional requirements depending on the hypervisor. See the requirements listed at the top of the Installation section for your chosen hypervisor: .. warning:: Be sure you fulfill the additional hypervisor requirements and installation steps provided in this Guide. Hypervisor hosts must be properly prepared to work with CloudStack. For example, the requirements for XenServer are listed under Citrix XenServer Installation.
{ "content_hash": "0bb3cf862f6fb15ff124258e9c65a7ed", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 81, "avg_line_length": 34.06024096385542, "alnum_prop": 0.7347010965688009, "repo_name": "apache/cloudstack-docs-install", "id": "153146214e15f315bb33a5578fbdee0cf88a7081", "size": "2827", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/overview/_requirements.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "807" }, { "name": "CSS", "bytes": "318" }, { "name": "HTML", "bytes": "16465" }, { "name": "Makefile", "bytes": "7668" }, { "name": "Python", "bytes": "14400" }, { "name": "Shell", "bytes": "59" } ], "symlink_target": "" }
<?php include 'header.php'; //==================== Insert New User ======================= if(isset($_POST['btnSave'])){ $cboBranch = $_POST['cboBranch']; $txtUserName = post('txtUserName'); $txtPassword = post('txtPassword'); $txtLevel = post('txtLevel'); $txtDescription = post('txtDescription'); $txtStatus = post('txtStatus'); $encrypted_pass = encrypt_decrypt('encrypt', $txtPassword); $insert=$db->query("CALL sp_Insert_UserAccount( '".time()."', '".$cboBranch."', N'".sql_quote($txtUserName)."', N'".sql_quote($encrypted_pass)."', '".sql_quote($txtLevel)."', N'".sql_quote($txtDescription)."', '".sql_quote($txtStatus)."' )"); if($insert){ cRedirect('userAccount.php'); } } ?> <body class="skin-blue"> <!-- header logo: style can be found in header.less --> <?php include 'nav.php';?> <!-- Left side column. contains the logo and sidebar --> <?php include 'menu.php';?> <!-- Right side column. Contains the navbar and content of the page --> <aside class="right-side"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="row"> <div class="col-xs-8"> <form role="form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label>Choose Branch</label> <select class="form-control" name="cboBranch"> <?php $select=$db->query("CALL sp_Branch_Select('')"); $rowselect=$db->dbCountRows($select); if($rowselect>0){ while($row=$db->fetch($select)){ $BranchID = $row->BranchID; $BranchName = $row->BranchName; echo'<option value='.$BranchID.'>'.$BranchName.'</option>'; } } ?> </select> <div class="form-group"> <label>User Name</label> <input name="txtUserName" class="form-control" placeholder="User Name" /> </div> <div class="form-group"> <label>Password</label> <input required name="txtPassword" type="password" class="form-control" placeholder="Password" /> </div> <div class="form-group"> <label>Level</label> <div class="radio"> <label> <input type="radio" name="txtLevel" id="optionsRadios1" value="1" checked> Admin </label> </div> <div class="radio"> <label> <input type="radio" name="txtLevel" id="optionsRadios2" value="2"> User </label> </div> </div> <div class="form-group"> <label>Description</label> <textarea class="form-control" name="txtDescription" rows="3"></textarea> </div> <div class="form-group"> <label>Status</label> <div class="radio"> <label> <input type="radio" name="txtStatus" id="optionsRadios1" value="1" checked> Active </label> </div> <div class="radio"> <label> <input type="radio" name="txtStatus" id="optionsRadios2" value="0"> Suspend </label> </div> </div> <div class="modal-footer"> <a href="userAccount.php"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </a> <input type="submit" name="btnSave" class="btn btn-primary" value="Save" /> </div> </form> </div> </div> </section> <!-- Main content --> </aside><!-- /.right-side --> </div><!-- ./wrapper --> <!-- add new calendar event modal --> <?php include 'footer.php';?>
{ "content_hash": "b147156bc5a2472bebb93361a6fc175c", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 141, "avg_line_length": 43.75, "alnum_prop": 0.33766233766233766, "repo_name": "khbuoyrupppiseth7/WebShop", "id": "21b38535b953a2b494ae7c84291218f26fae7c20", "size": "5775", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "WebShopV2/userAccount-new.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "725052" }, { "name": "HTML", "bytes": "2377813" }, { "name": "JavaScript", "bytes": "2450191" }, { "name": "PHP", "bytes": "1016128" } ], "symlink_target": "" }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class MdFilter3 extends React.Component<IconBaseProps, any> { }
{ "content_hash": "3b41369fdb4b34bcb87979c3cd510980", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 78, "avg_line_length": 53, "alnum_prop": 0.7672955974842768, "repo_name": "progre/DefinitelyTyped", "id": "891dd23d84fad8c4df3a8b8a7e31c89f44cf5336", "size": "187", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "react-icons/md/filter-3.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "HTML", "bytes": "308" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "20620621" } ], "symlink_target": "" }
PORTNAME= inn PORTVERSION= 2.2.2 CATEGORIES= news MASTER_SITES= ftp://ftp.isc.org/isc/inn/ PATCH_SITES= ftp://ftp.north.ad.jp/pub/IPv6/INN/ PATCHFILES= inn-2.2.2-v6-19991224.diff.gz PATCH_DIST_STRIP= -p1 # Based on torstenb's port (1999/05/02) MAINTAINER= kobayasi@north.ad.jp Y2K= http://www.isc.org/inn-y2k.html USE_PERL5=YES .if exists(/var/news) INN_NEWSSPOOL?=/var/news .else INN_NEWSSPOOL?=/var/spool/news .endif INN_NEWSLIB?=${PREFIX}/news INN_NEWSLOG?=/var/log/news HAS_CONFIGURE= yes CONFIGURE_ENV+= MANDIR=${PREFIX}/man CONFIGURE_ARGS+= --prefix=${INN_NEWSLIB} CONFIGURE_ARGS+= --with-spool-dir=${INN_NEWSSPOOL} CONFIGURE_ARGS+= --with-log-dir=${INN_NEWSLOG} CONFIGURE_ARGS+= --with-perl # Various Options. See ${WRKSRC}/INSTALL for details # Use tagged hash table for the history database. Uses much less memory but # is somewhat slower #CONFIGURE_ARGS+= --enable-tagged-hash MAN1= convdate.1 getlist.1 grephistory.1 inews.1 innconfval.1 innfeed.1 \ installit.1 nntpget.1 rnews.1 shlock.1 shrinkfile.1 startinnfeed.1 \ subst.1 MAN3= clientlib.3 dbz.3 inndcomm.3 libinn.3 libstorage.3 parsedate.3 qio.3 \ wildmat.3 MAN5= active.5 control.ctl.5 cycbuff.conf.5 distrib.pats.5 expire.ctl.5 \ history.5 incoming.conf.5 inn.conf.5 innfeed.conf.5 innwatch.ctl.5 \ moderators.5 motd.news.5 newsfeeds.5 newslog.5 nnrp.access.5 \ nnrpd.track.5 nntpsend.ctl.5 overview.ctl.5 overview.fmt.5 \ passwd.nntp.5 storage.conf.5 storage.ctl.5 MAN8= actived.8 actsync.8 actsyncd.8 archive.8 batcher.8 buffchan.8 \ cnfsstat.8 controlchan.8 crosspost.8 ctlinnd.8 cvtbatch.8 expire.8 \ expireindex.8 expireover.8 expirerm.8 fastrm.8 filechan.8 inncheck.8 \ innd.8 inndf.8 innreport.8 innstat.8 innwatch.8 innxbatch.8 innxmit.8 \ mailpost.8 makeactive.8 makehistory.8 news-recovery.8 news.daily.8 \ news2mail.8 newslog.8 newsrequeue.8 nnrpd.8 nntpsend.8 overchan.8 \ pgpverify.8 prunehistory.8 pullnews.8 scanlogs.8 send-uucp.8 sm.8 \ tally.control.8 tally.unwanted.8 writelog.8 post-install: ${SED} <${FILESDIR}/innd.sh >${PREFIX}/v6/etc/rc.d/innd.sh \ s+!!PREFIX!!+${PREFIX}+g && chmod +x ${PREFIX}/v6/etc/rc.d/innd.sh .include <bsd.port.mk>
{ "content_hash": "7fc7c28f2d154ccb5e912a012535fd31", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 76, "avg_line_length": 35.442622950819676, "alnum_prop": 0.7428307123034228, "repo_name": "MarginC/kame", "id": "1551440bfee268287ac521b8a0cd1a5ecd560de5", "size": "2361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "freebsd3/ports/inn/Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arc", "bytes": "7491" }, { "name": "Assembly", "bytes": "14375563" }, { "name": "Awk", "bytes": "313712" }, { "name": "Batchfile", "bytes": "6819" }, { "name": "C", "bytes": "356715789" }, { "name": "C++", "bytes": "4231647" }, { "name": "DIGITAL Command Language", "bytes": "11155" }, { "name": "Emacs Lisp", "bytes": "790" }, { "name": "Forth", "bytes": "253695" }, { "name": "GAP", "bytes": "9964" }, { "name": "Groff", "bytes": "2220485" }, { "name": "Lex", "bytes": "168376" }, { "name": "Logos", "bytes": "570213" }, { "name": "Makefile", "bytes": "1778847" }, { "name": "Mathematica", "bytes": "16549" }, { "name": "Objective-C", "bytes": "529629" }, { "name": "PHP", "bytes": "11283" }, { "name": "Perl", "bytes": "151251" }, { "name": "Perl6", "bytes": "2572" }, { "name": "Ruby", "bytes": "7283" }, { "name": "Scheme", "bytes": "76872" }, { "name": "Shell", "bytes": "583253" }, { "name": "Stata", "bytes": "408" }, { "name": "Yacc", "bytes": "606054" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain { public enum EntityStateOption { Active, Deleted, } public abstract class BaseEntity { public EntityStateOption EntityState { get; set; } public bool HasChanges { get; set; } public bool IsNew { get; set; } public bool Isvalied { get { return Checkvalied(); } } public abstract bool Checkvalied(); } }
{ "content_hash": "81a132184a5489c8bd6e9b0a6ac4ecad", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 58, "avg_line_length": 20.925925925925927, "alnum_prop": 0.5893805309734513, "repo_name": "asachanxxx/HRM", "id": "f918a82544f9dea436d348e101ff6392b371b277", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AdminLTEMVC/Domain/BaseEntity.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "195522" }, { "name": "CSS", "bytes": "384949" }, { "name": "HTML", "bytes": "1904400" }, { "name": "JavaScript", "bytes": "2868303" }, { "name": "PHP", "bytes": "3841" }, { "name": "PowerShell", "bytes": "188945" } ], "symlink_target": "" }
<?php //namespace Library\Core; class Data { public function __get($property) { if (property_exists($this, $property)) { return $this->$property; } } public function __set($property, $value) { //if (property_exists($this, $property)) { $this->$property = $value; //} return $this; } public function __unset($property){ if (property_exists($this, $property)) { unset($this->$property); } } } ?>
{ "content_hash": "8ef298d2679c7cd44ac4a1c4346619ae", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 50, "avg_line_length": 20.84, "alnum_prop": 0.4990403071017274, "repo_name": "ydk2/ymvc", "id": "a491c552730f49e16daa16ef8c900e553d4e9e30", "size": "521", "binary": false, "copies": "2", "ref": "refs/heads/3.0", "path": ".history/library/core/datat_20170730104102.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1245639" }, { "name": "HTML", "bytes": "30589" }, { "name": "JavaScript", "bytes": "568925" }, { "name": "PHP", "bytes": "37102073" }, { "name": "Shell", "bytes": "296" }, { "name": "XSLT", "bytes": "203785" } ], "symlink_target": "" }
package com.googlecode.dex2jar.reader.io; import java.io.File; public class LeRandomAccessFileInput extends BeRandomAccessFileInput { public LeRandomAccessFileInput(File file) { super(file); } @Override public int readUShortx() { return readUByte() | (readUByte() << 8); } @Override public int readUIntx() { return readUByte() | (readUByte() << 8) | (readUByte() << 16) | (readUByte() << 24); } @Override public int readIntx() { return readUIntx(); } @Override public int readShortx() { return (short) readUShortx(); } }
{ "content_hash": "d74f2279c132bd65cc3c43e557b3086f", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 92, "avg_line_length": 20, "alnum_prop": 0.5696969696969697, "repo_name": "acgmohu/android-toolkit", "id": "67f6198c2b9fea939fc0ceef98d228515b1d4d3b", "size": "1279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dex-reader/src/main/java/com/googlecode/dex2jar/reader/io/LeRandomAccessFileInput.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "3534" }, { "name": "Java", "bytes": "1057352" } ], "symlink_target": "" }
package com.shootbox.t_fragment_activity; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; /** * Created by yangyankai on 2015/11/17. */ public class LeftFragment extends Fragment { /** Acitivity要实现这个接口,这样Fragment和Activity就可以共享事件触发的资源了 */ public interface MyListener { public void showMessage(int index); } private MyListener myListener; private Button firstButton; private Button secondButton; private Button thirdButton; /** Fragment第一次附属于Activity时调用,在onCreate之前调用 */ @Override public void onAttach(Activity activity) { super.onAttach(activity); System.out.println("LeftFragment--->onAttach"); myListener = (MyListener) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("LeftFragment--->onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("LeftFragment--->onCreateView"); return inflater.inflate(R.layout.leftfragment, container, false); } @Override public void onResume() { super.onResume(); System.out.println("LeftFragment--->onResume"); firstButton = (Button) getActivity().findViewById(R.id.first_button); secondButton = (Button) getActivity().findViewById(R.id.second_button); thirdButton = (Button) getActivity().findViewById(R.id.third_button); MyButtonClickListener clickListener = new MyButtonClickListener(); firstButton.setOnClickListener(clickListener); secondButton.setOnClickListener(clickListener); thirdButton.setOnClickListener(clickListener); } /** 按钮的监听器 */ class MyButtonClickListener implements View.OnClickListener { public void onClick(View v) { Button button = (Button) v; if (button == firstButton) myListener.showMessage(1); if (button == secondButton) myListener.showMessage(2); if (button == thirdButton) myListener.showMessage(3); } } }
{ "content_hash": "25850ad1d5dd0d92a1be502f96b5cb33", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 98, "avg_line_length": 25.035714285714285, "alnum_prop": 0.7589158345221113, "repo_name": "yangyankai/Fragment-fragment-callbackListener", "id": "e6a5c09e85d9fcd560f458e98e91036b39eb3251", "size": "2443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/shootbox/t_fragment_activity/LeftFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5850" } ], "symlink_target": "" }
title: Portfolio permalink: portfolio/webb/ layout: portfolio-category header-title: <a href="/portfolio">Portfolio</a> header-text: Webbprojekt category: webb ---
{ "content_hash": "4b95fd69f795142f7a7fdc4ce1a23a9b", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 48, "avg_line_length": 23.428571428571427, "alnum_prop": 0.774390243902439, "repo_name": "webbab2/webbab2.github.io", "id": "bbbc285a62a2e4c2ccaa6796f4529ab997909104", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "portfolio-kategorier/webb.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "37321" }, { "name": "HTML", "bytes": "178981" }, { "name": "JavaScript", "bytes": "152345" } ], "symlink_target": "" }
package com.intellij.json.editor; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.ide.actions.CopyReferenceAction; import com.intellij.json.JsonBundle; import com.intellij.json.JsonUtil; import com.intellij.json.navigation.JsonQualifiedNameKind; import com.intellij.json.navigation.JsonQualifiedNameProvider; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; public class JsonCopyPointerAction extends CopyReferenceAction { public JsonCopyPointerAction() { } @Override public void update(@NotNull AnActionEvent e) { super.update(e); e.getPresentation().setText(JsonBundle.message("copy.json.pointer")); DataContext dataContext = e.getDataContext(); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); VirtualFile file = editor == null ? null : FileDocumentManager.getInstance().getFile(editor.getDocument()); e.getPresentation().setVisible(file != null && JsonUtil.isJsonFile(file, editor.getProject())); } @Override protected String getQualifiedName(Editor editor, List<? extends PsiElement> elements) { if (elements.size() != 1) return null; return JsonQualifiedNameProvider.generateQualifiedName(elements.get(0), JsonQualifiedNameKind.JsonPointer); } @NotNull @Override protected List<PsiElement> getPsiElements(DataContext dataContext, Editor editor) { List<PsiElement> elements = super.getPsiElements(dataContext, editor); if (!elements.isEmpty()) return elements; PsiElement location = ConfigurationContext.getFromContext(dataContext, ActionPlaces.UNKNOWN).getPsiLocation(); if (location == null) return elements; PsiElement parent = location.getParent(); return parent != null ? Collections.singletonList(parent) : elements; } }
{ "content_hash": "eb1dc3d857e3b9bc58048d90fed4eaa0", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 114, "avg_line_length": 42.55769230769231, "alnum_prop": 0.7912336195210122, "repo_name": "siosio/intellij-community", "id": "634f243f861766459374c2dbf99c52a0a3e724d7", "size": "2354", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "json/src/com/intellij/json/editor/JsonCopyPointerAction.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package hydrograph.engine.jaxb.groupcombine; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for type-transform-expression complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="type-transform-expression"> * &lt;complexContent> * &lt;restriction base="{hydrograph/engine/jaxb/commontypes}type-transform-expression"> * &lt;sequence> * &lt;element name="inputFields" type="{hydrograph/engine/jaxb/groupcombine}type-operation-input-fields" minOccurs="0"/> * &lt;element name="outputFields" type="{hydrograph/engine/jaxb/commontypes}type-expression-output-fields" minOccurs="0"/> * &lt;element name="properties" type="{hydrograph/engine/jaxb/commontypes}type-properties" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="expr" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="mergeExpr" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="accumulatorInitalValue" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;anyAttribute/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "type-transform-expression", namespace = "hydrograph/engine/jaxb/groupcombine") public class TypeTransformExpression extends hydrograph.engine.jaxb.commontypes.TypeTransformExpression { }
{ "content_hash": "0eb16ff3a09a141251353080df2f58b1", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 131, "avg_line_length": 40.906976744186046, "alnum_prop": 0.709494030699261, "repo_name": "capitalone/Hydrograph", "id": "edc1bfe64d6de54648970b50899d1a966381c478", "size": "2372", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hydrograph.engine/hydrograph.engine.core/src/main/java/hydrograph/engine/jaxb/groupcombine/TypeTransformExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "9581" }, { "name": "CSS", "bytes": "162185" }, { "name": "HTML", "bytes": "1036397" }, { "name": "Java", "bytes": "10606203" }, { "name": "Scala", "bytes": "1464765" }, { "name": "Shell", "bytes": "12318" } ], "symlink_target": "" }
package abi42_0_0.expo.modules.constants; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.UUID; /** * An installation ID provider - it solves two purposes: * - in installations that have a legacy UUID persisted * in shared-across-expo-modules SharedPreferences, * migrates the UUID from there to a non-backed-up file, * - provides/creates a UUID unique per an installation. * * Similar class exists in expoview and expo-notifications. */ public class ExponentInstallationId { private static final String TAG = ExponentInstallationId.class.getSimpleName(); public static final String LEGACY_UUID_KEY = "uuid"; public static final String UUID_FILE_NAME = "expo_installation_uuid.txt"; private static final String PREFERENCES_FILE_NAME = "host.exp.exponent.SharedPreferences"; private String mUuid; private Context mContext; private SharedPreferences mSharedPreferences; /* package */ ExponentInstallationId(Context context) { mContext = context; mSharedPreferences = context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE); } public String getUUID() { // If it has already been cached, return the value. if (mUuid != null) { return mUuid; } // Read from non-backed-up storage File uuidFile = getNonBackedUpUuidFile(); try (FileReader fileReader = new FileReader(uuidFile); BufferedReader bufferedReader = new BufferedReader(fileReader)) { // Cache for future calls mUuid = UUID.fromString(bufferedReader.readLine()).toString(); } catch (IOException | IllegalArgumentException e) { // do nothing, try other sources } // We could have returned inside try clause, // but putting it like this here makes it immediately // visible. if (mUuid != null) { return mUuid; } // In November 2020 we decided to move installationID (backed by LEGACY_UUID_KEY value) from backed-up SharedPreferences // to a non-backed-up text file to fix issues where devices restored from backups have the same installation IDs // as the devices where the backup was created. String legacyUuid = mSharedPreferences.getString(LEGACY_UUID_KEY, null); if (legacyUuid != null) { mUuid = legacyUuid; boolean uuidHasBeenSuccessfullyMigrated = true; try (FileWriter writer = new FileWriter(uuidFile)) { writer.write(legacyUuid); } catch (IOException e) { uuidHasBeenSuccessfullyMigrated = false; Log.e(TAG, "Error while migrating UUID from legacy storage. " + e); } // We only remove the value from old storage once it's set and saved in the new storage. if (uuidHasBeenSuccessfullyMigrated) { mSharedPreferences.edit().remove(LEGACY_UUID_KEY).apply(); } } // Return either value from legacy storage or null return mUuid; } public String getOrCreateUUID() { String uuid = getUUID(); if (uuid != null) { return uuid; } // We persist the new UUID in "session storage" // so that if writing to persistent storage // fails subsequent calls to get(orCreate)UUID // return the same value. mUuid = UUID.randomUUID().toString(); try (FileWriter writer = new FileWriter(getNonBackedUpUuidFile())) { writer.write(mUuid); } catch (IOException e) { Log.e(TAG, "Error while writing new UUID. " + e); } return mUuid; } private File getNonBackedUpUuidFile() { return new File(mContext.getNoBackupFilesDir(), UUID_FILE_NAME); } }
{ "content_hash": "90a556efc09d9c90dedfd846c9e49088", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 124, "avg_line_length": 33.95454545454545, "alnum_prop": 0.7022757697456493, "repo_name": "exponent/exponent", "id": "7c85e8fba44ff294177c4cd17b660236f5eeaf32", "size": "3735", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/constants/ExponentInstallationId.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "113276" }, { "name": "Batchfile", "bytes": "127" }, { "name": "C", "bytes": "1744836" }, { "name": "C++", "bytes": "1801159" }, { "name": "CSS", "bytes": "7854" }, { "name": "HTML", "bytes": "176329" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "6251130" }, { "name": "JavaScript", "bytes": "4416558" }, { "name": "Makefile", "bytes": "18061" }, { "name": "Objective-C", "bytes": "13971362" }, { "name": "Objective-C++", "bytes": "725480" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "125673" }, { "name": "Ruby", "bytes": "61190" }, { "name": "Shell", "bytes": "4441" } ], "symlink_target": "" }
/* $Gateweaver: display.c,v 1.59 2007/09/24 14:31:27 cmaxwell Exp $ */ /* * Copyright (c) 2005 Christopher Maxwell. All rights reserved. */ #include <sys/ioctl.h> #include <sys/time.h> #include <sys/param.h> #include <ctype.h> #include <curses.h> #include <err.h> #include <event.h> #include <signal.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include "chopstix.h" RCSID("$Gateweaver: display.c,v 1.59 2007/09/24 14:31:27 cmaxwell Exp $"); static struct display display; static struct event evsig_winch, evsig_int; static ChopstixForm *curform; static ChopstixForm *curform_butwindow; enum { STATE_QTY, STATE_CODE } state; int ordertop; int debugscreen = 0; int printfailed = 0; static void display_sighdlr(int, short, void *); static void display_keycb(int); #define GETCENTRE(str) \ (strlen((str)) >= COLS ? 0 : ((COLS - strlen((str))) / 2)); void display_init(void) { bzero(&display, sizeof(display)); if (initscr() == NULL) err(1, "cannot initialize display"); if (has_colors() != FALSE) display.has_colour = 1; if (display.has_colour) { start_color(); #if 1 #define CHOPSTIX_BACKGROUND COLOR_BLACK init_pair(1, COLOR_WHITE, CHOPSTIX_BACKGROUND); /* NORMAL */ bkgdset(CHOPSTIX_COLOR_NORMAL); clear(); init_pair(2, COLOR_WHITE, COLOR_BLUE); /* STATUS */ init_pair(3, COLOR_YELLOW, COLOR_RED); /* ERROR */ init_pair(4, CHOPSTIX_BACKGROUND, COLOR_WHITE); /* FORM */ init_pair(5, COLOR_WHITE, COLOR_RED); /* ALERT */ init_pair(6, COLOR_CYAN, CHOPSTIX_BACKGROUND); /* TITLE */ init_pair(7, COLOR_YELLOW, COLOR_BLUE); /* HELP */ init_pair(8, COLOR_WHITE, COLOR_BLUE); /* WINDOW */ #else #define CHOPSTIX_BACKGROUND COLOR_WHITE init_pair(1, COLOR_BLACK, CHOPSTIX_BACKGROUND); /* NORMAL */ bkgdset(CHOPSTIX_COLOR_NORMAL); clear(); init_pair(2, COLOR_WHITE, COLOR_BLUE); /* STATUS */ init_pair(3, COLOR_YELLOW, COLOR_RED); /* ERROR */ init_pair(4, COLOR_WHITE, COLOR_RED); /* FORM */ init_pair(5, COLOR_WHITE, COLOR_RED); /* ALERT */ init_pair(6, COLOR_BLUE, CHOPSTIX_BACKGROUND); /* TITLE */ init_pair(7, COLOR_YELLOW, COLOR_BLUE); /* HELP */ init_pair(8, COLOR_WHITE, COLOR_BLUE); /* WINDOW */ #endif } /* enable arrows and function keys */ keypad(stdscr, TRUE); /* disable line buffering, but keep interrupts */ cbreak(); /* echoing is handled by us */ noecho(); /* force getch() to be non-blocking for use with libevent */ nodelay(stdscr, TRUE); /* hook SIGWINCH to handle terminal resizing */ signal_set(&evsig_winch, SIGWINCH, display_sighdlr, NULL); signal_add(&evsig_winch, NULL); /* do not allow SIGINT to terminate */ signal_set(&evsig_int, SIGINT, display_sighdlr, NULL); signal_add(&evsig_int, NULL); state = STATE_QTY; ordertop = 1; input_set_keycb(&display_keycb); curform = &addrform; } /* * str is an optional label (ie: 'PST') */ void display_money(int money, char *str) { char number[ALIGN_MONEYWIDTH + 1]; int y, x; int tx, cx; /* steal the line pointer */ getyx(stdscr, y, x); snprintf(number, sizeof(number), "$%s%d.%02d", NEGSIGN(money), DOLLARS(money), CENTS(money)); if (str) { /* 7 allows 999.99 orders without misaligning labels */ cx = COLS - MAX(strlen(number), ALIGN_MONEY) - strlen(str) - strlen(CHOPSTIX_FORM_LABEL); for (tx = x; tx < cx; tx++) ADDCH(NORMAL, ' '); ADDSTR(NORMAL, str); cx = COLS - MAX(strlen(number), ALIGN_MONEY) - strlen(CHOPSTIX_FORM_LABEL); for (tx = x; tx < cx; tx++) ADDCH(NORMAL, ' '); ADDSTR(NORMAL, CHOPSTIX_FORM_LABEL); } else { cx = COLS - MAX(strlen(number), ALIGN_MONEY); for (tx = x; tx < cx; tx++) ADDCH(NORMAL, ' '); } x = COLS - strlen(number); MVADDSTR(NORMAL, y, x, number); } void display_pad(void) { int y, x; getyx(stdscr, y, x); while (x++ < COLS) addch(' '); } /* * Redisplay the top header */ void display_header(ChopstixHeader *hdr) { int centre; /* horizontal line */ attron(CHOPSTIX_COLOR_HELP); mvhline(LINE_TITLE, 0, ACS_HLINE, COLS); attroff(CHOPSTIX_COLOR_HELP); move(LINE_TITLE, 0); ADDSTR(HELP | A_BOLD, "F1"); ADDSTR(HELP, ":Help "); ADDSTR(HELP | A_BOLD, "F2"); ADDSTR(HELP, ":Recall "); ADDSTR(HELP | A_BOLD, "F4"); ADDSTR(HELP, ":ChPhone "); ADDSTR(HELP | A_BOLD, "F7"); ADDSTR(HELP, ":New"); move(LINE_TITLE, COLS - strlen("F8:ReRrnt F10:Cred F11:Disc F12:Dlvry")); ADDSTR(HELP | A_BOLD, "F8"); ADDSTR(HELP, ":RePrnt "); ADDSTR(HELP | A_BOLD, "F10"); ADDSTR(HELP, ":Cred "); ADDSTR(HELP | A_BOLD, "F11"); ADDSTR(HELP, ":Disc "); ADDSTR(HELP | A_BOLD, "F12"); ADDSTR(HELP, ":Dlvry"); /* Company Name */ centre = GETCENTRE(hdr->company); MVADDSTR(TITLE, LINE_TITLE, centre, hdr->company); } void display_form(ChopstixForm *form) { ChopstixFormField *ff; int lwidth = 0, len = 0, fwidth, this = 0, i, thislwidth; const char *str; /* align the input columns */ lwidth = form_getalign(form); TAILQ_FOREACH(ff, &form->fields, entry) { this++; /* start HERE */ move(ff->y, ff->x); /* if no width set, use to end of screen */ fwidth = ff->w ? (ff->w - 1) : (COLS - ff->x - 1); /* label */ if (ff->label) { ADDSTR(NORMAL, ff->label); ADDSTR(NORMAL, form->labelsep); } len = ff->label ? (strlen(ff->label) + strlen(form->labelsep)) : 0; if (form_doalign(form, ff)) thislwidth = lwidth; else thislwidth = len; /* pad the label */ if (thislwidth) while (len++ < thislwidth) ADDCH(NORMAL, ' '); /* set maximum input width */ if (ff->iw) fwidth = MIN((len + ff->iw - 1), fwidth); /* copy the field string. note: len == thislwidth */ i = 0; /* XXX roving field header */ if (curform == form && form_field_active(form, ff)) attron(CHOPSTIX_COLOR_FORM); if ((str = form_field_getstr(ff))) { if (ff->rightalign) while (len <= fwidth - strlen(str)) { addch(CHOPSTIX_CHAR_FORM); len++; } while (*str) { if (len <= fwidth) { addch(*str++); } else { i++; len = thislwidth; move(ff->y + i, ff->x + len); if (i >= ff->l) break; addch(*str++); } len++; } } /* pad the field */ while (i < ff->l) { while (len <= fwidth) { addch(CHOPSTIX_CHAR_FORM); len++; } len = thislwidth; i++; move(ff->y + i, len); } attroff(CHOPSTIX_COLOR_FORM); } } void display_window(ChopstixForm *form) { int y = LINES, x = COLS, wy = 0, wx = 0, wiw = 0; int i, j; ChopstixFormField *ff; TAILQ_FOREACH(ff, &form->fields, entry) { if (ff->y < y) y = ff->y; if (ff->x < x) x = ff->x; if ((ff->y + ff->l) > wy) wy = ff->y + ff->l; if ((ff->x + ff->w) > wx) wx = ff->x + ff->w; if (ff->label) { if (ff->iw + strlen(ff->label) > wiw) wiw = ff->iw + strlen(ff->label); } else { if (ff->iw > wiw) wiw = ff->iw; } } if (wx - x > wiw) wiw = wx - x; if (form->labelsep) wiw += strlen(form->labelsep); attron(CHOPSTIX_COLOR_WINDOW); for (j = y - 1; j < wy + 1; j++) { move(j, x - 1); for (i = x - 1; i < x + wiw + 1; i++) addch(' '); } display_form(form); attroff(CHOPSTIX_COLOR_WINDOW); } /* * Deal with order display. This is the only part allowed to move the cursor * willy-nilly */ void display_order(ChopstixOrder *order) { /* print the address block */ display_form(&addrform); /* get ready for the order screen */ mvhline(LINE_ORDER, 0, ACS_HLINE, COLS); if (order->date > 0) { char s[ALIGN_NUMBER + CHOPSTIX_DATE_SIZE + sizeof("[/]")]; int x, len; len = snprintf(s, sizeof(s), "[%d/", order->key); strftime(s + len, sizeof(s) - len, CHOPSTIX_DATE_FORMAT "]", localtime(&order->date)); x = COLS - strlen(s); MVADDSTR(ALERT, LINE_ORDER, x, s); } /* display the order fields */ display_order_title(LINE_ORDER + 1); display_form(&orderform); if (WINDOW_TEST(curform)) display_window(curform); /* Help text */ move(LINE_TOTAL, 0); ADDSTR(HELP | A_BOLD, "Tab/Enter"); ADDSTR(HELP, ":Store "); ADDSTR(HELP | A_BOLD, "Ins/Del"); ADDSTR(HELP, ":Special "); ADDSTR(HELP | A_BOLD, "^P"); ADDSTR(HELP, ":Post "); ADDSTR(HELP | A_BOLD, "^L"); ADDSTR(HELP, ":Refresh "); ADDSTR(HELP | A_BOLD, "F5"); ADDSTR(HELP, ":DailyTotal "); ADDSTR(HELP | A_BOLD, "F3"); ADDSTR(HELP, ":LastPhone "); ADDSTR(HELP | A_BOLD, "^X"); ADDSTR(HELP, ":Exit"); attron(CHOPSTIX_COLOR_HELP); display_pad(); attroff(CHOPSTIX_COLOR_HELP); /* display the subtotal */ move(LINE_TOTAL + 1, 0); display_money(order->total.subtotal, "Subtotal"); move(LINE_TOTAL + 2, 0); if (order->total.discount && order->total.credit > 0) display_money(DISCOUNT(&order->total) + order->total.credit, "Disc+Crd"); else if (order->total.credit > 0) display_money(DISCOUNT(&order->total) + order->total.credit, "Credit"); else display_money(DISCOUNT(&order->total), "Discount"); move(LINE_TOTAL + 3, 0); display_money(DELIVERY(&order->total), "Delivery"); move(LINE_TOTAL + 4, 0); display_money(order->total.tax1, config.tax1name); move(LINE_TOTAL + 5, 0); display_money(order->total.tax2, config.tax2name); move(LINE_TOTAL + 6, 0); display_money(order->total.total, "Total"); /* special instructions, printed to left of totals */ display_form(&specialform); /* payment info */ display_form(&payform); if (LINES < LINE_TITLE_SIZE + 1 + LINE_ORDER_MINSIZE + LINE_TOTAL_SIZE + LINE_STATUS_SIZE ) status_set("SCREEN TOO SMALL!"); } void display_order_title(int line) { move(line, 0); ADDSTR(TITLE, "Item"); move(line, 6); ADDSTR(TITLE, "Qty."); move(line, 12); ADDSTR(TITLE, "Code"); move(line, 18); ADDSTR(TITLE, "Description"); move(line, COLS - 5); ADDSTR(TITLE, "Price"); } void display_status(ChopstixStatus *status) { move(LINE_STATUS, 0); clrtoeol(); if (status->bad) attron(CHOPSTIX_COLOR_ERROR); else attron(CHOPSTIX_COLOR_STATUS); addstr(status->status); display_pad(); if (status->bad) attroff(CHOPSTIX_COLOR_ERROR); else attroff(CHOPSTIX_COLOR_STATUS); } /* * Display any credits/complaints the customer has on file in the database. * Complaints are never removed, though credits are applied down to zero. */ void display_credits(ChopstixOrder *order) { int cnum; char str[sizeof("[COMPLAINTS: ]") + ALIGN_NUMBER]; if ((cnum = customer_getcredits(&order->customer)) > 0) { snprintf(str, sizeof(str), "[COMPLAINTS: %d]", cnum); attron(CHOPSTIX_COLOR_ALERT | A_BOLD); mvaddstr(LINE_STATUS, COLS - strlen(str), str); attroff(CHOPSTIX_COLOR_ALERT | A_BOLD); } } void display_refresh(void) { int y, x; if (debugscreen) for (y = 0; y < LINES; y++) { move(y, 0); for (x = 0; x < COLS; x++) ADDCH(NORMAL, 'X'); } display_header(&header); display_order(&order); display_status(&status); display_credits(&order); form_getyx(curform, y, x); if (debugscreen) mvprintw(0,0,"cy:%d cx:%d ot:%d", y, x, ordertop); /* set the cursor */ move(MIN(y, LINES), MIN(x, COLS - 1)); refresh(); } void display_exit(void) { if (display.has_colour) { attroff(CHOPSTIX_COLOR_STATUS); attroff(CHOPSTIX_COLOR_ERROR); attroff(CHOPSTIX_COLOR_FORM); attroff(CHOPSTIX_COLOR_ALERT); attroff(CHOPSTIX_COLOR_TITLE); } endwin(); } static void display_sighdlr(int sig, short which, void *arg) { switch (sig) { case SIGINT: status_set("Press Ctrl-X to exit"); display_refresh(); break; case SIGWINCH: { struct winsize ws; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) resizeterm(ws.ws_row, ws.ws_col); /* clear before refresh */ clear(); /* reinit order form */ order_reinit(LINE_ORDER_SIZE - 1, &ordertop); order_refresh(ordertop); /* reinit lower level forms */ special_reinit(); payment_reinit(); window_reinit(); display_refresh(); } break; } } static void display_keycb(int ch) { ChopstixFormAction a = FIELD_POS_NONE; ChopstixFormField *ff; int lines; reprocess: switch (ch) { case KEY_DOWN: a = form_driver(curform, FIELD_POS_DOWN); break; case KEY_UP: a = form_driver(curform, FIELD_POS_UP); break; case KEY_LEFT: a = form_driver(curform, FIELD_POS_LEFT); break; case KEY_RIGHT: a = form_driver(curform, FIELD_POS_RIGHT); break; case KEY_HOME: a = form_driver(curform, FIELD_POS_HOME); break; case KEY_END: a = form_driver(curform, FIELD_POS_END); break; case KEY_PREVIOUS: a = form_driver(curform, FIELD_PREV); break; case KEY_TAB: case KEY_NEXT: case '\n': case KEY_ENTER: /* MUST CHANGE POSTING keys in form selector below if changed */ status_clear(); a = form_driver(curform, FIELD_STORE); order_tally(&order); break; case KEY_DC: /* delete special text on orderform */ if (curform != &orderform) { a = FORM_NONE; break; } order_edit_special(getfield_cur(&orderform), 0); order_refresh(ordertop); a = form_driver(curform, FIELD_NEXT); break; case KEY_IC: /* insert special text on orderform */ if (curform != &orderform) { a = FORM_NONE; break; } order_edit_special(getfield_cur(&orderform), 1); order_refresh(ordertop); a = form_driver(curform, FIELD_NEXT); break; case KEY_NPAGE: /* Page Down order form (if possible) */ lines = order_getlines(&order.items); if (ordertop < lines) { ordertop += MIN((LINE_ORDER_SIZE - 2), (lines - ordertop)); order_refresh(ordertop); a = form_driver(&orderform, FORM_ENTER_UP); } break; case KEY_PPAGE: /* Page Up order form (if possible) */ if (ordertop > 1) { ordertop -= MIN((LINE_ORDER_SIZE - 2), ordertop); if (ordertop == 0) ordertop = 1; order_refresh(ordertop); a = form_driver(&orderform, FORM_ENTER_DOWN); } break; case KEY_F(1): /* help */ status_set("Arrow keys, Tab/Enter, PgUp, PgDn"); break; case KEY_F(2): /* recall */ if (order_getlast(&order.customer.phone, &order) == -1) { status_warn("no last order available"); break; } if (customer_load(&order.customer) == -1) { status_warn("order references invalid customer"); break; } ordertop = 1; order_refresh(ordertop); curform = &orderform; display_refresh(); a = FORM_NONE; break; case KEY_F(3): /* damnit I lost the phone number and need to see the last order */ if (order_getlast(NULL, &order) == -1) { status_warn("no last phone available"); break; } if (customer_load(&order.customer) == -1) { status_warn("order references invalid customer"); break; } ordertop = 1; order_refresh(ordertop); curform = &orderform; display_refresh(); a = FORM_NONE; break; case KEY_F(4): /* chphone */ if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &chphoneform; display_refresh(); a = FORM_ENTER_UP; break; case KEY_F(5): /* daily totals */ if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &dailyinfoform; order_getdaily_total(); display_refresh(); a = FORM_ENTER_UP; break; case KEY_F(8): /* reprint */ /* * run the rules processor, recalling and reprinting did not print * the rules properly */ rule_run(&order, 0); /* * If there was a print failure (daemon missing, etc) allow the * order to be reprinted without the reprint information. But only * once. */ if (printfailed) { if (print_order(&order, 0) == 0) printfailed = 0; } else print_order(&order, 1); a = FORM_NONE; break; case KEY_F(10): /* credit */ if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &creditform; window_update_credit(); display_refresh(); a = FORM_ENTER_UP; break; case KEY_F(11): /* discount */ if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &discountform; display_refresh(); a = FORM_ENTER_UP; break; case KEY_F(12): /* delivery */ if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &deliveryform; display_refresh(); a = FORM_ENTER_UP; break; case KEY_PRINTORDER: if (order_post() == -1) { /* failed, just abort. can be wiped by NEWORDER */ a = FORM_NONE; break; } if (print_order(&order, 0) == -1) { /* print failed, don't clear the order */ printfailed = 1; a = FORM_NONE; break; } window_update_cashin(&order.total); if (!WINDOW_TEST(curform)) curform_butwindow = curform; curform = &cashinform; display_refresh(); a = FORM_ENTER_UP; break; case KEY_F(7): case KEY_NEWORDER: form_wipe_input(&addrform); form_wipe_input(&orderform); form_wipe_input(&specialform); form_wipe_input(&payform); window_wipe(); order_new(); ordertop = 1; printfailed = 0; order_refresh(ordertop); curform = &addrform; display_refresh(); a = FORM_NONE; break; case 0x16: /* ^V^V */ if ((ff = getfield_cur(curform))) status_set("RAW INPUT: \"%s\"", ff->input.s); a = FORM_NONE; break; case 0x13: /* ^V^S */ debugscreen = !debugscreen; break; case KEY_BACKSPACE: case KEY_BSPACE: a = form_input(curform, KEY_BSPACE); break; default: /* input */ if (debugscreen && ch > KEY_CODE_YES) { status_set("EXT KEY (oct): %o", ch); break; } if (isgraph(ch) || isspace(ch)) a = form_input(curform, ch); break; } /* * FORM SELECTOR */ do { if (a == FORM_EXIT_UP) { if (curform == &orderform) { /* orderform is special */ if (ordertop > 1) { --ordertop; order_refresh(ordertop); a = form_driver(&orderform, FORM_ENTER_UP); break; } else curform = &addrform; } else if (curform == &specialform) curform = &orderform; else if (curform == &payform) curform = &specialform; else if (curform == &cashinform) { /* not allowed to exit UP from this form */ a = form_driver(curform, FORM_ENTER_UP); break; } else if (WINDOW_TEST(curform)) curform = curform_butwindow; else break; a = form_driver(curform, FORM_ENTER_DOWN); } else if (a == FORM_EXIT_DOWN) { if (curform == &addrform) curform = &orderform; else if (curform == &orderform) { /* orderform is special */ if ((ordertop + LINE_ORDER_SIZE - 2) <= order_getlines(&order.items)) { ++ordertop; order_refresh(ordertop); a = form_driver(&orderform, FIELD_BEGIN); break; } else curform = &specialform; } else if (curform == &specialform) curform = &payform; else if (curform == &payform) { /* * enta-enta-enta-enta * User is ready to post the form, so change the key and * reprocess as a PRINTORDER command */ if (ch == KEY_TAB || ch == KEY_NEXT || ch == '\n' || ch == KEY_ENTER) { ch = KEY_PRINTORDER; goto reprocess; } else status_set("Press ENTER to post order"); break; } else if (curform == &cashinform) { /* this pops up after order post, to help with cashin/out */ if (ch == KEY_TAB || ch == KEY_NEXT || ch == '\n' || ch == KEY_ENTER) { ch = KEY_NEWORDER; goto reprocess; } else status_set("Press ENTER to leave"); break; } else if (WINDOW_TEST(curform)) curform = curform_butwindow; else break; a = form_driver(curform, FORM_ENTER_UP); } else if (a == FORM_ENTER_UP || a == FORM_ENTER_DOWN) a = form_driver(curform, a); } while ((a == FORM_EXIT_UP && curform != &addrform) || (a == FORM_EXIT_DOWN && curform != &payform)); display_form(curform); }
{ "content_hash": "48b0646d749f0cc8408c08afd4566f92", "timestamp": "", "source": "github", "line_count": 847, "max_line_length": 77, "avg_line_length": 23.082644628099175, "alnum_prop": 0.6113242289396962, "repo_name": "WrathOfChris/chopstix", "id": "d461828fe811dfc18d975da41aa01e6962e831d2", "size": "19551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/usr.bin/chopstix/display.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "595149" }, { "name": "C++", "bytes": "2053" }, { "name": "CSS", "bytes": "11058" }, { "name": "Erlang", "bytes": "235" }, { "name": "PHP", "bytes": "59697" }, { "name": "Shell", "bytes": "7950" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.google.code.play2.provider.play23.run.Reloader (Play! 2.x Provider for Play! 2.3.x 1.0.0-beta7 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.google.code.play2.provider.play23.run.Reloader (Play! 2.x Provider for Play! 2.3.x 1.0.0-beta7 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/google/code/play2/provider/play23/run/class-use/Reloader.html" target="_top">Frames</a></li> <li><a href="Reloader.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.google.code.play2.provider.play23.run.Reloader" class="title">Uses of Class<br>com.google.code.play2.provider.play23.run.Reloader</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.google.code.play2.provider.play23.run">com.google.code.play2.provider.play23.run</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.google.code.play2.provider.play23.run"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a> in <a href="../../../../../../../../com/google/code/play2/provider/play23/run/package-summary.html">com.google.code.play2.provider.play23.run</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../com/google/code/play2/provider/play23/run/package-summary.html">com.google.code.play2.provider.play23.run</a> with parameters of type <a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">ReloaderApplicationClassLoaderProvider.</span><code><span class="memberNameLink"><a href="../../../../../../../../com/google/code/play2/provider/play23/run/ReloaderApplicationClassLoaderProvider.html#setReloader-com.google.code.play2.provider.play23.run.Reloader-">setReloader</a></span>(<a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a>&nbsp;reloader)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../../../../com/google/code/play2/provider/play23/run/package-summary.html">com.google.code.play2.provider.play23.run</a> with parameters of type <a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../com/google/code/play2/provider/play23/run/ReloaderPlayDevServer.html#ReloaderPlayDevServer-play.core.server.ServerWithStop-java.util.jar.JarFile-com.google.code.play2.provider.play23.run.Reloader-">ReloaderPlayDevServer</a></span>(play.core.server.ServerWithStop&nbsp;server, <a href="http://docs.oracle.com/javase/1.6.0/docs/api/java/util/jar/JarFile.html?is-external=true" title="class or interface in java.util.jar">JarFile</a>&nbsp;docsJarFile, <a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Reloader</a>&nbsp;reloader)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/google/code/play2/provider/play23/run/Reloader.html" title="class in com.google.code.play2.provider.play23.run">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/google/code/play2/provider/play23/run/class-use/Reloader.html" target="_top">Frames</a></li> <li><a href="Reloader.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013&#x2013;2017. All rights reserved.</small></p> </body> </html>
{ "content_hash": "2db66c1d8e5e25d86ae8d63026639319", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 530, "avg_line_length": 49.12359550561798, "alnum_prop": 0.6398673376029277, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "f71b3d2d87b92aadf92b907223827c1839979e95", "size": "8744", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-beta7/play2-providers/play2-provider-play23/apidocs/com/google/code/play2/provider/play23/run/class-use/Reloader.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
#include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/IR/Location.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/OpDefinition.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/register.h" #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/shape_inference.h" #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_tensor.h" #include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/serialize_mlir_module_utils.h" #include "tensorflow/compiler/mlir/tensorflow/utils/translate_utils.h" #include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/compiler/mlir/xla/type_to_shape.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/xla/service/hlo_sharding.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/tpu/tpu_defs.h" namespace tensorflow { namespace { // Extracts shape from XlaArgument as TensorShape. If shape is a xla::Shape, // that is converted to a TensorShape. StatusOr<TensorShape> GetTensorShapeFromXlaArgument(const XlaArgument& arg) { if (absl::holds_alternative<xla::Shape>(arg.shape)) { TensorShape arg_shape; TF_RETURN_IF_ERROR( XLAShapeToTensorShape(absl::get<xla::Shape>(arg.shape), &arg_shape)); return arg_shape; } else { return absl::get<TensorShape>(arg.shape); } } // Converts arg_shapes to xla::Shape's and store into xla_input_shapes. Status GetXlaInputShapes( mlir::ModuleOp module, llvm::ArrayRef<TensorOrResourceShape> arg_shapes, bool use_tuple_args, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, std::vector<xla::Shape>* xla_input_shapes) { xla_input_shapes->clear(); mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); TF_RET_CHECK(main_func != nullptr) << "No main function found"; mlir::FunctionType func_type = main_func.getType(); int num_args = func_type.getNumInputs(); xla_input_shapes->reserve(num_args); std::vector<xla::Shape> individual_arg_shapes; individual_arg_shapes.reserve(num_args); for (int i = 0; i < num_args; ++i) { individual_arg_shapes.emplace_back(); xla::Shape& xla_shape = individual_arg_shapes.back(); DataType dtype; TF_RETURN_IF_ERROR(ConvertToDataType(func_type.getInput(i), &dtype)); TF_ASSIGN_OR_RETURN(xla_shape, shape_representation_fn(arg_shapes[i].shape, dtype, /*use_fast_memory=*/false)); // Rewrite layout with sharding, if sharding is set. auto sharding = main_func.getArgAttrOfType<mlir::StringAttr>(i, "mhlo.sharding"); if (!sharding) continue; absl::optional<xla::HloSharding> arg_sharding; xla::OpSharding op_sharding; if (!op_sharding.ParseFromString(sharding.getValue().str())) return errors::InvalidArgument("failed to parse argument sharding ", i, " '", sharding.getValue().str(), "'"); TF_ASSIGN_OR_RETURN(arg_sharding, xla::HloSharding::FromProto(op_sharding)); TF_RETURN_IF_ERROR( RewriteLayoutWithShardedShape(arg_sharding, /*use_fast_memory=*/false, shape_representation_fn, &xla_shape)); } if (use_tuple_args) { xla_input_shapes->push_back( xla::ShapeUtil::MakeTupleShape(individual_arg_shapes)); } else { *xla_input_shapes = individual_arg_shapes; } return Status::OK(); } // Calculates computation output shape and build OutputDescription for each // output based on static shapes in MLIR module. If an output is a resource // write, `resource_updates` is populated insead of `outputs` for that output. Status GetOutputInfo( mlir::ModuleOp module, bool use_resource_updates_for_aliases, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, xla::Shape* xla_output_shape, std::vector<XlaOutputDescription>* outputs, std::vector<XlaResourceUpdate>* resource_updates) { auto shape_representation_fn_no_fast_memory = [shape_representation_fn](const TensorShape& shape, DataType dtype) { return shape_representation_fn(shape, dtype, /*use_fast_memory=*/false); }; mlir::FuncOp main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::FunctionType func_type = main_func.getType(); outputs->clear(); outputs->reserve(func_type.getNumResults()); resource_updates->reserve(func_type.getNumResults()); std::vector<xla::Shape> shapes; shapes.reserve(func_type.getNumResults()); llvm::SmallDenseMap<unsigned, unsigned> output_to_input_alias; for (unsigned i = 0; i < main_func.getNumArguments(); ++i) if (auto aliasing_output = main_func.getArgAttrOfType<mlir::IntegerAttr>( i, "tf.aliasing_output")) output_to_input_alias[aliasing_output.getInt()] = i; for (auto type_and_idx : llvm::enumerate(func_type.getResults())) { TF_ASSIGN_OR_RETURN( xla::Shape shape, xla::TypeToShape(type_and_idx.value(), shape_representation_fn_no_fast_memory)); auto tensor_type = type_and_idx.value().dyn_cast<mlir::RankedTensorType>(); shapes.push_back(shape); auto it = output_to_input_alias.find(type_and_idx.index()); if (it != output_to_input_alias.end() && use_resource_updates_for_aliases) { // Add resource write. resource_updates->emplace_back(); XlaResourceUpdate& resource_update = resource_updates->back(); resource_update.input_index = it->getSecond(); resource_update.modified = true; TF_RETURN_IF_ERROR(ConvertToDataType(tensor_type, &resource_update.type)); TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape, &resource_update.shape)); continue; } // Construct OutputDescription for result. outputs->emplace_back(); XlaOutputDescription& out_desc = outputs->back(); TF_RETURN_IF_ERROR(ConvertToDataType(tensor_type, &out_desc.type)); // TODO(ycao): Support constant output. out_desc.is_constant = false; TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape, &out_desc.shape)); // Input_index is only meaningful for resource output. Setting it to // meaningless value -1 for non resource outputs. out_desc.input_index = it != output_to_input_alias.end() ? it->getSecond() : -1; // MLIR-based TF-Compiler bridge doesn't support tensorlist output yet. // TODO(ycao): Support tensorlist-type output. out_desc.is_tensor_list = false; } // XLA computation always uses Tuple shape. *xla_output_shape = xla::ShapeUtil::MakeTupleShape(shapes); return Status::OK(); } // Creates a vector that maps from the parameters of the XLA computation to // their original argument positions. // MLIR-based TF-Compiler bridge doesn't have constant analysis yet, thus no // inputs are known constants. Therefore, the input mapping between input to // computation arguments is a trivial in-order 1-1 mapping. // TODO(ycao): Support computation with compile-time constant, which requires // non-trivial input mapping as implemented now. void GetInputMappingForMlir(int num_inputs, std::vector<int>* input_mapping) { input_mapping->resize(num_inputs, 0); std::iota(input_mapping->begin(), input_mapping->end(), 0); } static void RegisterDialects(mlir::DialectRegistry& registry) { mlir::RegisterAllTensorFlowDialects(registry); mlir::mhlo::registerAllMhloDialects(registry); } // Checks if functions can be inlined after TF -> HLO legalization. Currently // TPU's are supported, to follow the behavior of inlining functions via the // Graph based bridge in the TPUCompile op kernel. bool CanInlineFunctionsPostLegalization(llvm::StringRef device_type) { return device_type == DEVICE_TPU_XLA_JIT; } } // namespace Status RefineShapes(llvm::ArrayRef<TensorOrResourceShape> arg_shapes, mlir::ModuleOp module) { auto producer_or = GetTfGraphProducerVersion(module); if (!producer_or.ok()) return producer_or.status(); int64_t producer_version = producer_or.ValueOrDie(); llvm::SmallVector<int64_t, 16> shape_backing; llvm::SmallVector<llvm::ArrayRef<int64_t>, 4> arg_shapes_copy; { // Convert arg_shapes to a mlir friendly format. size_t count = 0; for (const TensorOrResourceShape& tensor_resource_shape : arg_shapes) { if (tensor_resource_shape.is_resource) continue; count += tensor_resource_shape.shape.dims(); } shape_backing.resize(count); arg_shapes_copy.reserve(arg_shapes.size()); size_t offset = 0; for (const TensorOrResourceShape& tensor_resource_shape : arg_shapes) { if (tensor_resource_shape.is_resource) { arg_shapes_copy.push_back(llvm::ArrayRef<int64_t>()); continue; } size_t start = offset; for (tensorflow::TensorShapeDim dim : tensor_resource_shape.shape) { shape_backing[offset] = dim.size; ++offset; } if (offset == start) { arg_shapes_copy.push_back(llvm::ArrayRef<int64_t>()); } else { arg_shapes_copy.push_back( llvm::ArrayRef<int64_t>(&shape_backing[start], offset - start)); } } } auto main_func = module.lookupSymbol<mlir::FuncOp>("main"); mlir::StatusScopedDiagnosticHandler error_handler(module.getContext()); mlir::LogicalResult result = mlir::TF::InferShapeForFunction( main_func, arg_shapes_copy, producer_version); if (failed(result)) { return error_handler.Combine( errors::Internal("MLIR Shape refinement failed")); } return Status::OK(); } void CreateConvertMlirToXlaHloPipeline( mlir::OpPassManager& pm, llvm::StringRef device_type, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { pm.addPass(mlir::TF::CreateTFFunctionalControlFlowToRegions()); pm.addNestedPass<mlir::FuncOp>(mlir::TF::CreateDropWhileShapeInvariantPass()); pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); // The SCCP pass performs constant propagation across the IR, which, for // example, propagates constant arguments into callee functions. pm.addPass(mlir::createSCCPPass()); // Guarantee all functions have one use, which enables shape inference. pm.addPass(mlir::TF::CreateGuaranteeAllFuncsOneUsePass()); // Run shape inference pass before tensorlist decomposition to get buffer // shape of uninitialized TensorLists. pm.addPass(mlir::TF::CreateTFShapeInferencePass()); pm.addPass(mlir::TF::CreateTensorListOpsDecompositionPass()); pm.addPass(mlir::TF::CreateStackOpsDecompositionPass()); pm.addPass(mlir::TF::CreateTensorArrayOpsDecompositionPass()); pm.addNestedPass<mlir::FuncOp>( mlir::TFDevice::CreateDecomposeResourceOpsPass()); pm.addPass(mlir::TF::CreatePromoteResourcesToArgsPass()); pm.addPass(mlir::createSymbolDCEPass()); pm.addPass(mlir::TF::CreateTFShapeInferencePass()); // TODO(b/171426148): We cannot completely remove region to functional control // flow conversion from this pipeline yet as it causes some unit tests to // fail. pm.addPass(mlir::TF::CreateTFRegionControlFlowToFunctional()); // LegalizeTFControlFlow encapsulates arguments for control flow operations // with a tuple argument which break the assumption of resource lifting // inside PromoteResourcesToArgs. pm.addPass(mlir::mhlo::createLegalizeTFControlFlowPass()); pm.addNestedPass<mlir::FuncOp>(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/true, /*legalize_chlo=*/true, /*tf2xla_fallback_device_type=*/device_type)); for (auto& target_pass : custom_legalization_passes) { pm.addNestedPass<mlir::FuncOp>(std::move(target_pass)); } pm.addPass(mlir::mhlo::CreateLegalizeTFCommunicationPass()); pm.addNestedPass<mlir::FuncOp>(mlir::createCanonicalizerPass()); // Run shape inference pass to propagate shapes through tensor_cast operations // from static to dynamic shapes. This could be generated if the shape // inference was originally missing in a TF op but the corresponding HLO op // had static shape after lowering. pm.addPass(mlir::TF::CreateTFShapeInferencePass()); // Run LegalizeTFPass again because the previous legalization passes can // expose more graph pruning and canonicalization opportunities that are // necessary for the second LegalizeTFPass(allow_partial_conversion=false) // invocation. pm.addNestedPass<mlir::FuncOp>(mlir::mhlo::createLegalizeTFPass( /*allow_partial_conversion=*/false, /*legalize_chlo=*/true, /*tf2xla_fallback_device_type=*/device_type)); if (CanInlineFunctionsPostLegalization(device_type)) pm.addPass(mlir::createInlinerPass()); // In order to export to XLA, we must sink constants to control flow regions, // since XLA uses functional control flow. pm.addNestedPass<mlir::FuncOp>( mlir::mhlo::createSinkConstantsToControlFlowPass()); } Status LegalizeToHlo(mlir::ModuleOp module_op, llvm::StringRef device_type, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { mlir::PassManager tf2xla(module_op.getContext()); applyTensorflowAndCLOptions(tf2xla); CreateConvertMlirToXlaHloPipeline(tf2xla, device_type, custom_legalization_passes); if (VLOG_IS_ON(1)) { // Print the whole module after each pass which requires disabling // multi-threading as well. module_op.getContext()->disableMultithreading(); tf2xla.enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>( /*print_module_scope=*/true)); } // Make sure we catch any error reported by MLIR and forward it to the TF // error reporting system. Report a generic error if pass manager failed // without emitting a diagnostic. mlir::StatusScopedDiagnosticHandler error_handler(module_op.getContext()); if (failed(tf2xla.run(module_op))) { return error_handler.Combine( errors::Internal("MLIR TF to XLA legalization failed")); } if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_legalize_hlo", module_op); return Status::OK(); } Status BuildHloFromTfInner(mlir::ModuleOp module_op, xla::XlaBuilder& builder, llvm::ArrayRef<xla::XlaOp> xla_params, std::vector<xla::XlaOp>& returns, llvm::StringRef device_type, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { TF_RETURN_IF_ERROR( LegalizeToHlo(module_op, device_type, custom_legalization_passes)); mlir::Block& block = module_op.lookupSymbol<mlir::FuncOp>("main").front(); return mlir::BuildHloFromMlirHlo(block, builder, xla_params, returns); } Status ConvertMLIRToXlaComputation( mlir::ModuleOp module_op, llvm::StringRef device_type, xla::XlaComputation* xla_computation, bool use_tuple_args, bool return_tuple, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { TF_RETURN_IF_ERROR( LegalizeToHlo(module_op, device_type, custom_legalization_passes)); xla::HloProto hlo_proto; TF_RETURN_IF_ERROR(mlir::ConvertMlirHloToHlo(module_op, &hlo_proto, use_tuple_args, return_tuple, shape_representation_fn)); *xla_computation = xla::XlaComputation(hlo_proto.hlo_module()); return Status::OK(); } Status CompileMlirSetup( mlir::ModuleOp module_op, llvm::ArrayRef<TensorOrResourceShape> arg_shapes, XlaHelpers::ShapeRepresentationFn* shape_representation_fn) { if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_before", module_op); // Use arg_shapes to improve the mlir type information of `main` in module_op. TF_RETURN_IF_ERROR(RefineShapes(arg_shapes, module_op)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_shape_refiner", module_op); if (!*shape_representation_fn) *shape_representation_fn = IdentityShapeRepresentationFn(); return Status::OK(); } Status BuildHloFromTf(mlir::ModuleOp module_op, xla::XlaBuilder& builder, llvm::ArrayRef<xla::XlaOp> xla_params, std::vector<xla::XlaOp>& returns, llvm::ArrayRef<TensorOrResourceShape> arg_shapes, llvm::StringRef device_type, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { XlaHelpers::ShapeRepresentationFn shape_representation_fn; TF_RETURN_IF_ERROR( CompileMlirSetup(module_op, arg_shapes, &shape_representation_fn)); // Convert MLIR module to XLA HLO proto contained in XlaComputation. TF_RETURN_IF_ERROR(BuildHloFromTfInner(module_op, builder, xla_params, returns, device_type, custom_legalization_passes)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_after", module_op); return Status::OK(); } Status PopulateResultIOInfo( mlir::ModuleOp module_op, llvm::ArrayRef<TensorOrResourceShape> arg_shapes, bool use_tuple_args, bool use_resource_updates_for_aliases, XlaHelpers::ShapeRepresentationFn shape_representation_fn, XlaCompilationResult* compilation_result) { // Construct mapping from XlaComputation's arg to input edges of execute // node. GetInputMappingForMlir(arg_shapes.size(), &compilation_result->input_mapping); // Compute all input shapes. TF_RETURN_IF_ERROR(GetXlaInputShapes(module_op, arg_shapes, use_tuple_args, shape_representation_fn, &compilation_result->xla_input_shapes)); // Compute all output descriptions and resource writes TF_RETURN_IF_ERROR(GetOutputInfo( module_op, use_resource_updates_for_aliases, shape_representation_fn, &compilation_result->xla_output_shape, &compilation_result->outputs, &compilation_result->resource_updates)); if (VLOG_IS_ON(1)) tensorflow::DumpMlirOpToFile("mlir_compile_after", module_op); return Status::OK(); } Status CompileMlirToXlaHlo( mlir::ModuleOp module_op, llvm::ArrayRef<TensorOrResourceShape> arg_shapes, llvm::StringRef device_type, bool use_tuple_args, bool use_return_tuple, bool use_resource_updates_for_aliases, XlaHelpers::ShapeRepresentationFn shape_representation_fn, XlaCompilationResult* compilation_result, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { TF_RETURN_IF_ERROR( CompileMlirSetup(module_op, arg_shapes, &shape_representation_fn)); // Convert MLIR module to XLA HLO proto contained in XlaComputation. compilation_result->computation = std::make_shared<xla::XlaComputation>(); TF_RETURN_IF_ERROR(ConvertMLIRToXlaComputation( module_op, device_type, compilation_result->computation.get(), use_tuple_args, use_return_tuple, shape_representation_fn, custom_legalization_passes)); return PopulateResultIOInfo(module_op, arg_shapes, use_tuple_args, use_resource_updates_for_aliases, shape_representation_fn, compilation_result); } Status CompileSerializedMlirToXlaHlo( llvm::StringRef mlir_module_string, llvm::ArrayRef<TensorShape> arg_shapes, llvm::StringRef device_type, bool use_tuple_args, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, XlaCompilationResult* compilation_result, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { mlir::MLIRContext mlir_context; RegisterDialects(mlir_context.getDialectRegistry()); mlir::OwningModuleRef mlir_module; TF_RETURN_IF_ERROR( DeserializeMlirModule(mlir_module_string, &mlir_context, &mlir_module)); llvm::SmallVector<TensorOrResourceShape, 4> tensor_or_resource_shapes; tensor_or_resource_shapes.reserve(arg_shapes.size()); for (const auto& arg_shape : arg_shapes) tensor_or_resource_shapes.push_back({arg_shape}); return CompileMlirToXlaHlo( mlir_module.get(), tensor_or_resource_shapes, device_type, use_tuple_args, /*use_return_tuple=*/true, /*use_resource_updates_for_aliases=*/false, shape_representation_fn, compilation_result, custom_legalization_passes); } // Rewrites the given module with specified args. For each of the constant args, // it gets inlined in the "main' function and the corresponding argument is // removed from the signature. For resource args, their subtypes are populated. // Returns the original indices for the other arguments on success. static StatusOr<std::vector<int>> RewriteWithArgs( mlir::ModuleOp module_op, llvm::ArrayRef<XlaArgument> args) { mlir::FuncOp main_fn = module_op.lookupSymbol<mlir::FuncOp>("main"); std::vector<int> params; bool has_resource_args = false; auto builder = mlir::OpBuilder(main_fn.getBody()); std::vector<int> args_to_erase; for (int idx = 0; idx < args.size(); idx++) { const XlaArgument& xla_arg = args[idx]; mlir::BlockArgument mlir_arg = main_fn.getArgument(idx); if (xla_arg.kind == XlaArgument::kResource) { mlir::Type element_type; TF_RETURN_IF_ERROR(ConvertDataType(xla_arg.type, builder, &element_type)); TF_ASSIGN_OR_RETURN(TensorShape arg_shape, GetTensorShapeFromXlaArgument(xla_arg)); auto resource_shape = arg_shape.dim_sizes(); llvm::SmallVector<int64_t, 4> resource_subtype_shape( resource_shape.begin(), resource_shape.end()); auto resource_subtype = mlir::RankedTensorType::get(resource_subtype_shape, element_type); auto resource_type = mlir::TF::ResourceType::get({resource_subtype}, builder.getContext()); auto tensor_type = mlir_arg.getType().cast<mlir::TensorType>(); if (tensor_type.hasRank()) { mlir_arg.setType( mlir::RankedTensorType::get(tensor_type.getShape(), resource_type)); } else { mlir_arg.setType(mlir::UnrankedTensorType::get(resource_type)); } has_resource_args = true; } if (xla_arg.kind != XlaArgument::kConstant) { params.push_back(idx); continue; } TF_ASSIGN_OR_RETURN(auto value_attr, ConvertTensor(xla_arg.constant_value, &builder)); // TODO(hinsu): Use the actual location of the constant. auto constant = builder.create<mlir::TF::ConstOp>( mlir::UnknownLoc::get(module_op.getContext()), value_attr); mlir_arg.replaceAllUsesWith(constant); args_to_erase.push_back(idx); } if (has_resource_args) { llvm::SmallVector<mlir::Type, 4> updated_argument_types; updated_argument_types.reserve(main_fn.getNumArguments()); for (mlir::BlockArgument& arg : main_fn.getArguments()) updated_argument_types.push_back(arg.getType()); main_fn.setType(mlir::FunctionType::get(updated_argument_types, main_fn.getType().getResults(), main_fn.getContext())); } for (int idx : llvm::reverse(args_to_erase)) main_fn.eraseArgument(idx); return params; } Status CompileGraphSetup( mlir::ModuleOp module_op, llvm::ArrayRef<XlaArgument> args, std::vector<int>* remaining_params, llvm::SmallVector<TensorOrResourceShape, 4>& arg_shapes) { TF_ASSIGN_OR_RETURN(*remaining_params, RewriteWithArgs(module_op, args)); arg_shapes.reserve(remaining_params->size()); for (unsigned idx : *remaining_params) { const auto& arg = args[idx]; TF_ASSIGN_OR_RETURN(TensorShape arg_shape, GetTensorShapeFromXlaArgument(arg)); arg_shapes.push_back({arg_shape, /*is_resource=*/arg.kind == XlaArgument::kResource}); } mlir::PassManager pm(module_op.getContext()); applyTensorflowAndCLOptions(pm); mlir::TF::StandardPipelineOptions tf_options; mlir::TF::CreateTFStandardPipeline(pm, tf_options); mlir::StatusScopedDiagnosticHandler diag_handler(module_op.getContext()); if (failed(pm.run(module_op))) return diag_handler.ConsumeStatus(); return Status::OK(); } Status BuildHloFromModule(mlir::ModuleOp module_op, xla::XlaBuilder& builder, llvm::ArrayRef<xla::XlaOp> xla_params, std::vector<xla::XlaOp>& returns, llvm::ArrayRef<XlaArgument> args, llvm::StringRef device_type, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { std::vector<int> remaining_params; llvm::SmallVector<TensorOrResourceShape, 4> arg_shapes; TF_RETURN_IF_ERROR( CompileGraphSetup(module_op, args, &remaining_params, arg_shapes)); return BuildHloFromTf(module_op, builder, xla_params, returns, arg_shapes, device_type, custom_legalization_passes); } Status CompileGraphToXlaHlo( mlir::ModuleOp module_op, llvm::ArrayRef<XlaArgument> args, llvm::StringRef device_type, bool use_tuple_args, bool use_return_tuple, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, XlaCompilationResult* compilation_result, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { std::vector<int> remaining_params; llvm::SmallVector<TensorOrResourceShape, 4> arg_shapes; TF_RETURN_IF_ERROR( CompileGraphSetup(module_op, args, &remaining_params, arg_shapes)); auto status = CompileMlirToXlaHlo( module_op, arg_shapes, device_type, use_tuple_args, use_return_tuple, /*use_resource_updates_for_aliases=*/true, shape_representation_fn, compilation_result, custom_legalization_passes); compilation_result->input_mapping = remaining_params; return status; } Status GraphToModule(const Graph& graph, llvm::ArrayRef<std::string> control_rets, const FunctionLibraryDefinition& flib_def, const GraphDebugInfo& debug_info, mlir::MLIRContext* context, mlir::OwningModuleRef* module) { RegisterDialects(context->getDialectRegistry()); GraphImportConfig config; config.graph_as_function = true; config.control_outputs = control_rets; // Disable shape inference during import as some TensorFlow op fails during // shape inference with dynamic shaped operands. This in turn causes the // import to fail. Shape inference during import is going to be removed and // the shape inference pass is run early in the pass pipeline, shape inference // during import is not necessary. config.enable_shape_inference = false; auto module_or = ConvertGraphToMlir(graph, debug_info, flib_def, config, context); if (!module_or.ok()) return module_or.status(); *module = std::move(module_or.ValueOrDie()); return Status::OK(); } Status BuildHloFromGraph(const Graph& graph, xla::XlaBuilder& builder, llvm::ArrayRef<xla::XlaOp> xla_params, std::vector<xla::XlaOp>& returns, llvm::ArrayRef<XlaArgument> args, llvm::ArrayRef<std::string> control_rets, llvm::StringRef device_type, const FunctionLibraryDefinition& flib_def, const GraphDebugInfo& debug_info, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { mlir::MLIRContext context; mlir::OwningModuleRef module; TF_RETURN_IF_ERROR(GraphToModule(graph, control_rets, flib_def, debug_info, &context, &module)); return BuildHloFromModule(module.get(), builder, xla_params, returns, args, device_type, custom_legalization_passes); } Status CompileGraphToXlaHlo( const Graph& graph, llvm::ArrayRef<XlaArgument> args, llvm::ArrayRef<std::string> control_rets, llvm::StringRef device_type, bool use_tuple_args, const FunctionLibraryDefinition& flib_def, const GraphDebugInfo& debug_info, const XlaHelpers::ShapeRepresentationFn shape_representation_fn, XlaCompilationResult* compilation_result, llvm::MutableArrayRef<std::unique_ptr<mlir::Pass>> custom_legalization_passes) { mlir::MLIRContext context; mlir::OwningModuleRef module; TF_RETURN_IF_ERROR(GraphToModule(graph, control_rets, flib_def, debug_info, &context, &module)); return CompileGraphToXlaHlo(module.get(), args, device_type, use_tuple_args, /*use_return_tuple=*/true, shape_representation_fn, compilation_result, custom_legalization_passes); } } // namespace tensorflow
{ "content_hash": "1484505c43a7a56501be1e6781dac9f7", "timestamp": "", "source": "github", "line_count": 691, "max_line_length": 89, "avg_line_length": 44.74674384949349, "alnum_prop": 0.6917852522639069, "repo_name": "cxxgtxy/tensorflow", "id": "61388d3f7f971c73bb624ddfba2613d8a03f659f", "size": "31588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7481" }, { "name": "C", "bytes": "186817" }, { "name": "C++", "bytes": "24882047" }, { "name": "CMake", "bytes": "164374" }, { "name": "Go", "bytes": "854846" }, { "name": "HTML", "bytes": "564161" }, { "name": "Java", "bytes": "307246" }, { "name": "Jupyter Notebook", "bytes": "1833659" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "37393" }, { "name": "Objective-C", "bytes": "7037" }, { "name": "Objective-C++", "bytes": "64142" }, { "name": "Protocol Buffer", "bytes": "225621" }, { "name": "Python", "bytes": "22009999" }, { "name": "Shell", "bytes": "341543" }, { "name": "TypeScript", "bytes": "797437" } ], "symlink_target": "" }
<?xml version="1.0" ?> <INPUT> <MEDALS> <MEDAL Id="1" MEDAL_THRESHOLD="52000" TYPE="Gold"/> <MEDAL Id="2" MEDAL_THRESHOLD="79000" TYPE="Silver"/> <MEDAL Id="3" MEDAL_THRESHOLD="102000" TYPE="Bronze"/> </MEDALS> <SpeedSettings Default="18" Max="150" Min="0"/> <PenaltySettings SpeedLost="0.1" TimeLost="15"/> <PROBLEM_SET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="10" numerator="7"/> </TARGET> <QUESTION INDEX="1"> <Content TYPE="String"> <ContentSettings string="0.4"/> </Content> <Content TYPE="String"> <ContentSettings string="0.9"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="2"> <Content TYPE="String"> <ContentSettings string="0.1"/> </Content> <Content TYPE="String"> <ContentSettings string="1.1"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="3"> <Content TYPE="String"> <ContentSettings string="0.1"/> </Content> <Content TYPE="String"> <ContentSettings string="0.3"/> </Content> <Answer VALUE="2"/> </QUESTION> </PROBLEM_SUBSET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="12" numerator="18"/> </TARGET> <QUESTION INDEX="4"> <Content TYPE="String"> <ContentSettings string="0.333"/> </Content> <Content TYPE="String"> <ContentSettings string="0.75"/> </Content> <Answer VALUE="2"/> </QUESTION> <QUESTION INDEX="5"> <Content TYPE="String"> <ContentSettings string="1.666"/> </Content> <Content TYPE="String"> <ContentSettings string="1.75"/> </Content> <Answer VALUE="0"/> </QUESTION> <QUESTION INDEX="6"> <Content TYPE="String"> <ContentSettings string="0.416"/> </Content> <Content TYPE="String"> <ContentSettings string="1.333"/> </Content> <Answer VALUE="2"/> </QUESTION> </PROBLEM_SUBSET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="5" numerator="2" whole="1"/> </TARGET> <QUESTION INDEX="7"> <Content TYPE="String"> <ContentSettings string="0.4"/> </Content> <Content TYPE="String"> <ContentSettings string="0.6"/> </Content> <Answer VALUE="2"/> </QUESTION> <QUESTION INDEX="8"> <Content TYPE="String"> <ContentSettings string="2"/> </Content> <Content TYPE="String"> <ContentSettings string="2.2"/> </Content> <Answer VALUE="0"/> </QUESTION> <QUESTION INDEX="9"> <Content TYPE="String"> <ContentSettings string="0.4"/> </Content> <Content TYPE="String"> <ContentSettings string="1.6"/> </Content> <Answer VALUE="1"/> </QUESTION> </PROBLEM_SUBSET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="2" numerator="1" whole="1"/> </TARGET> <QUESTION INDEX="10"> <Content TYPE="String"> <ContentSettings string="0"/> </Content> <Content TYPE="String"> <ContentSettings string="1"/> </Content> <Answer VALUE="2"/> </QUESTION> <QUESTION INDEX="11"> <Content TYPE="String"> <ContentSettings string="0.5"/> </Content> <Content TYPE="String"> <ContentSettings string="2"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="12"> <Content TYPE="String"> <ContentSettings string="2"/> </Content> <Content TYPE="String"> <ContentSettings string="2.5"/> </Content> <Answer VALUE="0"/> </QUESTION> </PROBLEM_SUBSET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="1000" numerator="91" whole="1"/> </TARGET> <QUESTION INDEX="13"> <Content TYPE="String"> <ContentSettings string="1.749"/> </Content> <Content TYPE="String"> <ContentSettings string="1.851"/> </Content> <Answer VALUE="0"/> </QUESTION> <QUESTION INDEX="14"> <Content TYPE="String"> <ContentSettings string="0.571"/> </Content> <Content TYPE="String"> <ContentSettings string="1.388"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="15"> <Content TYPE="String"> <ContentSettings string="1.737"/> </Content> <Content TYPE="String"> <ContentSettings string="1.928"/> </Content> <Answer VALUE="0"/> </QUESTION> </PROBLEM_SUBSET> <PROBLEM_SUBSET> <TARGET TYPE="Fraction"> <ContentSettings denominator="5" numerator="1" whole="1"/> </TARGET> <QUESTION INDEX="16"> <Content TYPE="String"> <ContentSettings string="0.2"/> </Content> <Content TYPE="String"> <ContentSettings string="1.6"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="17"> <Content TYPE="String"> <ContentSettings string="0.6"/> </Content> <Content TYPE="String"> <ContentSettings string="2.2"/> </Content> <Answer VALUE="1"/> </QUESTION> <QUESTION INDEX="18"> <Content TYPE="String"> <ContentSettings string="0"/> </Content> <Content TYPE="String"> <ContentSettings string="0.6"/> </Content> <Answer VALUE="2"/> </QUESTION> </PROBLEM_SUBSET> </PROBLEM_SET> </INPUT>
{ "content_hash": "01432781c66e42858bf43e978207639a", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 66, "avg_line_length": 25.735849056603772, "alnum_prop": 0.5707478005865103, "repo_name": "synaptek/MathFluency", "id": "cc85d18a87e014b9329e68299b1a745d09f71c66", "size": "5456", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/ft1_racecar_html5/carlow_level03stage4/l03_s4_set027.xml", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1908" }, { "name": "HTML", "bytes": "580527" }, { "name": "JavaScript", "bytes": "24985612" }, { "name": "Python", "bytes": "77534" }, { "name": "Shell", "bytes": "162" } ], "symlink_target": "" }
package cn.easyproject.easyee.sm.sys.interceptor; import java.util.Arrays; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import cn.easyproject.easyee.sm.sys.entity.SysLog; import cn.easyproject.easyee.sm.sys.entity.SysUser; import cn.easyproject.easyee.sm.sys.service.SysLogService; /** * 系统操作,日志记录拦截器 * * @author easyproject.cn * @version 1.0 * */ public class LogInterceptor implements HandlerInterceptor { SysLogService sysLogService; @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if(request.getRequestURI().contains("captcha")){ return; } /* * 日志信息 */ String ip = request.getRemoteAddr(); StringBuilder parameters = new StringBuilder(); ; if (request.getParameterMap() != null) { Map<String, String[]> map = request.getParameterMap(); for (Entry<String, String[]> entry : map.entrySet()) { if (entry.getKey().contains("password") || entry.getKey().contains("pwd")) { parameters.append(entry.getKey() + ": can'tshow; "); continue; } parameters.append(entry.getKey() + ": " + Arrays.toString(entry.getValue()) + "; "); } if (parameters.toString().endsWith("; ")) { parameters.substring(0, parameters.length() - 2); } } // 利用反射, 防止出现 ClassCastException Object sysUser= request.getSession().getAttribute("USER"); // SysUser sysUser = (SysUser) request.getSession().getAttribute("USER"); String account = "未登录"; if (sysUser != null) { if(sysUser instanceof SysUser){ String name=((SysUser) sysUser).getName(); String realName=((SysUser) sysUser).getRealName(); account = name + "[" + realName + "]"; }else{ String name=sysUser.getClass().getMethod("getName").invoke(sysUser).toString(); String realName=sysUser.getClass().getMethod("getRealName").invoke(sysUser).toString(); account = name + "[" + realName + "]"; } } /* * 添加日志 */ String invokeBeanName = ""; if(handler instanceof HandlerMethod){ HandlerMethod hm = ((HandlerMethod) handler); invokeBeanName = hm.getBean().getClass().getName() + "#" + hm.getMethod().getName(); }else{ invokeBeanName = handler.getClass().getName(); } String res = ""; if (ex != null) { res = ex.getMessage() + " [" + ex.getClass().getName() + "]"; } SysLog sysLog = new SysLog(request.getRequestURI() + " [" + invokeBeanName + "]", parameters.toString(), res, account, ip, new Date()); sysLogService.add(sysLog); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { return true; } public void setSysLogService(SysLogService sysLogService) { this.sysLogService = sysLogService; } }
{ "content_hash": "1bf6d9146bb504c5a9bd3351e49b97a3", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 116, "avg_line_length": 28.575221238938052, "alnum_prop": 0.6958810777330443, "repo_name": "ushelp/EasyEE", "id": "55fd99304fda716b51aca13eee8f71f040d045a9", "size": "3293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project/easyee-sm-springboot/src/main/java/cn/easyproject/easyee/sm/sys/interceptor/LogInterceptor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "51834855" } ], "symlink_target": "" }
package com.linkedin.pinot.core.operator.transform.transformer.timeunit; import java.util.Random; import java.util.concurrent.TimeUnit; import org.joda.time.DurationFieldType; import org.joda.time.chrono.ISOChronology; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TimeUnitTransformerTest { private static final int NUM_ROWS = 100; private static final Random RANDOM = new Random(); private final long[] _input = new long[NUM_ROWS]; private final long[] _output = new long[NUM_ROWS]; @BeforeClass public void setUp() { long currentTimeMs = System.currentTimeMillis(); for (int i = 0; i < NUM_ROWS; i++) { _input[i] = Math.abs(RANDOM.nextLong()) % currentTimeMs; } } @Test public void testJavaTimeUnit() { TimeUnitTransformer timeUnitTransformer = TimeUnitTransformerFactory.getTimeUnitTransformer(TimeUnit.MILLISECONDS, "dAyS"); Assert.assertTrue(timeUnitTransformer instanceof JavaTimeUnitTransformer); timeUnitTransformer.transform(_input, _output, NUM_ROWS); for (int i = 0; i < NUM_ROWS; i++) { long expected = TimeUnit.MILLISECONDS.toDays(_input[i]); Assert.assertEquals(_output[i], expected); } } @Test public void testCustomTimeUnit() { TimeUnitTransformer timeUnitTransformer = TimeUnitTransformerFactory.getTimeUnitTransformer(TimeUnit.MILLISECONDS, "wEeKs"); Assert.assertTrue(timeUnitTransformer instanceof CustomTimeUnitTransformer); timeUnitTransformer.transform(_input, _output, NUM_ROWS); for (int i = 0; i < NUM_ROWS; i++) { int expected = DurationFieldType.weeks().getField(ISOChronology.getInstanceUTC()).getDifference(_input[i], 0L); Assert.assertEquals(_output[i], expected); } timeUnitTransformer = TimeUnitTransformerFactory.getTimeUnitTransformer(TimeUnit.MILLISECONDS, "mOnThS"); Assert.assertTrue(timeUnitTransformer instanceof CustomTimeUnitTransformer); timeUnitTransformer.transform(_input, _output, NUM_ROWS); for (int i = 0; i < NUM_ROWS; i++) { int expected = DurationFieldType.months().getField(ISOChronology.getInstanceUTC()).getDifference(_input[i], 0L); Assert.assertEquals(_output[i], expected); } timeUnitTransformer = TimeUnitTransformerFactory.getTimeUnitTransformer(TimeUnit.MILLISECONDS, "yEaRs"); Assert.assertTrue(timeUnitTransformer instanceof CustomTimeUnitTransformer); timeUnitTransformer.transform(_input, _output, NUM_ROWS); for (int i = 0; i < NUM_ROWS; i++) { int expected = DurationFieldType.years().getField(ISOChronology.getInstanceUTC()).getDifference(_input[i], 0L); Assert.assertEquals(_output[i], expected); } } }
{ "content_hash": "8d5e1ab381e21cc73bc3a75b858e1a6a", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 118, "avg_line_length": 40.92537313432836, "alnum_prop": 0.7341356673960613, "repo_name": "apucher/pinot", "id": "98227fa89fb1b04e673b25218b951c92f0265470", "size": "3379", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pinot-core/src/test/java/com/linkedin/pinot/core/operator/transform/transformer/timeunit/TimeUnitTransformerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "4620" }, { "name": "Batchfile", "bytes": "7738" }, { "name": "CSS", "bytes": "925082" }, { "name": "FreeMarker", "bytes": "243834" }, { "name": "HTML", "bytes": "274305" }, { "name": "Java", "bytes": "14420303" }, { "name": "JavaScript", "bytes": "5189610" }, { "name": "Makefile", "bytes": "8076" }, { "name": "Python", "bytes": "36574" }, { "name": "Shell", "bytes": "51677" }, { "name": "Thrift", "bytes": "5028" } ], "symlink_target": "" }
var apiFunctions =require('./apiFunctions') module.exports=Connection function Connection(webSocketServer,webSocketConnection){ this.webSocketServer=webSocketServer this.webSocketConnection=webSocketConnection this.webSocketConnection.on('message',message=>{ this.handleMessage(message) }) // bwc this.rawWebSocketConnection=webSocketConnection } Connection.prototype.handleMessage=function(message){ if(message.type!='utf8') return JSON.parse(message.utf8Data).forEach(request=>{ this.handleGmsRequest(request) }) } Connection.prototype.handleGmsRequest=function(request){ apiFunctions[request.function]({ connection:this, gameServer:this.webSocketServer.httpServer.gameServer, request, },(err,res)=>{ if(res){ res.time=request.time this.rawWebSocketConnection.sendUTF( JSON.stringify(res) ) } }) } Connection.prototype.sendPositionAutomatically=function(){ var connection=this setTimeout(send,50) function send(){ setTimeout(send,50) connection.webSocketConnection.sendUTF(JSON.stringify({ information:'position', x:connection.webSocketServer.httpServer.gameServer. gmsObjectById['564a0ddab81919fb35ca8c40']. children[2].x, y:connection.webSocketServer.httpServer.gameServer. gmsObjectById['564a0ddab81919fb35ca8c40']. children[2].y, })) } }
{ "content_hash": "265f8cea8c237394c9d403c7f7acac47", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 63, "avg_line_length": 31.816326530612244, "alnum_prop": 0.6561898652982682, "repo_name": "anliting/gms", "id": "489c44f615f819ac2914ebcd52b50509eb916775", "size": "1559", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Connection.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "289" }, { "name": "JavaScript", "bytes": "50578" }, { "name": "Shell", "bytes": "389" } ], "symlink_target": "" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/variations/net/variations_http_headers.h" #include <string> #include "base/containers/flat_map.h" #include "base/cxx17_backports.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "components/variations/variations.mojom.h" #include "net/base/isolation_info.h" #include "net/cookies/site_for_cookies.h" #include "services/network/public/cpp/resource_request.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace variations { namespace { // Returns a ResourceRequest created from the given values. network::ResourceRequest CreateResourceRequest( const std::string& request_initiator_url, bool is_main_frame, bool has_trusted_params, const std::string& isolation_info_top_frame_origin_url, const std::string& isolation_info_frame_origin_url) { network::ResourceRequest request; if (request_initiator_url.empty()) return request; request.request_initiator = url::Origin::Create(GURL(request_initiator_url)); request.is_main_frame = is_main_frame; if (!has_trusted_params) return request; request.trusted_params = network::ResourceRequest::TrustedParams(); if (isolation_info_top_frame_origin_url.empty()) return request; request.trusted_params->isolation_info = net::IsolationInfo::Create( net::IsolationInfo::RequestType::kOther, url::Origin::Create(GURL(isolation_info_top_frame_origin_url)), url::Origin::Create(GURL(isolation_info_frame_origin_url)), net::SiteForCookies()); return request; } // Wraps AppendVariationsHeaderWithCustomValue(). void AppendVariationsHeader(const GURL& destination, Owner owner, network::ResourceRequest* request) { base::flat_map<variations::mojom::GoogleWebVisibility, std::string> headers = {{variations::mojom::GoogleWebVisibility::FIRST_PARTY, "abc123"}, {variations::mojom::GoogleWebVisibility::ANY, "xyz456"}}; AppendVariationsHeaderWithCustomValue( destination, InIncognito::kNo, variations::mojom::VariationsHeaders::New(headers), owner, request); } } // namespace TEST(VariationsHttpHeadersTest, ShouldAppendVariationsHeader) { struct { const char* url; bool should_append_headers; } cases[] = { {"http://google.com", false}, {"https://google.com", true}, {"http://www.google.com", false}, {"https://www.google.com", true}, {"http://m.google.com", false}, {"https://m.google.com", true}, {"http://google.ca", false}, {"https://google.ca", true}, {"http://google.co.uk", false}, {"https://google.co.uk", true}, {"http://google.co.uk:8080/", false}, {"https://google.co.uk:8080/", true}, {"http://www.google.co.uk:8080/", false}, {"https://www.google.co.uk:8080/", true}, {"https://google", false}, {"http://youtube.com", false}, {"https://youtube.com", true}, {"http://www.youtube.com", false}, {"https://www.youtube.com", true}, {"http://www.youtube.ca", false}, {"https://www.youtube.ca", true}, {"http://www.youtube.co.uk:8080/", false}, {"https://www.youtube.co.uk:8080/", true}, {"https://youtube", false}, {"https://www.yahoo.com", false}, {"http://ad.doubleclick.net", false}, {"https://ad.doubleclick.net", true}, {"https://a.b.c.doubleclick.net", true}, {"https://a.b.c.doubleclick.net:8081", true}, {"http://www.doubleclick.com", false}, {"https://www.doubleclick.com", true}, {"https://www.doubleclick.org", false}, {"http://www.doubleclick.net.com", false}, {"https://www.doubleclick.net.com", false}, {"http://ad.googlesyndication.com", false}, {"https://ad.googlesyndication.com", true}, {"https://a.b.c.googlesyndication.com", true}, {"https://a.b.c.googlesyndication.com:8080", true}, {"http://www.doubleclick.edu", false}, {"http://www.googlesyndication.com.edu", false}, {"https://www.googlesyndication.com.com", false}, {"http://www.googleadservices.com", false}, {"https://www.googleadservices.com", true}, {"http://www.googleadservices.com:8080", false}, {"https://www.googleadservices.com:8080", true}, {"https://www.internal.googleadservices.com", true}, {"https://www2.googleadservices.com", true}, {"https://www.googleadservices.org", false}, {"https://www.googleadservices.com.co.uk", false}, {"http://WWW.ANDROID.COM", false}, {"https://WWW.ANDROID.COM", true}, {"http://www.android.com", false}, {"https://www.android.com", true}, {"http://www.doubleclick.com", false}, {"https://www.doubleclick.com", true}, {"http://www.doubleclick.net", false}, {"https://www.doubleclick.net", true}, {"http://www.ggpht.com", false}, {"https://www.ggpht.com", true}, {"http://www.googleadservices.com", false}, {"https://www.googleadservices.com", true}, {"http://www.googleapis.com", false}, {"https://www.googleapis.com", true}, {"http://www.googlesyndication.com", false}, {"https://www.googlesyndication.com", true}, {"http://www.googleusercontent.com", false}, {"https://www.googleusercontent.com", true}, {"http://www.googlevideo.com", false}, {"https://www.googlevideo.com", true}, {"http://ssl.gstatic.com", false}, {"https://ssl.gstatic.com", true}, {"http://www.gstatic.com", false}, {"https://www.gstatic.com", true}, {"http://www.ytimg.com", false}, {"https://www.ytimg.com", true}, {"https://wwwytimg.com", false}, {"https://ytimg.com", false}, {"https://www.android.org", false}, {"https://www.doubleclick.org", false}, {"http://www.doubleclick.net", false}, {"https://www.doubleclick.net", true}, {"https://www.ggpht.org", false}, {"https://www.googleadservices.org", false}, {"https://www.googleapis.org", false}, {"https://www.googlesyndication.org", false}, {"https://www.googleusercontent.org", false}, {"https://www.googlevideo.org", false}, {"https://ssl.gstatic.org", false}, {"https://www.gstatic.org", false}, {"https://www.ytimg.org", false}, {"http://a.b.android.com", false}, {"https://a.b.android.com", true}, {"http://a.b.doubleclick.com", false}, {"https://a.b.doubleclick.com", true}, {"http://a.b.doubleclick.net", false}, {"https://a.b.doubleclick.net", true}, {"http://a.b.ggpht.com", false}, {"https://a.b.ggpht.com", true}, {"http://a.b.googleadservices.com", false}, {"https://a.b.googleadservices.com", true}, {"http://a.b.googleapis.com", false}, {"https://a.b.googleapis.com", true}, {"http://a.b.googlesyndication.com", false}, {"https://a.b.googlesyndication.com", true}, {"http://a.b.googleusercontent.com", false}, {"https://a.b.googleusercontent.com", true}, {"http://a.b.googlevideo.com", false}, {"https://a.b.googlevideo.com", true}, {"http://ssl.gstatic.com", false}, {"https://ssl.gstatic.com", true}, {"http://a.b.gstatic.com", false}, {"https://a.b.gstatic.com", true}, {"http://a.b.ytimg.com", false}, {"https://a.b.ytimg.com", true}, {"http://googleweblight.com", false}, {"https://googleweblight.com", true}, {"http://wwwgoogleweblight.com", false}, {"https://www.googleweblight.com", false}, {"https://a.b.googleweblight.com", false}, {"http://a.b.litepages.googlezip.net", false}, {"https://litepages.googlezip.net", false}, {"https://a.litepages.googlezip.net", true}, {"https://a.b.litepages.googlezip.net", true}, }; for (size_t i = 0; i < base::size(cases); ++i) { const GURL url(cases[i].url); EXPECT_EQ(cases[i].should_append_headers, ShouldAppendVariationsHeaderForTesting(url, "Append")) << url; } } struct PopulateRequestContextHistogramData { const char* request_initiator_url; bool is_main_frame; bool has_trusted_params; const char* isolation_info_top_frame_origin_url; const char* isolation_info_frame_origin_url; bool is_top_level_google_owned; int bucket; const char* name; }; class PopulateRequestContextHistogramTest : public testing::TestWithParam<PopulateRequestContextHistogramData> { public: static const PopulateRequestContextHistogramData kCases[]; // Required to use ObserverListThreadSafe::AddObserver() from: // base::FieldTrialList::AddObserver // variations::VariationsIdsProvider::InitVariationIDsCacheIfNeeded // variations::VariationsIdsProvider::GetClientDataHeader // variations::VariationsHeaderHelper::VariationsHeaderHelper // variations::AppendVariationsHeaderUnknownSignedIn base::test::SingleThreadTaskEnvironment task_environment_; }; const PopulateRequestContextHistogramData PopulateRequestContextHistogramTest::kCases[] = { {"", false, false, "", "", false, 0, "kBrowserInitiated"}, {"chrome://newtab/", false, false, "", "", false, 1, "kInternalChromePageInitiated"}, {"chrome-search://most-visited/title.html", false, false, "", "", false, 1, "kInternalChromePageInitiated"}, {"https://www.youtube.com/", true, false, "", "", false, 2, "kGooglePageInitiated"}, {"https://docs.google.com/", false, true, "https://drive.google.com/", "https://docs.google.com/", false, 3, "kGoogleSubFrameOnGooglePageInitiated with TrustedParams"}, {"https://docs.google.com/", false, false, "", "", true, 3, "kGoogleSubFrameOnGooglePageInitiated without TrustedParams"}, {"https://www.un.org/", false, false, "", "", false, 4, "kNonGooglePageInitiated"}, // Bucket 5, kNoTrustedParams, is deprecated. {"https://foo.google.com/", false, true, "", "", false, 6, "kNoIsolationInfo"}, {"https://foo.gstatic.com/", false, true, "https://www.lexico.com/", "", false, 7, "kGoogleSubFrameOnNonGooglePageInitiated with TrustedParams"}, {"https://foo.gstatic.com/", false, false, "", "", false, 7, "kGoogleSubFrameOnNonGooglePageInitiated without TrustedParams"}, // Bucket 8, kNonGooglePageInitiatedFromFrameOrigin, is deprecated. }; TEST(VariationsHttpHeadersTest, PopulateUrlValidationResultHistograms) { const GURL invalid_url("invalid"); const GURL not_google("https://heavnlydonuts.com/"); const GURL should_append("https://youtube.com"); const GURL wrong_scheme("ftp://foo.com/"); const GURL google_not_https("http://google.com/"); const std::string append = "Append"; const std::string remove = "Remove"; base::HistogramTester tester; ASSERT_FALSE(ShouldAppendVariationsHeaderForTesting(invalid_url, append)); ASSERT_FALSE(ShouldAppendVariationsHeaderForTesting(not_google, append)); ASSERT_TRUE(ShouldAppendVariationsHeaderForTesting(should_append, append)); ASSERT_FALSE(ShouldAppendVariationsHeaderForTesting(wrong_scheme, remove)); ASSERT_FALSE( ShouldAppendVariationsHeaderForTesting(google_not_https, remove)); // Verify that the Append suffixed histogram has a sample corresponding to // the validation result for the three URLs validated for appending. const std::string append_histogram = "Variations.Headers.URLValidationResult.Append"; tester.ExpectTotalCount(append_histogram, 3); EXPECT_THAT(tester.GetAllSamples(append_histogram), testing::ElementsAre(base::Bucket(0, 1), base::Bucket(2, 1), base::Bucket(3, 1))); // Verify that the Remove suffixed histogram has a sample corresponding to // the validation result for the two URLs validated for removal. const std::string remove_histogram = "Variations.Headers.URLValidationResult.Remove"; tester.ExpectTotalCount(remove_histogram, 2); EXPECT_THAT(tester.GetAllSamples(remove_histogram), testing::ElementsAre(base::Bucket(4, 1), base::Bucket(5, 1))); } TEST(VariationsHttpHeadersTest, PopulateDomainOwnerHistogram) { const GURL destination("https://fonts.googleapis.com/foo"); network::ResourceRequest request = CreateResourceRequest( /*request_initiator_url=*/"https://docs.google.com/", /*is_main_frame=*/false, /*has_trusted_params=*/false, /*isolation_info_top_frame_origin_url=*/"", /*isolation_info_frame_origin_url=*/""); base::HistogramTester tester; AppendVariationsHeader(destination, Owner::kUnknownFromRenderer, &request); AppendVariationsHeader(destination, Owner::kUnknown, &request); AppendVariationsHeader(destination, Owner::kNotGoogle, &request); AppendVariationsHeader(destination, Owner::kGoogle, &request); EXPECT_THAT(tester.GetAllSamples("Variations.Headers.DomainOwner"), testing::ElementsAre(base::Bucket(0, 1), base::Bucket(1, 1), base::Bucket(2, 1), base::Bucket(3, 1))); } INSTANTIATE_TEST_SUITE_P( VariationsHttpHeadersTest, PopulateRequestContextHistogramTest, testing::ValuesIn(PopulateRequestContextHistogramTest::kCases)); TEST_P(PopulateRequestContextHistogramTest, PopulateRequestContextHistogram) { PopulateRequestContextHistogramData data = GetParam(); SCOPED_TRACE(data.name); network::ResourceRequest request = CreateResourceRequest( data.request_initiator_url, data.is_main_frame, data.has_trusted_params, data.isolation_info_top_frame_origin_url, data.isolation_info_frame_origin_url); base::HistogramTester tester; AppendVariationsHeader( GURL("https://foo.google.com"), data.is_top_level_google_owned ? Owner::kGoogle : Owner::kNotGoogle, &request); // Verify that the histogram has a single sample corresponding to the request // context category. const std::string histogram = "Variations.Headers.RequestContextCategory"; tester.ExpectUniqueSample(histogram, data.bucket, 1); } } // namespace variations
{ "content_hash": "91a8d43cfd080fcb11096ea711c8e0ce", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 80, "avg_line_length": 41.2836676217765, "alnum_prop": 0.6566490838423098, "repo_name": "ric2b/Vivaldi-browser", "id": "dc073e0b3d84a333738de372022d164cb1e74714", "size": "14408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/components/variations/net/variations_http_headers_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using NUnit.Framework; using VanillaTransformer.Core.PostTransformations; namespace VanillaTransformer.Tests.PostTransformations { [TestFixture] public class ReFormatJSONTest { [Test] public void should_be_able_to_reformat_json() { //ARRANGE var transformer = new ReFormatJSONTransformation(); const string sampleJson = "{\"someproperty1\":\"value1\", \"someproperty2\":\"value2\"}"; //ACT var result = transformer.Execute(sampleJson); //ASSERT const string expectedResult = "{\r\n \"someproperty1\": \"value1\",\r\n \"someproperty2\": \"value2\"\r\n}"; Assert.AreEqual(expectedResult, result); } [Test] public void should_strip_forbidden_comments() { //ARRANGE var transformer = new ReFormatJSONTransformation(); const string sampleJson = "{/*Invalid comment*/ \"someproperty1\":\"value1\", \"someproperty2\":\"value2\"}"; //ACT var result = transformer.Execute(sampleJson); //ASSERT const string expectedResult = "{\r\n \"someproperty1\": \"value1\",\r\n \"someproperty2\": \"value2\"\r\n}"; Assert.AreEqual(expectedResult, result); } [Test] public void should_break_trying_to_reformat_invalid_json() { //ARRANGE var transformer = new ReFormatJSONTransformation(); const string sampleJson = "{\"someproperty1\":\"va\\lue1\", \"someproperty2\":\"value2\"}"; //ACT Assert.Catch(()=> transformer.Execute(sampleJson)); } } }
{ "content_hash": "3875dfd5f6762b907c9c0f16d9fb750f", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 122, "avg_line_length": 35.28, "alnum_prop": 0.5493197278911565, "repo_name": "cezarypiatek/VanillaTransformer", "id": "53be8b93e9f14d9c6e58d6de527f780f7bf0c60f", "size": "1766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/VanillaTransformer.Tests/PostTransformations/ReFormatJSONTest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "115185" }, { "name": "PowerShell", "bytes": "13824" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk"> <report_format_detail> <FileFormat> <FormatID>109</FormatID> <FormatName>AutoCAD Compiled Menu</FormatName> <FormatVersion> </FormatVersion> <FormatAliases> </FormatAliases> <FormatFamilies> </FormatFamilies> <FormatTypes> </FormatTypes> <FormatDisclosure> </FormatDisclosure> <FormatDescription>This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select ‘Add an Entry’.</FormatDescription> <BinaryFileFormat>Text</BinaryFileFormat> <ByteOrders> </ByteOrders> <ReleaseDate> </ReleaseDate> <WithdrawnDate> </WithdrawnDate> <ProvenanceSourceID>1</ProvenanceSourceID> <ProvenanceName>Digital Preservation Department / The National Archives</ProvenanceName> <ProvenanceSourceDate>02 Aug 2005</ProvenanceSourceDate> <ProvenanceDescription> </ProvenanceDescription> <LastUpdatedDate>02 Aug 2005</LastUpdatedDate> <FormatNote> </FormatNote> <FormatRisk> </FormatRisk> <TechnicalEnvironment> </TechnicalEnvironment> <FileFormatIdentifier> <Identifier>x-fmt/68</Identifier> <IdentifierType>PUID</IdentifierType> </FileFormatIdentifier> <ExternalSignature> <ExternalSignatureID>103</ExternalSignatureID> <Signature>mnc</Signature> <SignatureType>File extension</SignatureType> </ExternalSignature> </FileFormat> <SearchCriteria>Criteria</SearchCriteria> </report_format_detail> </PRONOM-Report>
{ "content_hash": "743073a02521802548cfb0a332581b91", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 440, "avg_line_length": 41.38775510204081, "alnum_prop": 0.6849112426035503, "repo_name": "exponential-decay/the-format-registry", "id": "32e75ad3a0d5cc59cba8534f3556a5cfebb7a9da", "size": "2032", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "private/pronom/pronom-latest/x-fmt/x-fmt68.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "143" }, { "name": "JavaScript", "bytes": "23160" }, { "name": "PHP", "bytes": "607105" }, { "name": "XSLT", "bytes": "6980" } ], "symlink_target": "" }
namespace eskeleton { class TranslateSprState : public ee::TranslateSpriteState { public: TranslateSprState(ee::SpriteSelection* selection, const sm::vec2& first_pos); protected: virtual void Translate(const sm::vec2& offset) override; }; // TranslateSprState } #endif // _EASYSKELETON_TRANSLATE_SPR_STATE_H_
{ "content_hash": "d2265b91d7c140f07fd9a48b5004745f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 78, "avg_line_length": 19.8125, "alnum_prop": 0.7634069400630915, "repo_name": "xzrunner/easyeditor", "id": "81ab9183fbd1f510575cdb2503c8319891f18fc8", "size": "446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "easyskeleton/src/easyskeleton/TranslateSprState.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "118661" }, { "name": "C++", "bytes": "5152354" }, { "name": "GLSL", "bytes": "10503" }, { "name": "Lua", "bytes": "127544" }, { "name": "Makefile", "bytes": "210" } ], "symlink_target": "" }
using InfrastructureAsCode.Core.Extensions; using InfrastructureAsCode.Powershell.Commands.Base; using Microsoft.SharePoint.Client; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Threading.Tasks; namespace InfrastructureAsCode.Powershell.Commands.Sites { /// <summary> /// The function cmdlet will enable or disable the modern UI /// </summary> /// <remarks> /// Turn off the Modern UI /// </remarks> [Cmdlet(VerbsCommon.Set, "IaCModernUI", SupportsShouldProcess = true)] public class SetIaCModernUI : IaCCmdlet { /// <summary> /// Should we enable modern UI /// </summary> [Parameter(Mandatory = false, HelpMessage = "If you pass this in, it will reenable ModernUI")] public SwitchParameter EnableModernUI { get; set; } /// <summary> /// Should we enable modern UI /// </summary> [Parameter(Mandatory = false, HelpMessage = "If you pass this in, it will assume its a web")] public SwitchParameter IsWeb { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); var featureSiteGuid = new System.Guid("E3540C7D-6BEA-403C-A224-1A12EAFEE4C4"); var featureWebGuid = new System.Guid("52E14B6F-B1BB-4969-B89B-C4FAA56745EF"); // To apply the script to the site collection level, [set as default]. var connectionUrl = this.ClientContext.Url; if (!EnableModernUI) { // To turn off the new UI by default in the new site, uncomment the next line. if (!IsWeb) { this.ClientContext.Load(this.ClientContext.Site); this.ClientContext.Site.ActivateFeature(featureSiteGuid); } else { this.ClientContext.Load(this.ClientContext.Web); this.ClientContext.Web.ActivateFeature(featureWebGuid); } } else { // To re-enable the option to use the new UI after having first disabled it, uncomment the next line. // and comment the preceding line. if (!IsWeb) { this.ClientContext.Load(this.ClientContext.Site); this.ClientContext.Site.DeactivateFeature(featureSiteGuid); } else { this.ClientContext.Load(this.ClientContext.Web); this.ClientContext.Web.DeactivateFeature(featureWebGuid); } } this.ClientContext.ExecuteQueryRetry(); } } }
{ "content_hash": "9299ec94b678b50d92ced46eb23f185a", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 117, "avg_line_length": 35.59493670886076, "alnum_prop": 0.5796586059743954, "repo_name": "pinch-perfect/Infrastructure-As-Code", "id": "255e20cd0852db72b9130eb80285094a6909279d", "size": "2814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "InfrastructureAsCode.Powershell/Commands/Sites/SetIaCModernUI.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1226699" }, { "name": "PowerShell", "bytes": "8571" } ], "symlink_target": "" }
 #include <aws/ec2/model/ReservedInstancesOffering.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { ReservedInstancesOffering::ReservedInstancesOffering() : m_availabilityZoneHasBeenSet(false), m_duration(0), m_durationHasBeenSet(false), m_fixedPrice(0.0), m_fixedPriceHasBeenSet(false), m_instanceType(InstanceType::NOT_SET), m_instanceTypeHasBeenSet(false), m_productDescription(RIProductDescription::NOT_SET), m_productDescriptionHasBeenSet(false), m_reservedInstancesOfferingIdHasBeenSet(false), m_usagePrice(0.0), m_usagePriceHasBeenSet(false), m_currencyCode(CurrencyCodeValues::NOT_SET), m_currencyCodeHasBeenSet(false), m_instanceTenancy(Tenancy::NOT_SET), m_instanceTenancyHasBeenSet(false), m_marketplace(false), m_marketplaceHasBeenSet(false), m_offeringClass(OfferingClassType::NOT_SET), m_offeringClassHasBeenSet(false), m_offeringType(OfferingTypeValues::NOT_SET), m_offeringTypeHasBeenSet(false), m_pricingDetailsHasBeenSet(false), m_recurringChargesHasBeenSet(false), m_scope(Scope::NOT_SET), m_scopeHasBeenSet(false) { } ReservedInstancesOffering::ReservedInstancesOffering(const XmlNode& xmlNode) : m_availabilityZoneHasBeenSet(false), m_duration(0), m_durationHasBeenSet(false), m_fixedPrice(0.0), m_fixedPriceHasBeenSet(false), m_instanceType(InstanceType::NOT_SET), m_instanceTypeHasBeenSet(false), m_productDescription(RIProductDescription::NOT_SET), m_productDescriptionHasBeenSet(false), m_reservedInstancesOfferingIdHasBeenSet(false), m_usagePrice(0.0), m_usagePriceHasBeenSet(false), m_currencyCode(CurrencyCodeValues::NOT_SET), m_currencyCodeHasBeenSet(false), m_instanceTenancy(Tenancy::NOT_SET), m_instanceTenancyHasBeenSet(false), m_marketplace(false), m_marketplaceHasBeenSet(false), m_offeringClass(OfferingClassType::NOT_SET), m_offeringClassHasBeenSet(false), m_offeringType(OfferingTypeValues::NOT_SET), m_offeringTypeHasBeenSet(false), m_pricingDetailsHasBeenSet(false), m_recurringChargesHasBeenSet(false), m_scope(Scope::NOT_SET), m_scopeHasBeenSet(false) { *this = xmlNode; } ReservedInstancesOffering& ReservedInstancesOffering::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode availabilityZoneNode = resultNode.FirstChild("availabilityZone"); if(!availabilityZoneNode.IsNull()) { m_availabilityZone = StringUtils::Trim(availabilityZoneNode.GetText().c_str()); m_availabilityZoneHasBeenSet = true; } XmlNode durationNode = resultNode.FirstChild("duration"); if(!durationNode.IsNull()) { m_duration = StringUtils::ConvertToInt64(StringUtils::Trim(durationNode.GetText().c_str()).c_str()); m_durationHasBeenSet = true; } XmlNode fixedPriceNode = resultNode.FirstChild("fixedPrice"); if(!fixedPriceNode.IsNull()) { m_fixedPrice = StringUtils::ConvertToDouble(StringUtils::Trim(fixedPriceNode.GetText().c_str()).c_str()); m_fixedPriceHasBeenSet = true; } XmlNode instanceTypeNode = resultNode.FirstChild("instanceType"); if(!instanceTypeNode.IsNull()) { m_instanceType = InstanceTypeMapper::GetInstanceTypeForName(StringUtils::Trim(instanceTypeNode.GetText().c_str()).c_str()); m_instanceTypeHasBeenSet = true; } XmlNode productDescriptionNode = resultNode.FirstChild("productDescription"); if(!productDescriptionNode.IsNull()) { m_productDescription = RIProductDescriptionMapper::GetRIProductDescriptionForName(StringUtils::Trim(productDescriptionNode.GetText().c_str()).c_str()); m_productDescriptionHasBeenSet = true; } XmlNode reservedInstancesOfferingIdNode = resultNode.FirstChild("reservedInstancesOfferingId"); if(!reservedInstancesOfferingIdNode.IsNull()) { m_reservedInstancesOfferingId = StringUtils::Trim(reservedInstancesOfferingIdNode.GetText().c_str()); m_reservedInstancesOfferingIdHasBeenSet = true; } XmlNode usagePriceNode = resultNode.FirstChild("usagePrice"); if(!usagePriceNode.IsNull()) { m_usagePrice = StringUtils::ConvertToDouble(StringUtils::Trim(usagePriceNode.GetText().c_str()).c_str()); m_usagePriceHasBeenSet = true; } XmlNode currencyCodeNode = resultNode.FirstChild("currencyCode"); if(!currencyCodeNode.IsNull()) { m_currencyCode = CurrencyCodeValuesMapper::GetCurrencyCodeValuesForName(StringUtils::Trim(currencyCodeNode.GetText().c_str()).c_str()); m_currencyCodeHasBeenSet = true; } XmlNode instanceTenancyNode = resultNode.FirstChild("instanceTenancy"); if(!instanceTenancyNode.IsNull()) { m_instanceTenancy = TenancyMapper::GetTenancyForName(StringUtils::Trim(instanceTenancyNode.GetText().c_str()).c_str()); m_instanceTenancyHasBeenSet = true; } XmlNode marketplaceNode = resultNode.FirstChild("marketplace"); if(!marketplaceNode.IsNull()) { m_marketplace = StringUtils::ConvertToBool(StringUtils::Trim(marketplaceNode.GetText().c_str()).c_str()); m_marketplaceHasBeenSet = true; } XmlNode offeringClassNode = resultNode.FirstChild("offeringClass"); if(!offeringClassNode.IsNull()) { m_offeringClass = OfferingClassTypeMapper::GetOfferingClassTypeForName(StringUtils::Trim(offeringClassNode.GetText().c_str()).c_str()); m_offeringClassHasBeenSet = true; } XmlNode offeringTypeNode = resultNode.FirstChild("offeringType"); if(!offeringTypeNode.IsNull()) { m_offeringType = OfferingTypeValuesMapper::GetOfferingTypeValuesForName(StringUtils::Trim(offeringTypeNode.GetText().c_str()).c_str()); m_offeringTypeHasBeenSet = true; } XmlNode pricingDetailsNode = resultNode.FirstChild("pricingDetailsSet"); if(!pricingDetailsNode.IsNull()) { XmlNode pricingDetailsMember = pricingDetailsNode.FirstChild("item"); while(!pricingDetailsMember.IsNull()) { m_pricingDetails.push_back(pricingDetailsMember); pricingDetailsMember = pricingDetailsMember.NextNode("item"); } m_pricingDetailsHasBeenSet = true; } XmlNode recurringChargesNode = resultNode.FirstChild("recurringCharges"); if(!recurringChargesNode.IsNull()) { XmlNode recurringChargesMember = recurringChargesNode.FirstChild("item"); while(!recurringChargesMember.IsNull()) { m_recurringCharges.push_back(recurringChargesMember); recurringChargesMember = recurringChargesMember.NextNode("item"); } m_recurringChargesHasBeenSet = true; } XmlNode scopeNode = resultNode.FirstChild("scope"); if(!scopeNode.IsNull()) { m_scope = ScopeMapper::GetScopeForName(StringUtils::Trim(scopeNode.GetText().c_str()).c_str()); m_scopeHasBeenSet = true; } } return *this; } void ReservedInstancesOffering::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_availabilityZoneHasBeenSet) { oStream << location << index << locationValue << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&"; } if(m_durationHasBeenSet) { oStream << location << index << locationValue << ".Duration=" << m_duration << "&"; } if(m_fixedPriceHasBeenSet) { oStream << location << index << locationValue << ".FixedPrice=" << m_fixedPrice << "&"; } if(m_instanceTypeHasBeenSet) { oStream << location << index << locationValue << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&"; } if(m_productDescriptionHasBeenSet) { oStream << location << index << locationValue << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&"; } if(m_reservedInstancesOfferingIdHasBeenSet) { oStream << location << index << locationValue << ".ReservedInstancesOfferingId=" << StringUtils::URLEncode(m_reservedInstancesOfferingId.c_str()) << "&"; } if(m_usagePriceHasBeenSet) { oStream << location << index << locationValue << ".UsagePrice=" << m_usagePrice << "&"; } if(m_currencyCodeHasBeenSet) { oStream << location << index << locationValue << ".CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&"; } if(m_instanceTenancyHasBeenSet) { oStream << location << index << locationValue << ".InstanceTenancy=" << TenancyMapper::GetNameForTenancy(m_instanceTenancy) << "&"; } if(m_marketplaceHasBeenSet) { oStream << location << index << locationValue << ".Marketplace=" << std::boolalpha << m_marketplace << "&"; } if(m_offeringClassHasBeenSet) { oStream << location << index << locationValue << ".OfferingClass=" << OfferingClassTypeMapper::GetNameForOfferingClassType(m_offeringClass) << "&"; } if(m_offeringTypeHasBeenSet) { oStream << location << index << locationValue << ".OfferingType=" << OfferingTypeValuesMapper::GetNameForOfferingTypeValues(m_offeringType) << "&"; } if(m_pricingDetailsHasBeenSet) { unsigned pricingDetailsIdx = 1; for(auto& item : m_pricingDetails) { Aws::StringStream pricingDetailsSs; pricingDetailsSs << location << index << locationValue << ".PricingDetailsSet." << pricingDetailsIdx++; item.OutputToStream(oStream, pricingDetailsSs.str().c_str()); } } if(m_recurringChargesHasBeenSet) { unsigned recurringChargesIdx = 1; for(auto& item : m_recurringCharges) { Aws::StringStream recurringChargesSs; recurringChargesSs << location << index << locationValue << ".RecurringCharges." << recurringChargesIdx++; item.OutputToStream(oStream, recurringChargesSs.str().c_str()); } } if(m_scopeHasBeenSet) { oStream << location << index << locationValue << ".Scope=" << ScopeMapper::GetNameForScope(m_scope) << "&"; } } void ReservedInstancesOffering::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_availabilityZoneHasBeenSet) { oStream << location << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&"; } if(m_durationHasBeenSet) { oStream << location << ".Duration=" << m_duration << "&"; } if(m_fixedPriceHasBeenSet) { oStream << location << ".FixedPrice=" << m_fixedPrice << "&"; } if(m_instanceTypeHasBeenSet) { oStream << location << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&"; } if(m_productDescriptionHasBeenSet) { oStream << location << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&"; } if(m_reservedInstancesOfferingIdHasBeenSet) { oStream << location << ".ReservedInstancesOfferingId=" << StringUtils::URLEncode(m_reservedInstancesOfferingId.c_str()) << "&"; } if(m_usagePriceHasBeenSet) { oStream << location << ".UsagePrice=" << m_usagePrice << "&"; } if(m_currencyCodeHasBeenSet) { oStream << location << ".CurrencyCode=" << CurrencyCodeValuesMapper::GetNameForCurrencyCodeValues(m_currencyCode) << "&"; } if(m_instanceTenancyHasBeenSet) { oStream << location << ".InstanceTenancy=" << TenancyMapper::GetNameForTenancy(m_instanceTenancy) << "&"; } if(m_marketplaceHasBeenSet) { oStream << location << ".Marketplace=" << std::boolalpha << m_marketplace << "&"; } if(m_offeringClassHasBeenSet) { oStream << location << ".OfferingClass=" << OfferingClassTypeMapper::GetNameForOfferingClassType(m_offeringClass) << "&"; } if(m_offeringTypeHasBeenSet) { oStream << location << ".OfferingType=" << OfferingTypeValuesMapper::GetNameForOfferingTypeValues(m_offeringType) << "&"; } if(m_pricingDetailsHasBeenSet) { unsigned pricingDetailsIdx = 1; for(auto& item : m_pricingDetails) { Aws::StringStream pricingDetailsSs; pricingDetailsSs << location << ".PricingDetailsSet." << pricingDetailsIdx++; item.OutputToStream(oStream, pricingDetailsSs.str().c_str()); } } if(m_recurringChargesHasBeenSet) { unsigned recurringChargesIdx = 1; for(auto& item : m_recurringCharges) { Aws::StringStream recurringChargesSs; recurringChargesSs << location << ".RecurringCharges." << recurringChargesIdx++; item.OutputToStream(oStream, recurringChargesSs.str().c_str()); } } if(m_scopeHasBeenSet) { oStream << location << ".Scope=" << ScopeMapper::GetNameForScope(m_scope) << "&"; } } } // namespace Model } // namespace EC2 } // namespace Aws
{ "content_hash": "556e0dea9a589d13935932489a264918", "timestamp": "", "source": "github", "line_count": 363, "max_line_length": 169, "avg_line_length": 35.98347107438016, "alnum_prop": 0.697060174552136, "repo_name": "svagionitis/aws-sdk-cpp", "id": "e09e8b96741f3ada37dc439e59e1a8beb3ff183f", "size": "13635", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ec2/source/model/ReservedInstancesOffering.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2313" }, { "name": "C++", "bytes": "104799778" }, { "name": "CMake", "bytes": "455533" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "243075" }, { "name": "Python", "bytes": "72896" }, { "name": "Shell", "bytes": "2803" } ], "symlink_target": "" }
package org.apache.derbyTesting.functionTests.tests.lang; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import org.apache.derby.iapi.reference.SQLState; import org.apache.derbyTesting.junit.BaseTestSuite; import org.apache.derbyTesting.junit.CleanDatabaseTestSetup; import org.apache.derbyTesting.junit.DatabasePropertyTestSetup; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.TestConfiguration; /** * Test sequences. */ public class SequenceTest extends GeneratedColumnsHelper { private static final String TEST_DBO = "TEST_DBO"; private static final String ALPHA = "ALPHA"; private static final String BETA = "BETA"; private static final String[] LEGAL_USERS = {TEST_DBO, ALPHA, BETA}; private static final String TOO_MANY_UNUSED_SEQUENCES = "X0Y93"; public SequenceTest(String name) { super(name); // TODO Auto-generated constructor stub } // SETUP /** * Construct top level suite in this JUnit test */ public static Test suite() { BaseTestSuite suite = new BaseTestSuite(SequenceTest.class, "Sequence Test"); // Need atleast JSR169 to run these tests if (!JDBC.vmSupportsJSR169() && !JDBC.vmSupportsJDBC3()) { return suite; } Test cleanTest = new CleanDatabaseTestSetup(suite); Test authenticatedTest = DatabasePropertyTestSetup.builtinAuthentication (cleanTest, LEGAL_USERS, "sequence"); Test authorizedTest = TestConfiguration.sqlAuthorizationDecorator(authenticatedTest); return authorizedTest; } public void test_01_CreateSequence() throws SQLException { Statement s = createStatement(); s.executeUpdate("CREATE SEQUENCE mySeq"); } public void test_02_DropSequence() throws SQLException { Statement s = createStatement(); s.executeUpdate("CREATE SEQUENCE mySeq1"); s.executeUpdate("DROP SEQUENCE mySeq1 restrict"); } public void test_03_DuplicateCreationFailure() throws SQLException { Statement s = null; try { s = createStatement(); s.executeUpdate("CREATE SEQUENCE mySeq1"); s.executeUpdate("CREATE SEQUENCE mySeq1"); } catch (SQLException sqle) { assertSQLState("X0Y68", sqle); }finally{ s.executeUpdate("DROP SEQUENCE mySeq1 restrict"); // Drop the one created. } } public void test_04_ImplicitSchemaCreation() throws SQLException { Connection adminCon = openUserConnection(TEST_DBO); Connection alphaCon = openUserConnection(ALPHA); Statement stmt = alphaCon.createStatement(); // should implicitly create schema ALPHA stmt.executeUpdate("CREATE SEQUENCE alpha_seq"); stmt.executeUpdate("DROP SEQUENCE alpha_seq restrict"); stmt.close(); alphaCon.close(); adminCon.close(); } public void test_05CreateWithSchemaSpecified() throws SQLException { // create DB Connection alphaCon = openUserConnection(ALPHA); Statement stmt = alphaCon.createStatement(); // should implicitly create schema ALPHA stmt.executeUpdate("CREATE SEQUENCE alpha.alpha_seq"); stmt.executeUpdate("DROP SEQUENCE alpha.alpha_seq restrict"); stmt.close(); alphaCon.close(); } public void test_06_CreateWithSchemaSpecifiedCreateTrue() throws SQLException { Connection alphaCon = openUserConnection(ALPHA); Statement stmt = alphaCon.createStatement(); // should implicitly create schema ALPHA stmt.executeUpdate("CREATE SEQUENCE alpha.alpha_seq"); stmt.executeUpdate("DROP SEQUENCE alpha.alpha_seq restrict"); stmt.close(); alphaCon.close(); } public void test_07_CreateWithSchemaDropWithNoSchema() throws SQLException { Connection alphaCon = openUserConnection(ALPHA); Statement stmt = alphaCon.createStatement(); // should implicitly create schema ALPHA stmt.executeUpdate("CREATE SEQUENCE alpha.alpha_seq"); stmt.executeUpdate("DROP SEQUENCE alpha_seq restrict"); stmt.close(); alphaCon.close(); } /** * Test trying to drop a sequence in a schema that doesn't belong to one */ public void test_08_DropOtherSchemaSequence() throws SQLException { Connection adminCon = openUserConnection(TEST_DBO); Connection alphaCon = openUserConnection(ALPHA); Statement stmtAlpha = alphaCon.createStatement(); stmtAlpha.executeUpdate("CREATE SEQUENCE alpha_seq"); Connection betaCon = openUserConnection(BETA); Statement stmtBeta = betaCon.createStatement(); // should implicitly create schema ALPHA assertStatementError("42507", stmtBeta, "DROP SEQUENCE alpha.alpha_seq restrict"); // Cleanup: stmtAlpha.executeUpdate("DROP SEQUENCE alpha_seq restrict"); stmtAlpha.close(); stmtBeta.close(); alphaCon.close(); betaCon.close(); adminCon.close(); } /** * Test trying to create a sequence in a schema that doesn't belong to one */ public void test_09_CreateOtherSchemaSequence() throws SQLException { // create DB Connection adminCon = openUserConnection(TEST_DBO); Connection alphaCon = openUserConnection(ALPHA); Statement stmtAlpha = alphaCon.createStatement(); stmtAlpha.executeUpdate("CREATE SEQUENCE alpha_seq"); Connection betaCon = openUserConnection(BETA); Statement stmtBeta = betaCon.createStatement(); // should implicitly create schema ALPHA assertStatementError("42507", stmtBeta, "CREATE SEQUENCE alpha.alpha_seq3"); // Cleanup: stmtAlpha.executeUpdate("DROP SEQUENCE alpha_seq restrict"); stmtAlpha.close(); stmtBeta.close(); alphaCon.close(); betaCon.close(); adminCon.close(); } public void test_09a_createSequenceWithArguments() throws Exception { Connection alphaCon = openUserConnection(ALPHA); goodStatement(alphaCon, "CREATE SEQUENCE small1 AS SMALLINT START WITH 0 INCREMENT BY 1"); goodStatement(alphaCon, "CREATE SEQUENCE small2 AS SMALLINT START WITH " + Short.MIN_VALUE + " MAXVALUE " + Short.MAX_VALUE); goodStatement(alphaCon, "CREATE SEQUENCE small3 AS SMALLINT START WITH 1200" + " INCREMENT BY -5 MAXVALUE 32000 NO MINVALUE CYCLE"); // maxvalue out of range expectCompilationError(alphaCon, SQLState.LANG_SEQ_ARG_OUT_OF_DATATYPE_RANGE, "CREATE SEQUENCE small3 AS SMALLINT START WITH " + Short.MIN_VALUE + " MAXVALUE " + Integer.MAX_VALUE); // start with out of range expectCompilationError(alphaCon, SQLState.LANG_SEQ_INVALID_START, "CREATE SEQUENCE small4 AS SMALLINT START WITH " + Integer.MIN_VALUE); // minvalue larger than maxvalue negative expectCompilationError(alphaCon, SQLState.LANG_SEQ_MIN_EXCEEDS_MAX, "CREATE SEQUENCE small5 AS SMALLINT MAXVALUE -20000 MINVALUE -1"); goodStatement(alphaCon, "CREATE SEQUENCE int1 AS INTEGER START WITH " + Integer.MIN_VALUE + " INCREMENT BY -10 CYCLE"); goodStatement(alphaCon, "CREATE SEQUENCE int2 AS INTEGER INCREMENT BY 5" + " MAXVALUE " + Integer.MAX_VALUE); goodStatement(alphaCon, "CREATE SEQUENCE int3 AS INTEGER START WITH 1200 INCREMENT BY 5 " + "NO MAXVALUE MINVALUE -320000 CYCLE"); // minvalue out of range expectCompilationError(alphaCon, SQLState.LANG_SEQ_ARG_OUT_OF_DATATYPE_RANGE, "CREATE SEQUENCE int4 AS INTEGER START WITH " + Integer.MIN_VALUE + " MAXVALUE " + Short.MAX_VALUE + " MINVALUE " + Long.MIN_VALUE); // increment 0 expectCompilationError(alphaCon, SQLState.LANG_SEQ_INCREMENT_ZERO, "CREATE SEQUENCE int5 AS INTEGER INCREMENT BY 0"); goodStatement(alphaCon, "CREATE SEQUENCE long1 AS BIGINT START WITH " + Long.MIN_VALUE + " INCREMENT BY -100 NO CYCLE"); goodStatement(alphaCon, "CREATE SEQUENCE long2 AS BIGINT INCREMENT BY 25" + " MAXVALUE " + Integer.MAX_VALUE); goodStatement(alphaCon, "CREATE SEQUENCE long3 AS BIGINT START WITH 0 INCREMENT BY 5 " + "NO MAXVALUE MINVALUE " + Long.MIN_VALUE + " CYCLE"); // invalid minvalue expectCompilationError(alphaCon, SQLState.LANG_SEQ_ARG_OUT_OF_DATATYPE_RANGE, "CREATE SEQUENCE long4 AS BIGINT START WITH " + Integer.MAX_VALUE + " MINVALUE " + Long.MAX_VALUE); // minvalue larger than maxvalue expectCompilationError(alphaCon, SQLState.LANG_SEQ_MIN_EXCEEDS_MAX, "CREATE SEQUENCE long5 AS BIGINT START WITH 0 MAXVALUE 100000 MINVALUE 100001"); // should fail for non-int TYPES expectCompilationError(alphaCon, SQLState.LANG_SYNTAX_ERROR, "CREATE SEQUENCE char1 AS CHAR INCREMENT BY 1"); } /** * initial test for next value * @throws SQLException on error */ public void test_10_NextValue() throws SQLException { Statement s = createStatement(); s.executeUpdate("CREATE SEQUENCE mySeq1"); s.execute("SELECT NEXT VALUE FOR mySeq1 from sys.systables"); s.execute("DROP SEQUENCE mySeq1 restrict"); } /** * Verify that sequences can't be used in many contexts. */ public void test_11_forbiddenContexts() throws Exception { Connection conn = openUserConnection(ALPHA); goodStatement( conn, "create sequence seq_11_a\n" ); goodStatement( conn, "create sequence seq_11_b\n" ); String illegalSequence = SQLState.LANG_NEXT_VALUE_FOR_ILLEGAL; // sequences not allowed in WHERE clause expectCompilationError( conn, illegalSequence, "select * from sys.systables where ( next value for seq_11_a ) > 100\n" ); // sequences not allowed in HAVING clause expectCompilationError ( conn, illegalSequence, "select max( conglomeratenumber ), tableid\n" + "from sys.sysconglomerates\n" + "group by tableid\n" + "having max( conglomeratenumber ) > ( next value for seq_11_a )\n" ); // sequences not allowed in ON clause expectCompilationError ( conn, illegalSequence, "select * from sys.sysconglomerates left join sys.sysschemas on conglomeratenumber = ( next value for seq_11_a )\n" ); // sequences not allowed in CHECK constraints expectCompilationError ( conn, illegalSequence, "create table t_11_1( a int check ( a > ( next value for seq_11_a ) ) )\n" ); // sequences not allowed in generated columns expectCompilationError ( conn, illegalSequence, "create table t_11_1( a int, b generated always as ( a + ( next value for seq_11_a ) ) )\n" ); // sequences not allowed in aggregates expectCompilationError ( conn, illegalSequence, "select max( next value for seq_11_a ) from sys.systables\n" ); // sequences not allowed in CASE expressions expectCompilationError ( conn, illegalSequence, "values case when ( next value for seq_11_a ) < 0 then 100 else 200 end\n" ); // sequences not allowed in DISTINCT clauses expectCompilationError ( conn, illegalSequence, "select distinct( next value for seq_11_a ) from sys.systables\n" ); // sequences not allowed in ORDER BY clauses expectCompilationError ( conn, illegalSequence, "select tableid, ( next value for seq_11_a ) a from sys.systables order by a\n" ); // sequences not allowed in GROUP BY expressions expectCompilationError ( conn, illegalSequence, "select max( tableid ), ( next value for seq_11_a ) from sys.systables group by ( next value for seq_11_a )\n" ); // given sequence only allowed once per statement. see DERBY-4513. expectCompilationError ( conn, SQLState.LANG_SEQUENCE_REFERENCED_TWICE, "select next value for seq_11_a, next value for seq_11_a from sys.systables where 1=2\n" ); // however, two different sequences can appear in a statement goodStatement( conn, "select next value for seq_11_a, next value for seq_11_b from sys.systables where 1=2\n" ); } /** * Verify that optional clauses can appear in any order and redundant clauses * are forbidden. */ public void test_12_clauseOrder() throws Exception { Connection conn = openUserConnection(ALPHA); goodSequence ( conn, "seq_12_a", // name "", // clauses "INTEGER", // datatype Integer.MIN_VALUE, // initial Integer.MIN_VALUE, // min Integer.MAX_VALUE, // max 1L, // step false // cycle ); goodSequence ( conn, "seq_12_b", // name "minvalue 5 increment by 3 cycle start with 100 maxvalue 1000000 as bigint", // clauses "BIGINT", // datatype 100L, // initial 5L, // min 1000000L, // max 3L, // step true // cycle ); goodSequence ( conn, "seq_12_c", // name "increment by 3 as smallint no cycle no maxvalue", // clauses "SMALLINT", // datatype Short.MIN_VALUE, // initial Short.MIN_VALUE, // min Short.MAX_VALUE, // max 3L, // step false // cycle ); goodSequence ( conn, "seq_12_d", // name "maxvalue 1000000000 start with -50 increment by -3 cycle no minvalue", // clauses "INTEGER", // datatype -50L, // initial Integer.MIN_VALUE, // min 1000000000, // max -3L, // step true // cycle ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 as smallint as bigint\n" ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 start with 3 start with 7\n" ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 minvalue 5 no minvalue\n" ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 maxvalue 5 no maxvalue\n" ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 increment by 7 increment by -7\n" ); expectCompilationError ( conn, DUPLICATE_CLAUSE, "create sequence bad_12 no cycle cycle\n" ); } private void goodSequence ( Connection conn, String sequenceName, String clauses, String datatype, long initialValue, long minValue, long maxValue, long stepValue, boolean cycle ) throws Exception { String statement = "create sequence " + sequenceName + " " + clauses; goodStatement( conn, statement ); PreparedStatement ps = chattyPrepare ( conn, "select sequencedatatype, startvalue, minimumvalue, maximumvalue, increment, cycleoption\n" + "from sys.syssequences\n" + "where sequencename = ?" ); ps.setString( 1, sequenceName.toUpperCase() ); ResultSet rs = ps.executeQuery(); rs.next(); int col = 1; assertEquals( datatype, rs.getString( col++ ) ); assertEquals( initialValue, rs.getLong( col++ ) ); assertEquals( minValue, rs.getLong( col++ ) ); assertEquals( maxValue, rs.getLong( col++ ) ); assertEquals( stepValue, rs.getLong( col++ ) ); assertEquals( cycle, rs.getString( col++ ).equals( "Y" ) ); rs.close(); ps.close(); } /** * Verify that restricted drops prevent objects from being orphaned. */ public void test_13_restrictedDrop() throws Exception { Connection conn = openUserConnection(ALPHA); goodStatement( conn, "create table t_13_a( a int )" ); goodStatement( conn, "create table t_13_b( a int )" ); String createStatement; String dropStatement; String createDependentObject; String dropDependentObject; String badDropState; createStatement = "create sequence seq_13_a"; dropStatement = "drop sequence seq_13_a restrict"; createDependentObject = "create trigger trig_13 after insert on t_13_a for each row insert into t_13_b( a ) values ( next value for seq_13_a )\n"; dropDependentObject = "drop trigger trig_13"; badDropState = FORBIDDEN_DROP_TRIGGER; verifyRestrictedDrop ( conn, createDependentObject, dropDependentObject, createStatement, dropStatement, badDropState ); createStatement = "create sequence seq_13_b"; dropStatement = "drop sequence seq_13_b restrict"; createDependentObject = "create view v_13( a, b ) as select a, next value for seq_13_b from t_13_a\n"; dropDependentObject = "drop view v_13"; badDropState = VIEW_DEPENDENCY; verifyRestrictedDrop ( conn, createDependentObject, dropDependentObject, createStatement, dropStatement, badDropState ); } /** * Verify that you can use sequences in insert statements driven * by selects. See DERBY-4803. */ public void test_14_insertSelect() throws Exception { Connection conn = openUserConnection(ALPHA); goodStatement( conn, "create sequence sequence_is" ); goodStatement( conn, "create table tis_1( a int )" ); goodStatement( conn, "create table tis_2( a int, b int )" ); goodStatement( conn, "insert into tis_1( a ) values ( 1 ), ( 2 )" ); goodStatement( conn, "insert into tis_2 select next value for sequence_is, a from tis_1" ); assertResults ( conn, "select * from tis_2 order by b", new String[][] { { "-2147483648", "1" }, { "-2147483647", "2" }, }, true ); } /** * Verify that the new sequence-related keywords are non-reserved keywords. */ public void test_15_5254() throws Exception { Connection conn = openUserConnection(ALPHA); goodStatement( conn, "create table t_5254( cycle int, minvalue int, maxvalue int )" ); goodStatement( conn, "drop table t_5254" ); } /** * Verify that trigger recompilation doesn't choke trying to create * two nested writable transactions. */ public void test_16_6137() throws Exception { //DERBY-6176 (Couple failures in SequenceGeneratorTest suite on // trunk(1466748) with weme 6.2. Disabling the test for small // devices. if ( JDBC.vmSupportsJSR169() ) { return; } Connection conn = openUserConnection( TEST_DBO ); goodStatement( conn, "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', '2' )" ); goodStatement( conn, "create table t_6137( rateID int generated always as identity primary key, amount decimal( 5,2 ) )" ); goodStatement( conn, "create table t_history_6137( changeID int primary key, amount decimal( 5,2 ) )" ); goodStatement( conn, "create sequence seq_6137 start with 1" ); goodStatement ( conn, "create trigger trg_t_6137_hist_del\n" + "after delete on t_6137\n" + "referencing old row as old\n" + "for each row\n" + " insert into t_history_6137 ( changeID, amount ) values (( next value for seq_6137 ), old.amount )\n" ); goodStatement( conn, "insert into t_6137( amount ) values ( 30.04 ), ( 60.04 ), ( 90.04 )" ); // invalidate the stored statements so that the trigger will have to be recompiled goodStatement( conn, "call syscs_util.syscs_invalidate_stored_statements()" ); // put the sequence in the cache assertResults ( conn, "values next value for seq_6137", new String[][] { { "1" }, }, true ); // verify that the trigger recompiles and fires correctly goodStatement( conn, "delete from t_6137 where rateID = 1" ); goodStatement( conn, "delete from t_6137 where rateID = 2" ); assertResults ( conn, "select * from t_history_6137 order by changeID", new String[][] { { "2", "30.04" }, { "3", "60.04" }, }, true ); // verify current value of sequence String peekAtSequence = "values syscs_util.syscs_peek_at_sequence('" + TEST_DBO + "', 'SEQ_6137')"; assertResults ( conn, peekAtSequence, new String[][] { { "4" }, }, true ); // tidy up goodStatement( conn, "drop trigger trg_t_6137_hist_del" ); goodStatement( conn, "drop table t_history_6137" ); goodStatement( conn, "drop table t_6137" ); goodStatement( conn, "drop sequence seq_6137 restrict" ); goodStatement( conn, "call syscs_util.syscs_set_database_property( 'derby.language.sequence.preallocator', null )" ); // verify that the uncleared cache does not leave a phantom sequence hanging around expectExecutionError( conn, MISSING_OBJECT, peekAtSequence ); expectCompilationError( conn, OBJECT_DOES_NOT_EXIST, "values next value for seq_6137" ); } /** * Verify that a sequence can be used in the same transaction * which created it. */ public void test_17_6554() throws Exception { Connection alphaConn = openUserConnection( ALPHA ); Connection betaConn = openUserConnection( BETA ); alphaConn.setAutoCommit( false ); betaConn.setAutoCommit( false ); String createSequence = "create sequence seq6554"; String nextValueFor = "values next value for seq6554"; String[][] nextValueForResults = new String[][] { { "-2147483648" }, }; goodStatement( alphaConn, createSequence ); assertResults( alphaConn, nextValueFor, nextValueForResults, true ); alphaConn.rollback(); goodStatement( betaConn, createSequence ); assertResults( betaConn, nextValueFor, nextValueForResults, true ); betaConn.rollback(); // now try creating and using the sequence inside the nested // transaction context of a database procedure goodStatement ( alphaConn, "create procedure createSequence( sequenceName varchar( 128 ) )\n" + "language java parameter style java modifies sql data\n" + "external name 'org.apache.derbyTesting.functionTests.tests.lang.SequenceTest.createSequence'\n" ); goodStatement( alphaConn, "grant execute on procedure createSequence to public" ); alphaConn.commit(); String runProcedure = "call alpha.createSequence( 'seq6554_2' )"; String postProcedureQuery= "values next value for seq6554_2"; String[][] postProcedureResults = new String[][] { { "-2147483647" }, }; goodStatement( alphaConn, runProcedure ); assertResults( alphaConn, postProcedureQuery, postProcedureResults, true ); alphaConn.rollback(); goodStatement( betaConn, runProcedure ); assertResults( betaConn, postProcedureQuery, postProcedureResults, true ); betaConn.rollback(); alphaConn.setAutoCommit( true ); betaConn.setAutoCommit( true ); } /** * Verify that sequence numbers pick up where they left off after eviction from * the sequence cache. */ public void test_17_6554_cacheEviction() throws Exception { Connection control = openUserConnection( TEST_DBO ); // set the size of the sequence generator cache to 5 entries. // bounce the database so that the value takes effect. goodStatement( control, "call syscs_util.syscs_set_database_property( 'derby.language.sequenceGeneratorCacheSize', '5' )" ); getTestConfiguration().shutdownDatabase(); Connection conn1 = openUserConnection( ALPHA ); Connection conn2 = openUserConnection( ALPHA ); goodStatement( conn1, "create sequence s000" ); assertResults ( conn1, "values next value for s000", new String[][] { { "-2147483648" }, }, true ); goodStatement( conn1, "create sequence s001" ); assertResults ( conn1, "values next value for s001", new String[][] { { "-2147483648" }, }, true ); assertResults ( conn1, "values next value for s001", new String[][] { { "-2147483647" }, }, true ); // now create enough sequences to evict the first two sequences from the cache goodStatement( conn2, "create sequence s002" ); goodStatement( conn2, "create sequence s003" ); goodStatement( conn2, "create sequence s004" ); goodStatement( conn2, "create sequence s005" ); goodStatement( conn2, "create sequence s006" ); goodStatement( conn2, "create sequence s007" ); goodStatement( conn2, "create sequence s008" ); goodStatement( conn2, "create sequence s009" ); goodStatement( conn2, "create sequence s010" ); // now we pick up where we left off assertResults ( conn1, "values next value for s000", new String[][] { { "-2147483647" }, }, true ); assertResults ( conn1, "values next value for s001", new String[][] { { "-2147483646" }, }, true ); // restore the original size of the sequence generator cache control = openUserConnection( TEST_DBO ); goodStatement( control, "call syscs_util.syscs_set_database_property( 'derby.language.sequenceGeneratorCacheSize', '1000' )" ); getTestConfiguration().shutdownDatabase(); } ////////////////////////////////////////////////////////////////////// // // SQL ROUTINES // ////////////////////////////////////////////////////////////////////// public static void createSequence( String sequenceName ) throws Exception { Connection conn = DriverManager.getConnection( "jdbc:default:connection" ); conn.prepareStatement( "create sequence " + sequenceName ).execute(); ResultSet rs = conn.prepareStatement( "values next value for " + sequenceName ).executeQuery(); rs.next(); assertEquals( -2147483648L, rs.getLong( 1 ) ); rs.close(); } }
{ "content_hash": "bd91d951155e8b7a9dc6bb2f38ae6e0a", "timestamp": "", "source": "github", "line_count": 795, "max_line_length": 155, "avg_line_length": 36.40754716981132, "alnum_prop": 0.5859936428966279, "repo_name": "trejkaz/derby", "id": "2de91c2f6ce16e6e96a43a59c1cddf7c1bb465f6", "size": "29822", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "java/testing/org/apache/derbyTesting/functionTests/tests/lang/SequenceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13737" }, { "name": "HTML", "bytes": "287079" }, { "name": "Java", "bytes": "42740679" }, { "name": "PLSQL", "bytes": "48958" }, { "name": "PLpgSQL", "bytes": "11719" }, { "name": "SQLPL", "bytes": "69828" }, { "name": "Shell", "bytes": "30682" }, { "name": "XSLT", "bytes": "15231" } ], "symlink_target": "" }
namespace TABS_UserControls.usercontrols { public partial class events_tabs { /// <summary> /// upTabs control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.UpdatePanel upTabs; /// <summary> /// repeatEvents control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater repeatEvents; /// <summary> /// LinkButton1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton LinkButton1; /// <summary> /// dropEventTypes control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList dropEventTypes; } }
{ "content_hash": "6de7ea4704b07b01b37194b9f378aa05", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 84, "avg_line_length": 33.46511627906977, "alnum_prop": 0.5427380125086866, "repo_name": "cmorrow/cmorrow.github.io", "id": "96f4c0c808bdb011add29206c3f1e3c2ca20054c", "size": "1843", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "portfolio/TABS/web/usercontrols/events_tabs.ascx.designer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1386316" }, { "name": "ActionScript", "bytes": "129752" }, { "name": "AngelScript", "bytes": "60232" }, { "name": "C#", "bytes": "771072" }, { "name": "CSS", "bytes": "835386" }, { "name": "HTML", "bytes": "4708093" }, { "name": "JavaScript", "bytes": "17373" }, { "name": "PHP", "bytes": "1391" }, { "name": "Ruby", "bytes": "8845" }, { "name": "Shell", "bytes": "139" }, { "name": "Smalltalk", "bytes": "40136" } ], "symlink_target": "" }
const path = require('path'); const rootPath = path.normalize(__dirname + '/..'); const env = process.env.NODE_ENV || 'development'; const config = { development: { root: rootPath, app: { name: '<%= slugify(appname) %>' }, port: process.env.PORT || 3000,<% if(options.database == 'mongodb'){ %> db: 'mongodb://localhost/<%= slugify(appname) %>-development'<% } %><% if(options.database == 'mysql'){ %> db: 'mysql://localhost/<%= slugify(appname) %>-development'<% } %><% if(options.database == 'postgresql'){ %> db: 'postgres://localhost/<%= slugify(appname) %>-development'<% } %><% if(options.database == 'sqlite'){ %> db: 'sqlite://localhost/<%= slugify(appname) %>-development', storage: rootPath + '/data/<%= slugify(appname) %>-development'<% } %><% if(options.database == 'rethinkdb'){ %> db: {db: '<%= slugify(appname) %>_development'}<% } %> }, test: { root: rootPath, app: { name: '<%= slugify(appname) %>' }, port: process.env.PORT || 3000,<% if(options.database == 'mongodb'){ %> db: 'mongodb://localhost/<%= slugify(appname) %>-test'<% } %><% if(options.database == 'mysql'){ %> db: 'mysql://localhost/<%= slugify(appname) %>-test'<% } %><% if(options.database == 'postgresql'){ %> db: 'postgres://localhost/<%= slugify(appname) %>-test'<% } %><% if(options.database == 'sqlite'){ %> db: 'sqlite://localhost/<%= slugify(appname) %>-test', storage: rootPath + '/data/<%= slugify(appname) %>-test'<% } %><% if(options.database == 'rethinkdb'){ %> db: {db: '<%= slugify(appname) %>_test'}<% } %> }, production: { root: rootPath, app: { name: '<%= slugify(appname) %>' }, port: process.env.PORT || 3000,<% if(options.database == 'mongodb'){ %> db: 'mongodb://localhost/<%= slugify(appname) %>-production'<% } %><% if(options.database == 'mysql'){ %> db: 'mysql://localhost/<%= slugify(appname) %>-production'<% } %><% if(options.database == 'sqlite'){ %> db: 'sqlite://localhost/<%= slugify(appname) %>-production', storage: rootPath + '/data/<%= slugify(appname) %>-production'<% } %><% if(options.database == 'postgresql'){ %> db: 'postgres://localhost/<%= slugify(appname) %>-production'<% } %><% if(options.database == 'rethinkdb'){ %> db: {db: '<%= slugify(appname) %>_production'}<% } %> } }; module.exports = config[env];
{ "content_hash": "80432256a5ef9278840189b45176321d", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 116, "avg_line_length": 48.816326530612244, "alnum_prop": 0.5681438127090301, "repo_name": "petecoop/generator-express", "id": "b044d3cb954d799feb2f6d737e7dc742751722aa", "size": "2392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/mvc/config/config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "110" }, { "name": "CoffeeScript", "bytes": "9290" }, { "name": "EJS", "bytes": "536" }, { "name": "Handlebars", "bytes": "490" }, { "name": "JavaScript", "bytes": "49884" }, { "name": "Less", "bytes": "111" }, { "name": "Marko", "bytes": "595" }, { "name": "Pug", "bytes": "473" }, { "name": "SCSS", "bytes": "111" }, { "name": "Stylus", "bytes": "97" } ], "symlink_target": "" }
import stripe # Set your secret key: remember to change this to your live secret key in production stripe.api_key = "sk_test_rgfft426e22w2mw2m2" stripe.Customer.create( source= "tok_1OgIlDSDDSFFaaKPesPD", plan=103, email="payinguser@example.com" )
{ "content_hash": "c8350c2dca8a00f8ec45f0cfebe11ea6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 84, "avg_line_length": 18.571428571428573, "alnum_prop": 0.7538461538461538, "repo_name": "coding4medicine/notes-and-commands", "id": "747cdd7d26833b37c1c198f51545cccaeb3985a3", "size": "283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Stripe/code.py", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "12830" }, { "name": "Nginx", "bytes": "1033" }, { "name": "PHP", "bytes": "26" }, { "name": "Python", "bytes": "283" }, { "name": "Ruby", "bytes": "196" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; using System.IO; #if UNITY_EDITOR using UnityEditor; #endif public class SteamVrSettings : MonoBehaviour { const string SettingsFilename = "default.vrsettings"; // manifest not present on windows (I don't think?) but doesn't need configuration for hmd-less mode to work it seems #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX const string ManifestFilename = "driver.vrdrivermanifest"; #else const string ManifestFilename = null; #endif const string NullDriver = "null"; // general settings const string RequireHmdKey = "requireHmd"; const string ForcedDriverKey = "forcedDriver"; const string ActivateMultipleDriversKey = "activateMultipleDrivers"; // driver manifest const string AlwaysActivateKey = "alwaysActivate"; // driver settings const string DriverEnableKey = "enable"; static string SettingsPath { get { return Path.Combine(GetSettingsFolder(null), SettingsFilename ); } } static string SettingsFolder { get { return GetSettingsFolder(null); } } static public string GetDriverSettingsPath(string DriverName) { return Path.Combine(GetSettingsFolder(DriverName), SettingsFilename); } static public string GetDriverManifestPath(string DriverName) { return Path.Combine(GetDriverFolder(DriverName), ManifestFilename); } static string GetDriverFolder(string DriverName) { if (string.IsNullOrEmpty(DriverName)) throw new System.Exception("GetDriverFolder expects a drivername"); var Parts = new List<string>(); Parts.Add(SteamRuntimeFolder); Parts.Add("drivers"); Parts.Add(DriverName); return PopX.IO.Path_Combine(Parts); } static string GetSettingsFolder(string DriverName) { var Parts = new List<string>(); Parts.Add(SteamRuntimeFolder); if (!string.IsNullOrEmpty(DriverName)) { Parts.Add("drivers"); Parts.Add(DriverName); } Parts.Add("resources"); Parts.Add("settings"); return PopX.IO.Path_Combine(Parts); } // todo, work this out from env vars etc #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX static string SteamRuntimeFolder { get { return Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Library/Application Support/Steam/steamapps/common/SteamVR/SteamVR.app/Contents/MacOS/runtime/"); } } #else const string SteamRuntimeFolder = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\SteamVR\\"; #endif #if UNITY_EDITOR [MenuItem("NewChromantics/SteamVR/Set RequireHmd False")] public static void Set_RequireHmd_False() { ChangeSettings(null, RequireHmdKey, false); } #endif #if UNITY_EDITOR [MenuItem("NewChromantics/SteamVR/Set RequireHmd True")] public static void Set_RequireHmd_True() { ChangeSettings(null, RequireHmdKey, true); } #endif #if UNITY_EDITOR [MenuItem("NewChromantics/SteamVR/Show " + SettingsFilename)] public static void ShowSettingsFile() { EditorUtility.RevealInFinder( SettingsPath ); } #endif #if UNITY_EDITOR [MenuItem("NewChromantics/SteamVR/Show " + NullDriver + " driver settings")] public static void ShowDriverSettingsFile() { EditorUtility.RevealInFinder( GetDriverFolder(NullDriver)); } #endif // returns if changed #if UNITY_EDITOR [MenuItem("NewChromantics/SteamVR/enable " + NullDriver +" driver")] #endif public static bool EnableNullDriver() { // gr: for OSX. March 7th 2018 // enable the driver and make it always activate // general settings dont NEED requireHmd nor forcedDriver, just activateMultipleDrivers var Changed = false; Changed |= ChangeSettings(NullDriver,DriverEnableKey,true); if ( ManifestFilename != null) Changed |= ChangeManifest(NullDriver, AlwaysActivateKey, true); Changed |= ChangeSettings(null, ActivateMultipleDriversKey, true); #if UNITY_EDITOR_OSX //|| UNITY_STANDALONE_OSX if (Changed) { EditorUtility.DisplayDialog("Settings may not yet apply", "After changing settings, the steamvr runtime may need to be restarted.\n\nClosing Unity and/or steamvr may not be enough.\n\nOpen activity monitor and kill the process called vrserver", "ok"); } #endif return Changed; } public static bool ChangeSettings(string DriverName, string Key, bool Value) { var Filename = GetDriverSettingsPath(DriverName); return ChangeFile(Filename, Key, Value,DriverName); } public static bool ChangeManifest(string DriverName, string Key, bool Value) { var Filename = GetDriverManifestPath(DriverName); return ChangeFile(Filename, Key, Value,DriverName); } public static bool ChangeFile(string Filename,string Key,bool Value,string DriverName) { if (string.IsNullOrEmpty(DriverName)) DriverName = "null"; try { var Contents = File.ReadAllText(Filename); var NewContents = Contents; PopX.Json.Replace(ref NewContents, Key, Value); if (NewContents == Contents) { Debug.Log("No changes made to " + DriverName + " settings (" + Key + "=" + Value + ")"); return false; } System.IO.File.WriteAllText(Filename, NewContents); Debug.Log("Updated " + DriverName + " settings."); return true; } catch (System.Exception e) { Debug.LogError("Error replacing " + Key + " in " + DriverName + " settings..."); Debug.LogException(e); throw; } } }
{ "content_hash": "88e1a3f60c5826efb278d2ce384f1cab", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 254, "avg_line_length": 29.38888888888889, "alnum_prop": 0.7425330812854443, "repo_name": "SoylentGraham/PopUnityCommon", "id": "5a08d51f9b5af4b98814e1c6a99a983626d3d645", "size": "5290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SteamvrSettings.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "321842" }, { "name": "HLSL", "bytes": "20116" }, { "name": "ShaderLab", "bytes": "38773" } ], "symlink_target": "" }
Argo allows you to easily decode loosely typed structures into strongly typed models. When paired with functional programming concepts, Argo becomes a beautiful way to decode JSON from network responses into your application models. The following guides will teach you how to use Argo and how powerful it can be. ## High Level Concepts ## - [Overarching ideology](Ideology.md) - [Functional concepts](Functional-Concepts.md) ## Basic Usage ## - [Decoding your first model](Basic-Usage.md) - [Relationships](Relationships.md) ## Advanced Usage ## - [Decoding root keys](Decode-Root-Keys.md) - [Decoding Enums](Decode-Enums.md) - Understanding the Decode operators // TODO - Interacting with the `JSON` enum // TODO - Writing your own custom parser // TODO - More complex parsers // TODO ## Common Gotchas - [`curry` limitations](Curry-Limitations.md) - [Compilation errors](Compilation-Errors.md)
{ "content_hash": "b7ebb73b64381d08b025780a71099e00", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 79, "avg_line_length": 31.17241379310345, "alnum_prop": 0.7588495575221239, "repo_name": "edwardaux/Ogra", "id": "1b0a16d2ab7426a0905cf1ef45c1a98256852568", "size": "923", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Carthage/Checkouts/Argo/Documentation/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "478" }, { "name": "Ruby", "bytes": "3542" }, { "name": "Swift", "bytes": "11831" } ], "symlink_target": "" }
#include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <engine.h> #ifdef HAVE_DLFCN_H #include <dlfcn.h> #ifndef RTLD_NOW #define RTLD_NOW 0 #endif #endif struct hc_engine { int references; char *name; char *id; void (*destroy)(ENGINE *); const RSA_METHOD *rsa; const DH_METHOD *dh; const RAND_METHOD *rand; }; ENGINE * ENGINE_new(void) { ENGINE *engine; engine = calloc(1, sizeof(*engine)); engine->references = 1; return engine; } int ENGINE_free(ENGINE *engine) { return ENGINE_finish(engine); } int ENGINE_finish(ENGINE *engine) { if (engine->references-- <= 0) abort(); if (engine->references > 0) return 1; if (engine->name) free(engine->name); if (engine->id) free(engine->id); if(engine->destroy) (*engine->destroy)(engine); memset(engine, 0, sizeof(engine)); engine->references = -1; free(engine); return 1; } int ENGINE_up_ref(ENGINE *engine) { if (engine->references < 0) abort(); engine->references++; return 1; } int ENGINE_set_id(ENGINE *engine, const char *id) { engine->id = strdup(id); return (engine->id == NULL) ? 0 : 1; } int ENGINE_set_name(ENGINE *engine, const char *name) { engine->name = strdup(name); return (engine->name == NULL) ? 0 : 1; } int ENGINE_set_RSA(ENGINE *engine, const RSA_METHOD *method) { engine->rsa = method; return 1; } int ENGINE_set_DH(ENGINE *engine, const DH_METHOD *method) { engine->dh = method; return 1; } int ENGINE_set_destroy_function(ENGINE *e, void (*destroy)(ENGINE *)) { e->destroy = destroy; return 1; } const char * ENGINE_get_id(const ENGINE *engine) { return engine->id; } const char * ENGINE_get_name(const ENGINE *engine) { return engine->name; } const RSA_METHOD * ENGINE_get_RSA(const ENGINE *engine) { return engine->rsa; } const DH_METHOD * ENGINE_get_DH(const ENGINE *engine) { return engine->dh; } const RAND_METHOD * ENGINE_get_RAND(const ENGINE *engine) { return engine->rand; } /* * */ #define SG_default_engine(type) \ static ENGINE *type##_engine; \ int \ ENGINE_set_default_##type(ENGINE *engine) \ { \ if (type##_engine) \ ENGINE_finish(type##_engine); \ type##_engine = engine; \ if (type##_engine) \ ENGINE_up_ref(type##_engine); \ return 1; \ } \ ENGINE * \ ENGINE_get_default_##type(void) \ { \ if (type##_engine) \ ENGINE_up_ref(type##_engine); \ return type##_engine; \ } SG_default_engine(RSA) SG_default_engine(DH) #undef SG_default_engine /* * */ static ENGINE **engines; static unsigned int num_engines; static int add_engine(ENGINE *engine) { ENGINE **d, *dup; dup = ENGINE_by_id(engine->id); if (dup) return 0; d = realloc(engines, (num_engines + 1) * sizeof(*engines)); if (d == NULL) return 1; engines = d; engines[num_engines++] = engine; return 1; } void ENGINE_load_builtin_engines(void) { ENGINE *engine; int ret; engine = ENGINE_new(); if (engine == NULL) return; ENGINE_set_id(engine, "builtin"); ENGINE_set_name(engine, "Heimdal crypto builtin (ltm) engine version " PACKAGE_VERSION); ENGINE_set_RSA(engine, RSA_ltm_method()); ENGINE_set_DH(engine, DH_ltm_method()); ret = add_engine(engine); if (ret != 1) ENGINE_finish(engine); /* * TFM */ engine = ENGINE_new(); if (engine == NULL) return; ENGINE_set_id(engine, "tfm"); ENGINE_set_name(engine, "Heimdal crypto tfm engine version " PACKAGE_VERSION); ENGINE_set_RSA(engine, RSA_tfm_method()); ENGINE_set_DH(engine, DH_tfm_method()); ret = add_engine(engine); if (ret != 1) ENGINE_finish(engine); /* * ltm */ engine = ENGINE_new(); if (engine == NULL) return; ENGINE_set_id(engine, "ltm"); ENGINE_set_name(engine, "Heimdal crypto ltm engine version " PACKAGE_VERSION); ENGINE_set_RSA(engine, RSA_ltm_method()); ENGINE_set_DH(engine, DH_ltm_method()); ret = add_engine(engine); if (ret != 1) ENGINE_finish(engine); /* * imath */ engine = ENGINE_new(); if (engine == NULL) return; ENGINE_set_id(engine, "imath"); ENGINE_set_name(engine, "Heimdal crypto imath engine version " PACKAGE_VERSION); ENGINE_set_RSA(engine, RSA_imath_method()); ENGINE_set_DH(engine, DH_imath_method()); ret = add_engine(engine); if (ret != 1) ENGINE_finish(engine); #ifdef HAVE_GMP /* * gmp */ engine = ENGINE_new(); if (engine == NULL) return; ENGINE_set_id(engine, "gmp"); ENGINE_set_name(engine, "Heimdal crypto gmp engine version " PACKAGE_VERSION); ENGINE_set_RSA(engine, RSA_gmp_method()); ret = add_engine(engine); if (ret != 1) ENGINE_finish(engine); #endif } ENGINE * ENGINE_by_dso(const char *path, const char *id) { #ifdef HAVE_DLOPEN ENGINE *engine; void *handle; int ret; engine = calloc(1, sizeof(*engine)); if (engine == NULL) return NULL; handle = dlopen(path, RTLD_NOW); if (handle == NULL) { /* printf("error: %s\n", dlerror()); */ free(engine); return NULL; } { unsigned long version; openssl_v_check v_check; v_check = (openssl_v_check)dlsym(handle, "v_check"); if (v_check == NULL) { dlclose(handle); free(engine); return NULL; } version = (*v_check)(OPENSSL_DYNAMIC_VERSION); if (version == 0) { dlclose(handle); free(engine); return NULL; } } { openssl_bind_engine bind_engine; bind_engine = (openssl_bind_engine)dlsym(handle, "bind_engine"); if (bind_engine == NULL) { dlclose(handle); free(engine); return NULL; } ret = (*bind_engine)(engine, id, NULL); /* XXX fix third arg */ if (ret != 1) { dlclose(handle); free(engine); return NULL; } } ENGINE_up_ref(engine); ret = add_engine(engine); if (ret != 1) { dlclose(handle); ENGINE_finish(engine); return NULL; } return engine; #else return NULL; #endif } ENGINE * ENGINE_by_id(const char *id) { int i; for (i = 0; i < num_engines; i++) { if (strcmp(id, engines[i]->id) == 0) { ENGINE_up_ref(engines[i]); return engines[i]; } } return NULL; } void ENGINE_add_conf_module(void) { }
{ "content_hash": "22fde90eb6184a6042c02517c0b7a932", "timestamp": "", "source": "github", "line_count": 378, "max_line_length": 70, "avg_line_length": 16.944444444444443, "alnum_prop": 0.5981264637002341, "repo_name": "ystk/debian-heimdal", "id": "de1901c4df2f787114e0b6d675449ae1f319661f", "size": "8042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/hcrypto/engine.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "475" }, { "name": "Awk", "bytes": "875" }, { "name": "C", "bytes": "13860605" }, { "name": "C++", "bytes": "11082" }, { "name": "Clarion", "bytes": "735" }, { "name": "Emacs Lisp", "bytes": "1456" }, { "name": "Groff", "bytes": "557802" }, { "name": "HTML", "bytes": "467" }, { "name": "Java", "bytes": "3461" }, { "name": "Lex", "bytes": "18067" }, { "name": "Makefile", "bytes": "13984" }, { "name": "Perl", "bytes": "35244" }, { "name": "Python", "bytes": "45036" }, { "name": "Shell", "bytes": "283959" }, { "name": "TeX", "bytes": "461956" }, { "name": "Yacc", "bytes": "75333" } ], "symlink_target": "" }
import { expect } from 'chai'; import value from '../../src/rules/value'; describe('value()', () => { const sampleString = 'Hello World'; const sampleArray = ['hello', 'world']; const sampleNumber = 1980; it('Up & Running', () => { expect(typeof value).to.equal('function'); }); it('accept a {string} sample', () => { expect(value(sampleString, 'Hello World')).to.equal(true); }); it('refuses a {string} sample', () => { expect(value(sampleString, 'hello world')).to.equal(false); }); it('accept a {number} sample', () => { expect(value(sampleNumber, 1980)).to.equal(true); }); it('refuses a {number} sample', () => { expect(value(sampleNumber, '1980')).to.equal(false); expect(value(sampleNumber, 1981)).to.equal(false); }); it('accept a {array} sample', () => { expect(value(sampleArray, ['hello', 'world'])).to.equal(true); }); it('refuses a {array} sample', () => { expect(value(sampleArray, ['hello', 'World'])).to.equal(false); expect(value(sampleArray, ['hello'])).to.equal(false); }); });
{ "content_hash": "9dc63fe3d72a95a4c9e3a7ce70fb7a73", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 67, "avg_line_length": 28.289473684210527, "alnum_prop": 0.5916279069767442, "repo_name": "mediasmart/bobby", "id": "478c59481875b3976e0ed2ad96c8543b250c8757", "size": "1075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/rules/value.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18366" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <link rel="icon" href="/favicon.ico"> <title>PCFS Node.js Demo</title> <!-- Bootstrap core CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles --> <link href="css/demo.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- do this here so the page only loads after ajax call --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" integrity="sha384-THPy051/pYDQGanwU6poAc/hOdQxjnOEXzbT+OuUAFqNqFjL+4IGLBgCJC3ZOShY" crossorigin="anonymous"></script> <script> var globalInstance = {}; // get info synchronously for Vue $.ajax({ url: '/info', type: 'get', dataType: 'json', async: false, success: function(data) { globalInstance = data; } }); </script> </head> <body> <!-- Vue templates--> <template id="instances-template"> <div class="row expander" id="instances"> <instance-component v-for="(instance, index) in instances" :instance="instance" :index="index"> </instance-component> </div> </template> <template id="instance-template"> <div class="col-md-4 col-sm-6 col-xs-12 text-center"> <img v-if="redis" :src="'holder.js/100px280?text=' + index + '&bg=' + colour"> <img v-else :src="'holder.js/100px280?fg=' + colour + '&bg=' + colour"> <p v-if="thisInstance" class="line-50"> <a :href="'/killme?index=' + index">kill me</a> </p> <p v-else class="line-50">id: {{ instance }}</p> </div> </template> <!-- End Vue templates--> <!-- navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <span class="navbar-brand">Pivotal Cloud Foundry Services</span> </div> </div> </nav> <!-- content --> <div class="container expander" id="app"> <h1>{{ applicationName }} <small>app id: {{ applicationId }}</small> </h1> <p v-if="redis" class="lead"> Redis is <strong>enabled</strong>. There are <strong>{{ instances.length }}</strong> instances behind this app, the one you are viewing is <strong :style="'color: #' + colour">highlighted</strong>. </p> <p v-else class="lead"> Redis is <strong>disabled</strong>. </p> <instances-component :instances="instances"></instances-component> <!-- footer --> <div class="row footer line-50"> <div class="col-xs-12 col-sm-6 text-left"> <p class="text-muted">instance id: {{ instanceId }}</p> </div> <div class="col-xs-12 col-sm-6 text-right"> <p class="text-muted">&copy; PCFS 2017</p> </div> </div> </div> <!-- /app --> <!-- yavascripts--> <script src="/js/vendor/vue.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js" integrity="sha384-BLiI7JTZm+JWlgKa0M0kGRpJbF2J8q+qreVrKBC47e3K6BW78kGLrCkeRX6I9RoK" crossorigin="anonymous"></script> <script src="/js/vendor/holder.min.js"></script> <script> //instances component Vue.component('instances-component', { template: '#instances-template', props: ['instances'] }); //instance component Vue.component('instance-component', { template: '#instance-template', props: ['instance', 'index'], computed: { // compare this instance (which is an id) with global instanceId // and set theme to 'lava' if they match colour: function() { return this.instance === globalInstance.instanceId ? globalInstance.colour : 'f8f8f8'; }, thisInstance: function() { return this.instance === globalInstance.instanceId; }, redis: function() { return globalInstance.redis; } } }); new Vue({ el: '#app', data: globalInstance }); </script> </body> </html>
{ "content_hash": "3f4caa29ab0c84d937a13bab34217af5", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 209, "avg_line_length": 34.75555555555555, "alnum_prop": 0.5918584825234442, "repo_name": "sturadnidge/cf-demo-node", "id": "e0b5338beec585c4b464dbc5d5e63072a6bdf167", "size": "4692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "525" }, { "name": "HTML", "bytes": "4692" }, { "name": "JavaScript", "bytes": "10634" } ], "symlink_target": "" }
package metrics import ( "fmt" "github.com/blang/semver" "github.com/prometheus/client_golang/prometheus" "sync" ) // KubeOpts is superset struct for prometheus.Opts. The prometheus Opts structure // is purposefully not embedded here because that would change struct initialization // in the manner which people are currently accustomed. // // Name must be set to a non-empty string. DeprecatedVersion is defined only // if the metric for which this options applies is, in fact, deprecated. type KubeOpts struct { Namespace string Subsystem string Name string Help string ConstLabels prometheus.Labels DeprecatedVersion *semver.Version deprecateOnce sync.Once annotateOnce sync.Once StabilityLevel StabilityLevel } // StabilityLevel represents the API guarantees for a given defined metric. type StabilityLevel string const ( // ALPHA metrics have no stability guarantees, as such, labels may // be arbitrarily added/removed and the metric may be deleted at any time. ALPHA StabilityLevel = "ALPHA" // STABLE metrics are guaranteed not be mutated and removal is governed by // the deprecation policy outlined in by the control plane metrics stability KEP. STABLE StabilityLevel = "STABLE" ) // CounterOpts is an alias for Opts. See there for doc comments. type CounterOpts KubeOpts // Modify help description on the metric description. func (o *CounterOpts) markDeprecated() { o.deprecateOnce.Do(func() { o.Help = fmt.Sprintf("(Deprecated since %v) %v", o.DeprecatedVersion, o.Help) }) } // annotateStabilityLevel annotates help description on the metric description with the stability level // of the metric func (o *CounterOpts) annotateStabilityLevel() { o.annotateOnce.Do(func() { o.Help = fmt.Sprintf("[%v] %v", o.StabilityLevel, o.Help) }) } // convenience function to allow easy transformation to the prometheus // counterpart. This will do more once we have a proper label abstraction func (o *CounterOpts) toPromCounterOpts() prometheus.CounterOpts { return prometheus.CounterOpts{ Namespace: o.Namespace, Subsystem: o.Subsystem, Name: o.Name, Help: o.Help, ConstLabels: o.ConstLabels, } }
{ "content_hash": "e5ec818d4a49772bc8eade9bc2408197", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 103, "avg_line_length": 31.8, "alnum_prop": 0.7398921832884097, "repo_name": "enisoc/kubernetes", "id": "1409f241020b339ee0a855fcb6005b26f652c20b", "size": "2795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "staging/src/k8s.io/component-base/metrics/opts.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2840" }, { "name": "Dockerfile", "bytes": "61390" }, { "name": "Go", "bytes": "46076482" }, { "name": "HTML", "bytes": "38" }, { "name": "Lua", "bytes": "17200" }, { "name": "Makefile", "bytes": "76592" }, { "name": "PowerShell", "bytes": "97180" }, { "name": "Python", "bytes": "3176190" }, { "name": "Ruby", "bytes": "430" }, { "name": "Shell", "bytes": "1561537" }, { "name": "sed", "bytes": "11992" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: dclauson * Date: 11/23/2015 * Time: 1:24 PM */ namespace Elytus\LimoncelloBundle\DependencyInjection\Compiler; use Elytus\LimoncelloBundle\EventListener\ControllerListener; use Elytus\LimoncelloBundle\Integration\SymfonyIntegration; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class RegisterEventListenersPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $container->setParameter('json_api.controller_listener.class', ControllerListener::class); $container->setParameter('json_api.symfony_integration.class', SymfonyIntegration::class); $container->register('json_api.symfony_integration', '%json_api.symfony_integration.class%') ->addMethodCall('setContainer', array(new Reference('service_container'))); $container->register('json_api.controller_listener', '%json_api.controller_listener.class%') ->addMethodCall('setContainer', array(new Reference('service_container'))) ->addTag('kernel.event_listener', ['event' => 'kernel.controller', 'method' => 'onKernelController']); } }
{ "content_hash": "fd9805bd5505e8c6413f5d9a1fc4262a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 114, "avg_line_length": 43.266666666666666, "alnum_prop": 0.75115562403698, "repo_name": "drewclauson/elytus-limoncello-bundle", "id": "bd790bba5a8614276964dca252cf99e940e9f5f5", "size": "1298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DependencyInjection/Compiler/RegisterEventListenersPass.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "9999" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="exposed-instrumentation-api-publish-0.5"> <CLASSES> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support.test/exposed-instrumentation-api-publish/0.5/res" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support.test/exposed-instrumentation-api-publish/0.5/jars/classes.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$PROJECT_DIR$/../../Android/sdk/extras/android/m2repository/com/android/support/test/exposed-instrumentation-api-publish/0.5/exposed-instrumentation-api-publish-0.5-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "1172f3e4fba368db8272b105024bdb7b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 205, "avg_line_length": 58.833333333333336, "alnum_prop": 0.7181303116147308, "repo_name": "Plot-ka/coolweather", "id": "033dc93a652c829c452e7d14cb192b3d80cce579", "size": "706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/exposed_instrumentation_api_publish_0_5.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "31616" } ], "symlink_target": "" }
using Nancy; using Nancy.TinyIoc; namespace Okanshi.Dashboard { public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register<IConfiguration>(Config.Instance); } } }
{ "content_hash": "6b6de9e9477ef333456555615f041b53", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 83, "avg_line_length": 23.214285714285715, "alnum_prop": 0.803076923076923, "repo_name": "mvno/Okanshi.Dashboard", "id": "2167dc7076b128f73423c1a7bfef06e8712cb616", "size": "327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Okanshi.Dashboard/Bootstrapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "293" }, { "name": "C#", "bytes": "20377" }, { "name": "CSS", "bytes": "878" }, { "name": "F#", "bytes": "11737" }, { "name": "HTML", "bytes": "4212" }, { "name": "JavaScript", "bytes": "15537" }, { "name": "Shell", "bytes": "612" } ], "symlink_target": "" }
import React, { Component, PropTypes } from "react" import Page from "../Page" class Post extends Component { // it's up to you to choose what to do with this layout ;) render() { const { props } = this const { head } = props const pageDate = head.date ? new Date(head.date) : null return ( <Page { ...props } header={ <header> { pageDate && <time key={ pageDate.toISOString() }> { pageDate.toDateString() } </time> } </header> } /> ) } } Post.propTypes = { head: PropTypes.object.isRequired } export default Post
{ "content_hash": "39a103bc03c0456daa9ed87d5c5c6f62", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 60, "avg_line_length": 18.27027027027027, "alnum_prop": 0.5103550295857988, "repo_name": "anthonydugois/polynomic", "id": "ccd0bed4ef2063b2eaa1a5a5e03c30e93c852721", "size": "676", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/web_modules/layouts/Post/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10550" }, { "name": "JavaScript", "bytes": "88799" } ], "symlink_target": "" }
.border-left { border-left: solid 1px; }
{ "content_hash": "b41113de4a092574d7439de49b35b653", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 25, "avg_line_length": 14.333333333333334, "alnum_prop": 0.6511627906976745, "repo_name": "lander854/firebase-crud", "id": "e23cd0ee5ccbb7eb8b1339fd3872bbab25a926ab", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/app.component.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3644" }, { "name": "HTML", "bytes": "3938" }, { "name": "JavaScript", "bytes": "1884" }, { "name": "TypeScript", "bytes": "14128" } ], "symlink_target": "" }
<?php namespace Application; use Zend\Mvc\ModuleRouteListener; use Zend\Mvc\MvcEvent; class Module { public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); // Set up locale from "HTTP_ACCEPT_LANGUAGE" $language = $e->getApplication()->getRequest()->getServer('HTTP_ACCEPT_LANGUAGE'); $e->getApplication()->getServiceManager()->get('translator') ->setLocale(\Locale::acceptFromHttp($language)); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
{ "content_hash": "7dbb8d60704e1285d644190aa9120921", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 90, "avg_line_length": 26.763157894736842, "alnum_prop": 0.576204523107178, "repo_name": "mrjingles/zendframework2", "id": "92b43f2725326ba74b7dec3e00c6dccb01fc04d6", "size": "1339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/Application/Module.php", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Field awe_cursor_type.AWE_CUR_WEST_PANNING</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js">/**/</script> <script type="text/javascript" src="../../prettify/prettify.js">/**/</script> <script type="text/javascript" src="../../scripts/ddox.js">/**/</script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class=" module">animation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/component.html" class=" module">component</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class=" tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/awesomium.html" class="selected module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class=" module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/resources.html" class=" module">resources</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/tasks.html" class=" module">tasks</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); //]]> </script> </div> </nav> <div id="main-contents"> <h1>Field awe_cursor_type.AWE_CUR_WEST_PANNING</h1><!-- using block body in layout.dt--><!-- using block ddox.description in ddox.layout.dt--> <p></p> <section> <h2>Declaration</h2> <pre class="code prettyprint lang-d prototype"> enum <a href="../../utility/awesomium/awe_cursor_type.html">awe_cursor_type</a> { // ... AWE_CUR_WEST_PANNING, // ... }</pre> </section><!-- using block ddox.sections in ddox.layout.dt--> <!-- Default block ddox.members in ddox.layout.dt--> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt--> </section> <section> <h2>License</h2><!-- using block ddox.license in ddox.layout.dt--> </section> </div> </body> </html>
{ "content_hash": "fb968e4a322ff87e1b9430ab32a8b524", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 197, "avg_line_length": 34.17467248908297, "alnum_prop": 0.5313059033989267, "repo_name": "Circular-Studios/Dash-Docs", "id": "5fa1b21fd1dbed7dda0328d1c906049f2dd6ab83", "size": "7826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/v0.9.0/utility/awesomium/awe_cursor_type.AWE_CUR_WEST_PANNING.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "146638" }, { "name": "HTML", "bytes": "212463985" }, { "name": "JavaScript", "bytes": "72098" } ], "symlink_target": "" }
static int statusG = 0; typedef struct put_object_callback_data { FILE *infile; uint64_t contentLength, originalContentLength; } put_object_callback_data; static void responseCompleteCallback( S3Status status, const S3ErrorDetails *error, void *callbackData ) { int i; statusG = status; if ( error && error->message ) { printf( " Message: %s\n", error->message ); } if ( error && error->resource ) { printf( " Resource: %s\n", error->resource ); } if ( error && error->furtherDetails ) { printf( " Further Details: %s\n", error->furtherDetails ); } if ( error && error->extraDetailsCount ) { printf( "%s", " Extra Details:\n" ); for ( i = 0; i < error->extraDetailsCount; i++ ) { printf( " %s: %s\n", error->extraDetails[i].name, error->extraDetails[i].value ); } } } static S3Status responsePropertiesCallback( const S3ResponseProperties *properties, void *callbackData ) { return S3StatusOK; } static int putObjectDataCallback( int bufferSize, char *buffer, void *callbackData ) { put_object_callback_data *data = ( put_object_callback_data * ) callbackData; int length; int ret = 0; if ( data->contentLength ) { int length = ( ( data->contentLength > ( unsigned ) bufferSize ) ? ( unsigned ) bufferSize : data->contentLength ); ret = fread( buffer, 1, length, data->infile ); } data->contentLength -= ret; return ret; } int putFileIntoS3( char *fileName, char *s3ObjName ) { S3Status status; char *key; struct stat statBuf; uint64_t fileSize; FILE *fd; char *accessKeyId; char *secretAccessKey; put_object_callback_data data; accessKeyId = getenv( "S3_ACCESS_KEY_ID" ); if ( accessKeyId == NULL ) { printf( "S3_ACCESS_KEY_ID environment variable is undefined" ); return( -1 ); } secretAccessKey = getenv( "S3_SECRET_ACCESS_KEY" ); if ( secretAccessKey == NULL ) { printf( "S3_SECRET_ACCESS_KEY environment variable is undefined" ); return( -1 ); } key = ( char * ) strchr( s3ObjName, '/' ); if ( key == NULL ) { printf( "S3 Key for the Object Not defined\n" ); return( -1 ); } *key = '\0'; key++; if ( stat( fileName, &statBuf ) == -1 ) { printf( "Unknown input file" ); return( -1 ); } fileSize = statBuf.st_size; fd = fopen( fileName, "r" ); if ( fd == NULL ) { printf( "Unable to open input file" ); return( -1 ); } data.infile = fd; S3BucketContext bucketContext = {s3ObjName, 1, 0, accessKeyId, secretAccessKey}; S3PutObjectHandler putObjectHandler = { { &responsePropertiesCallback, &responseCompleteCallback }, &putObjectDataCallback }; if ( ( status = S3_initialize( "s3", S3_INIT_ALL ) ) != S3StatusOK ) { printf( "Failed to initialize libs3: %s\n", S3_get_status_name( status ) ); return( -1 ); } S3_put_object( &bucketContext, key, fileSize, NULL, 0, &putObjectHandler, &data ); if ( statusG != S3StatusOK ) { printf( "Put failed: %i\n", statusG ); S3_deinitialize(); return( -1 ); } S3_deinitialize(); fclose( fd ); return( 0 ); } int main( int argc, char **argv ) { int i; if ( argc != 3 ) { printf( "usage: %s fileName s3Objname\n", argv[0] ); exit( -1 ); } i = putFileIntoS3( argv[1], argv[2] ) ; exit( i ); }
{ "content_hash": "5d2fdd112ad0473a30224278a813e209", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 83, "avg_line_length": 27.057553956834532, "alnum_prop": 0.5469290082424887, "repo_name": "leesab/irods", "id": "02bc7e64501a668fd83556edd292eb1265f6da67", "size": "3986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iRODS/server/test/s3/irodss3/src/puts3.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "8928714" }, { "name": "FORTRAN", "bytes": "6804" }, { "name": "Perl", "bytes": "616072" }, { "name": "Prolog", "bytes": "15035" }, { "name": "Puppet", "bytes": "21402" }, { "name": "Python", "bytes": "420547" }, { "name": "R", "bytes": "8001" }, { "name": "Rebol", "bytes": "176871" }, { "name": "Ruby", "bytes": "5890" }, { "name": "SQL", "bytes": "69248" }, { "name": "Shell", "bytes": "186575" } ], "symlink_target": "" }
package pl.edu.agh.planner.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.edu.agh.planner.dao.ClassroomHourDao; import pl.edu.agh.planner.domain.ClassroomHourEntity; import java.util.List; @Service("classroomHourService") public class ClassroomHourService implements ServiceInterface<ClassroomHourEntity, Long> { private ClassroomHourDao classroomHourDao; @Autowired public void setClassroomHourDao(ClassroomHourDao classroomHourDao) { this.classroomHourDao = classroomHourDao; } @Override public void add(ClassroomHourEntity classroomHourEntity) { classroomHourDao.add(classroomHourEntity); } @Override public void add(List<ClassroomHourEntity> classroomHourEntities) { classroomHourDao.add(classroomHourEntities); } @Override public void update(ClassroomHourEntity classroomHourEntity) { classroomHourDao.update(classroomHourEntity); } @Override public void delete(ClassroomHourEntity classroomHourEntity) { classroomHourDao.delete(classroomHourEntity); } @Override public ClassroomHourEntity getById(Long id) { return classroomHourDao.getById(id); } @Override public List<ClassroomHourEntity> getList() { return classroomHourDao.getList(); } @Override public ClassroomHourEntity saveOrUpdate(ClassroomHourEntity entity) { return classroomHourDao.saveOrUpdate(entity); } }
{ "content_hash": "b25e26966c1bf0e7e433c17ad5b1092f", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 90, "avg_line_length": 27.87272727272727, "alnum_prop": 0.7495107632093934, "repo_name": "Blondas/planner2", "id": "3c12a2cea17aa6117325609badceff54219d6907", "size": "1533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AghPlanner/src/main/java/pl/edu/agh/planner/service/ClassroomHourService.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "20260" }, { "name": "HTML", "bytes": "5731" }, { "name": "Java", "bytes": "224213" }, { "name": "JavaScript", "bytes": "395678" } ], "symlink_target": "" }
// ----------------------------------------------------------------------- // <copyright file="EventResponsibleUser.cs" company="Nodine Legal, LLC"> // Licensed to Nodine Legal, LLC under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Nodine Legal, LLC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </copyright> // ----------------------------------------------------------------------- namespace OpenLawOffice.Common.Models.Events { using System; /// <summary> /// Relates a user to an event /// </summary> public class EventResponsibleUser : Core { public Guid? Id { get; set; } public Event Event { get; set; } public Account.Users User { get; set; } public string Responsibility { get; set; } } }
{ "content_hash": "54c3d0b4b68cf4dae4a212d243200d3f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 75, "avg_line_length": 36.17948717948718, "alnum_prop": 0.6272147413182141, "repo_name": "NodineLegal/OpenLawOffice", "id": "44de33e9451f8ce05905d481e553f682c350bba5", "size": "1413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OpenLawOffice.Common/Models/Events/EventResponsibleUser.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "872408" }, { "name": "C#", "bytes": "2202604" }, { "name": "CSS", "bytes": "47639" }, { "name": "HTML", "bytes": "213" }, { "name": "JavaScript", "bytes": "1712413" } ], "symlink_target": "" }
import { assert } from 'chai'; import { createParser } from '~test/test-utils'; import { Expression } from '~/syntax'; describe('Expression', () => { const parse = createParser(Expression); it('should parse an array access as an expression', () => { assert.isDefined(parse('a[1]')); }); it('should parse an array literal as an expression', () => { assert.isDefined(parse('[]')); }); it('should parse a binary expression as an expression', () => { assert.isDefined(parse('1+1')); }); it('should parse a bool literal as an expression', () => { assert.isDefined(parse('true')); }); it('should parse a char literal as an expression', () => { assert.isDefined(parse("'a'")); }); it('should parse a field access as an expression', () => { assert.isDefined(parse('a.b')); }); it('should parse a float literal as an expression', () => { assert.isDefined(parse('1.5')); }); it('should parse a function application as an expression', () => { assert.isDefined(parse('a()')); }); it('should parse an identifier as an expression', () => { assert.isDefined(parse('a')); }); it('should parse an if-else as an expression', () => { assert.isDefined(parse('if (1) 2 else 3')); }); it('should parse an integer literal as an expression', () => { assert.isDefined(parse('1')); }); it('should parse a lambda as an expression', () => { assert.isDefined(parse('()=>1')); }); it('should parse a parenthesized expression as an expression', () => { assert.isDefined(parse('(1)')); }); it('should parse a string literal as an expression', () => { assert.isDefined(parse('""')); }); it('should parse a struct literal as an expression', () => { assert.isDefined(parse('{}')); }); it('should parse a tuple literal as an expression', () => { assert.isDefined(parse('()')); }); it('should parse a unary expression as an expression', () => { assert.isDefined(parse('+1')); }); it('should parse a var declaration as an expression', () => { assert.isDefined(parse('a=1')); }); });
{ "content_hash": "38aefced8939b4f169640dce93f76325", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 74, "avg_line_length": 35.015625, "alnum_prop": 0.5618027666220438, "repo_name": "jchitel/renlang", "id": "10fc2516281df0e67a4dcfc4d61b7ef8054bb320", "size": "2241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/syntax/expressions/Expression.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2097" }, { "name": "TypeScript", "bytes": "519471" } ], "symlink_target": "" }
import os, sys # init_params # make_params_from_default # make_params_from_yaml # make_params_from_options # check_params # # make_analyses # # make_file_layout # init_paths # # read_matrices # read_matrices_all # strip_affx_control_probes # log_matrices # quantile_normalize_matrices # dwd_normalize_matrices # shiftscale_normalize_matrices # _shiftscale_normalize_standard # _shiftscale_normalize_normref # # write_dataset # write_files_for_binreg # run_analysis # _run_binreg_standard # _run_binreg_normref # # summarize_model # summarize_parameters # summarize_probabilities # summarize_signature_dataset # summarize_signature_heatmap # summarize_dataset_heatmap # summarize_predictions # summarize_report # summarize_all_report # _make_signature_figure # _make_prediction_figure # _make_footer # # pretty_runtime # pretty_hostname MAX_ANALYSES = 128 # Maximum number of analyses to do at a time. class Analysis: def __init__(self, params, subpath): self.params = params # subpath should be None if this analysis should be in the # root directory. self.subpath = subpath class PyBinregParams: # Holds parameters for Binreg and other parameters for this # script. # # binreg_version For Binreg. # genes List of ints, used by Binreg one at a time. # metagenes List of ints, used by Binreg one at a time. # # train0_file # train1_file # test_file # # log_train0 # log_train1 # log_test # log_normref # strip_affx Handled by this script. # quantile Handled by this script. # shift_scale Handled by this script. # dwd Handled by this script. # dwd_bild Handled by this script. # normref_file Handled by this script. # # burnin For Binreg. # samples For Binreg. # skips For Binreg. # credible_interval For Binreg. # # cross_validate For Binreg. # noplots Converted to make_plots for Binreg. # label_samples Handled by this script. # draw_error_bars Handled by this script. # archive Handled by this script. def __init__( self, binreg_version=None, genes=None, metagenes=None, train0_file=None, train1_file=None, test_file=None, normref_file=None, strip_affx=None, log_train0=None, log_train1=None, log_test=None, log_normref=None, quantile=None, shiftscale=None, dwd=None, dwd_bild=None, burnin=None, samples=None, skips=None, credible_interval=None, cross_validate=None, noplots=None, label_samples=None, draw_error_bars=None, archive=None, ): self.binreg_version = binreg_version self.genes = genes self.metagenes = metagenes self.train0_file = train0_file self.train1_file = train1_file self.test_file = test_file self.normref_file = normref_file self.strip_affx = strip_affx self.log_train0 = log_train0 self.log_train1 = log_train1 self.log_test = log_test self.log_normref = log_normref self.quantile = quantile self.shiftscale = shiftscale self.dwd = dwd self.dwd_bild = dwd_bild self.burnin = burnin self.samples = samples self.skips = skips self.credible_interval = credible_interval self.cross_validate = cross_validate self.noplots = noplots self.label_samples = label_samples self.draw_error_bars = draw_error_bars self.archive = archive def init_params(): # Initialize the parameters. from optparse import OptionParser, OptionGroup # Initialize the default parameters. Needed for some of the # options. default_params = make_params_from_default() usage = "usage: %prog [options] train0_file train1_file [test_file]" parser = OptionParser(usage=usage, version="%prog 02") parser.add_option( "-v", "--binreg_version", dest="binreg_version", type="int", default=None, help="Use binreg version 1 or 2 (default %d)." % default_params.binreg_version) parser.add_option( "", "--python", dest="python", default=None, help="Specify the command to run python (optional).") parser.add_option( "", "--matlab", dest="matlab", default="matlab", help="Specify the command to run matlab.") parser.add_option( "", "--povray", dest="povray", default="povray", help="Specify the command to run povray.") parser.add_option( "", "--cluster", dest="cluster", default=None, help="Specify the command to run cluster.") parser.add_option( "", "--dwd_path", dest="dwd_path", default=None, help="Specify the path of BatchAdjust.") parser.add_option( "", "--binreg", dest="binreg_path", default=None, help="Specify the path to the BinReg2.0 code.") parser.add_option( "", "--arrayplot", dest="arrayplot", default=None, help="Specify the command to run arrayplot.") parser.add_option( "", "--libpath", dest="libpath", action="append", default=[], help="Add to the Python library search path.") parser.add_option( "-o", "--outpath", dest="outpath", type="string", default=None, help="Save files in this path.") parser.add_option( "-z", "", dest="archive", action="store_true", default=None, help="Archive the raw output. Helpful for GenePattern.") #parser.add_option( # "-j", "", dest="num_procs", type="int", default=1, # help="Number of jobs to run in parallel.") parser.add_option( "", "--yaml", dest="yaml", default=None, help="Configure the analysis from a YAML-formatted file. " "Command line parameters takes precedence over the ones from " "the file.") group = OptionGroup(parser, "Plotting") group.add_option( "", "--noplots", dest="noplots", action="store_true", default=None, help="Do not make any plots.") group.add_option( "", "--label_samples", dest="label_samples", type="choice", choices=["yes", "no", "auto"], default="auto", help="Label the samples in the scatter plot. " "Must be 'yes', 'no', or 'auto' (default).") group.add_option( "", "--draw_error_bars", dest="draw_error_bars", type="choice", choices=["yes", "no", "auto"], default="auto", help="Draw the error bars in the scatter plot. " "Must be 'yes', 'no', or 'auto' (default).") group.add_option( "", "--credible_interval", dest="credible_interval", type="int", default=None, help="Credible interval (default %d)." % default_params.credible_interval) parser.add_option_group(group) group = OptionGroup(parser, "Signature") group.add_option( "-g", "--genes", dest="genes", default=str(default_params.genes), help="Number of genes to use (default %s)." % default_params.genes) group.add_option( "-m", "--metagenes", dest="metagenes", default=str(default_params.metagenes), help="Number of metagenes to use (default %s)." % default_params.metagenes) parser.add_option_group(group) group = OptionGroup(parser, "Normalization") group.add_option( "", "--strip_affx", dest="strip_affx", action="store_true", default=None, help="Strip the AFFX control probes.") group.add_option( "-l", "--log_the_data", dest="log_the_data", type="choice", choices=["yes", "no", "auto"], default="auto", help="Log the data before analyzing. " "Must be 'yes', 'no', or 'auto' (default).") group.add_option( "-q", "--quantile", dest="quantile", action="store_true", default=None, help="Quantile normalize the data.") group.add_option( "-d", "--dwd", dest="dwd", action="store_true", default=None, help="DWD normalize the data.") group.add_option( "", "--dwd_bild", dest="dwd_bild", action="store_true", default=None, help="DWD normalize the data, using the Bild method.") group.add_option( "-s", "--shiftscale", dest="shiftscale", action="store_true", default=None, help="Shift-scale normalize the data.") group.add_option( "--normalization_reference_file", dest="normref_file", type="string", default=None, help="Use this file to help normalize the test file.") parser.add_option_group(group) group = OptionGroup(parser, "MCMC Internals") group.add_option( "", "--burnin", dest="burnin", type="int", default=None, help="Number of burn-in samples (default %d)." % default_params.burnin) group.add_option( "", "--samples", dest="samples", type="int", default=None, help="Number of samples (default %d)." % default_params.samples) group.add_option( "", "--skips", dest="skips", type="int", default=None, help="Number of skips (default %d)." % default_params.skips) parser.add_option_group(group) # Parse the arguments. options, args = parser.parse_args() if options.libpath: sys.path = options.libpath + sys.path # Import after the library path is set. from genomicode import genepattern genepattern.fix_environ_path() yaml_params = None if options.yaml: yaml_params = make_params_from_yaml(options.yaml, args) # HACK: If YAML, then args will only consist of the test_file. # The train0_file and train1_file will be provided in the YAML # file. However, the options parameters might depend on # these. If this is the case, then add the train0_file and # train1_file to args. assert yaml_params.train0_file and yaml_params.train_file and \ yaml_params.test_file x = yaml_params.train0_file, yaml_params.train1_file, \ yaml_params.test_file args = x option_params_list = make_params_from_options(options, args) # Precedence is OPTION > YAML > DEFAULT. param_list = [] for option_params in option_params_list: x = [option_params, yaml_params, default_params] parameters = [x for x in x if x] keywds = {} for i in range(len(parameters)-1, -1, -1): p = parameters[i] for name in dir(p): if name.startswith("_"): continue value = getattr(p, name) if value is None: continue keywds[name] = value x = PyBinregParams(**keywds) # Make sure params are complete and valid. check_params(x) param_list.append(x) # Make sure the user didn't specify an unreasonable number of # analyses to be done. if len(param_list) > MAX_ANALYSES: assert False, "Requested %d analyses, but maximum is %d." % ( len(param_list), MAX_ANALYSES) return options, param_list def make_params_from_default(): x = PyBinregParams( binreg_version=2, genes=100, metagenes=2, normref_file=None, strip_affx=False, log_train0=False, log_train1=False, log_test=False, log_normref=False, quantile=False, shiftscale=False, dwd=False, dwd_bild=False, burnin=1000, samples= 5000, skips=1, credible_interval=95, cross_validate=True, noplots=False, label_samples=True, draw_error_bars=True, archive=False, ) return x def make_params_from_yaml(filename, args): import yaml from genomicode import filelib # Since train0_file and train1_file are specified in the YAML # file, args should only contain test_file. assert len(args) == 1, "Please specify test file." test_file, = args data = yaml.load(filelib.openfh(filename).read()) # Conversion of the YAML names to the attributes for PyBinregParams. name2stdname = { "binreg_version" : "binreg_version", "genes" : "genes", "factors" : "metagenes", "quantile_normalize_arrays" : "quantile", "shift_scale" : "shiftscale", "burnins" : "burnin", "iterations" : "samples", "skips" : "skips", "remove_affymetrix_controlprobes" : "strip_affx", } # Make an object with the standard options. keywds = {} for name, stdname in name2stdname.iteritems(): assert name in data, "Missing key in YAML file: %s" % name assert stdname not in keywds keywds[stdname] = data[name] # Make sure the values are the right type. keywds["genes"] = int(data.genes) keywds["metagenes"] = int(data.metagenes) znf = data.get("zero_normalized_file") onf = data.get("one_normalized_file") assert znf, "zero_normalized_file missing" assert onf, "one_normalized_file missing" keywds["train0_file"] = znf keywds["train1_file"] = onf keywds["test_file"] = test_file # Check the data. assert keywds["binreg_version"] in [1, 2] assert keywds["quantile"] in [False, True] assert keywds["shiftscale"] in [False, True] assert keywds["strip_affx"] in [False, True] x = PyBinregParams(**keywds) return x def make_params_from_options(options, args): # Return a list of PyBinregParams. import copy import itertools from genomicode import parselib from genomicode import binreg options = copy.copy(options) # Parse the file arguments. train0_file = train1_file = test_file = None if len(args) == 2: train0_file, train1_file = args elif len(args) == 3: train0_file, train1_file, test_file = args elif len(args) < 2: raise AssertionError, "Please specify train0 and train1 files." else: raise AssertionError, "Too many files." normref_file = options.normref_file # Parse genes and metagenes. Accept genes as string, to allow # people to specify numbers like "080" for 80. if options.genes: genes = [] for (start, end) in parselib.parse_ranges(options.genes): genes.extend(range(start, end+1)) if options.metagenes: metagenes = [] for (start, end) in parselib.parse_ranges(options.metagenes): metagenes.extend(range(start, end+1)) # Normalization reference file only works with shift-scale. if options.normref_file and not options.shiftscale: if test_file: print("Normalization reference provided, so enabling shift-scale " "normalization.") options.shiftscale = True # Configure the normalization options based on the test file. if not test_file: if options.shiftscale: print "No test file, so disabling shift-scale normalization." options.shiftscale = False options.normref_file = None if options.dwd: print "No test file, so disabling DWD normalization." options.dwd = False if options.dwd_bild: print "No test file, so disabling DWD (Bild) normalization." options.dwd_bild = False # Read each of the input files and align them. x = read_matrices(train0_file, train1_file, test_file, normref_file) train0, train1, test, normref = x # Configure the logging options based on the files. log_test = log_normref = False if options.log_the_data == "yes": log_train0 = True log_train1 = True if test: log_test = True if normref: log_normref = True elif options.log_the_data == "no": log_train0 = False log_train1 = False else: assert options.log_the_data == "auto" log_train0 = not binreg.is_logged_array_data(train0) log_train1 = not binreg.is_logged_array_data(train1) if test: log_test = not binreg.is_logged_array_data(test) if normref: log_normref = not binreg.is_logged_array_data(normref) # Configure the plotting parameters. assert options.label_samples in ["yes", "no", "auto"] assert options.draw_error_bars in ["yes", "no", "auto"] label_samples = True if options.label_samples == "no" or ( options.label_samples == "auto" and test and test.ncol() > 50): # Don't label if it's too crowded. label_samples = False draw_error_bars = True if options.draw_error_bars == "no": draw_error_bars = False # Set some attributes that can be directly copied from the options. attributes = [ "binreg_version", "strip_affx", "quantile", "shiftscale", "dwd", "dwd_bild", "burnin", "samples", "skips", "credible_interval", "noplots", "archive", ] keywds = {} keywds["train0_file"] = train0_file keywds["train1_file"] = train1_file keywds["test_file"] = test_file keywds["normref_file"] = normref_file keywds["log_train0"] = log_train0 keywds["log_train1"] = log_train1 keywds["log_test"] = log_test keywds["log_normref"] = log_normref keywds["label_samples"] = label_samples keywds["draw_error_bars"] = draw_error_bars for name in attributes: assert name not in keywds value = getattr(options, name) if value is not None: keywds[name] = value paramlist = [] seen = {} # No duplicate genes or metagenes. for x in itertools.product(genes, metagenes): g, mg = x if (g, mg) in seen: continue seen[(g, mg)] = 1 keywds["genes"] = g keywds["metagenes"] = mg x = PyBinregParams(**keywds) paramlist.append(x) return paramlist def check_params(params): # Make sure the parameters are reasonable. from genomicode import filelib assert params.binreg_version in [1, 2], repr(params.binreg_version) # Make sure genes and metagenes are in valid ranges. assert type(params.genes) is type(0) and params.genes > 0, \ repr(params.genes) assert type(params.metagenes) is type(0) and params.metagenes > 0, \ repr(params.metagenes) # Make sure each file exists. assert filelib.exists_nz(params.train0_file), \ "File not found: %s" % params.train0_file assert filelib.exists_nz(params.train1_file), \ "File not found: %s" % params.train1_file if params.test_file: assert filelib.exists_nz(params.test_file), \ "File not found: %s" % params.test_file if params.normref_file: assert filelib.exists_nz(params.normref_file), \ "File not found: %s" % params.normref_file # Make sure boolean attributes are boolean. bool_attrs = [ "strip_affx", "log_train0", "log_train1", "log_test", "log_normref", "quantile", "shiftscale", "dwd", "dwd_bild", "cross_validate", "noplots", "label_samples", "draw_error_bars", "archive"] for attr in bool_attrs: assert hasattr(params, attr) assert getattr(params, attr) in [True, False] assert params.burnin >= 0 assert params.samples > 0 assert params.skips >= 0 assert params.credible_interval >= 0 and params.credible_interval <= 100 def make_analyses(param_list): # Return a list of Analysis objects. analyses = [] for params in param_list: path = None if len(param_list) > 1: path = "%03d_GENES_%02d_MGENES" % ( params.genes, params.metagenes) x = Analysis(params, path) analyses.append(x) return analyses def make_file_layout(outpath, analysis_path): from genomicode import filelayout outpath = outpath or "." if not os.path.exists(outpath): os.mkdir(outpath) outpath = os.path.realpath(outpath) Path, File = filelayout.Path, filelayout.File # Have only one set of these files for the whole analysis. GLOBAL_FILES = [ Path.GLOBAL_ATTIC("attic", File.DS_ORIG("dataset.original.gct"), File.DS_LOG("dataset.log.gct"), File.DS_QNORM("dataset.qnorm.gct"), File.DS_DWD("dataset.dwd.gct"), File.DS_DWD_BILD("dataset.dwd_bild.gct"), File.DS_SS("dataset.shiftscale.gct"), File.NR_ORIG("normref.original.gct"), File.NR_QNORM("normref.qnorm.gct"), File.NR_FINAL("normref.final.gct"), ), File.DS_FINAL("dataset.gct"), ] LOCAL_FILES = [ # One set of files per set of parameters. Path.BINREG("binreg", File.BR_DESCRIPTION("description.txt"), File.BR_EXPRESSION("expression.txt"), File.BR_COEFFICIENTS("genecoefficients.txt"), File.BR_VALIDATION("validationcases.txt"), ), Path.ATTIC("attic", File.PREDICTIONS_POV("predictions.pov"), File.SIGNATURE_GCT("signature.gct"), File.DS_SIG("dataset.sig.gct"), File.DS_SIG_PNG("dataset.sig.png"), ), File.PARAMETERS("parameters.txt"), File.PROBABILITIES("probabilities.txt"), File.PREDICTIONS_PNG("predictions.png"), File.SIGNATURE_PNG("signature.png"), File.MODEL("model.txt"), File.REPORT("REPORT.html"), ] if analysis_path: LOCAL_FILES = [Path.ANALYSIS(analysis_path, *LOCAL_FILES)] GLOBAL_FILES = GLOBAL_FILES + [ File.GLOBAL_REPORT("REPORT.html"), File.GLOBAL_PROBABILITIES("probabilities.%s.txt" % analysis_path), File.GLOBAL_PREDICTIONS_PNG("predictions.%s.png" % analysis_path), File.GLOBAL_SIGNATURE_PNG("signature.%s.png" % analysis_path), ] file_layout = Path.OUTPATH(outpath, *(GLOBAL_FILES+LOCAL_FILES)) return file_layout def init_paths(file_layout): from genomicode import filelayout for x in filelayout.walk(file_layout): dirpath, dirnames, filenames = x if os.path.exists(dirpath): continue os.mkdir(dirpath) MATRIX_CACHE = {} def read_matrices_all(train0_file, train1_file, test_file, normref_file): global MATRIX_CACHE from genomicode import matrixlib filenames = [train0_file, train1_file] if test_file: filenames.append(test_file) if normref_file: filenames.append(normref_file) x = matrixlib.read_matrices(filenames, cache=MATRIX_CACHE) DATA, ALIGNED = x DATA_train0, DATA_train1 = DATA[:2] ALIGN_train0, ALIGN_train1 = ALIGNED[:2] DATA_test = ALIGN_test = DATA_normref = ALIGN_normref = None if test_file: DATA_test = DATA[2] ALIGN_test = ALIGNED[2] if normref_file: DATA_normref = DATA[-1] ALIGN_normref = ALIGNED[-1] x = (DATA_train0, DATA_train1, DATA_test, DATA_normref, ALIGN_train0, ALIGN_train1, ALIGN_test, ALIGN_normref) return x def read_matrices(train0_file, train1_file, test_file, normref_file): x = read_matrices_all(train0_file, train1_file, test_file, normref_file) (DATA_train0, DATA_train1, DATA_test, DATA_normref, ALIGN_train0, ALIGN_train1, ALIGN_test, ALIGN_normref) = x return ALIGN_train0, ALIGN_train1, ALIGN_test, ALIGN_normref def strip_affx_control_probes(train0, train1, test, normref): # test, normref can be None from genomicode import binreg from genomicode import matrixlib print "Stripping Affymetrix control IDs." train0_s = binreg.strip_affx_control_probes(train0) train1_s = binreg.strip_affx_control_probes(train1) test_s = None if test: test_s = binreg.strip_affx_control_probes(test) normref_s = None if normref: normref_s = binreg.strip_affx_control_probes(normref) matrixlib.assert_rows_aligned(train0_s, train1_s, test_s, normref_s) return train0_s, train1_s, test_s, normref_s def log_matrices( train0, train1, test, normref, log_train0, log_train1, log_test, log_normref): # Log each variable if necessary. Will log in place. Return a # boolean indicating whether anything was logged. test can be None. from genomicode import jmath variables = [ ("train0", train0, log_train0), ("train1", train1, log_train1), ("test", test, log_test), ("normref", normref, log_normref), ] any_files_logged = False for name, var, do_log in variables: if var is None: continue msg = "I will not log the %s data." % name if do_log: msg = "I will log the %s data." % name var._X = jmath.log(var._X, base=2, safe=1) any_files_logged = True print msg sys.stdout.flush() return any_files_logged def quantile_normalize_matrices( train0, train1, test, normref, matlab=None, binreg_path=None): # Normalize the matrices with quantiles. Will normalize in place. # test can be None. from genomicode import Matrix from genomicode import quantnorm from genomicode import matrixlib matrixlib.assert_rows_aligned(train0, train1, test, None) X = [None] * train0.nrow() for i in range(len(X)): x = train0._X[i] + train1._X[i] if test: x = x + test._X[i] if normref: x = x + normref._X[i] X[i] = x # Normalize base on the values in the training set. print "Normalizing with quantiles." I = range(train0.ncol()+train1.ncol()) DATA = Matrix.InMemoryMatrix(X) # Our own quantile normalization differs from the Matlab one at # the 4-5th decimal place. Use the Matlab code so that the # results will be exactly the same. #DATA = quantnorm.normalize(DATA, which_columns=I) DATA = quantnorm.normalize_binreg( DATA, which_columns=I, matlab=matlab, binreg_path=binreg_path) # Reassign normalized values in place. X = DATA._X for i in range(len(X)): x = X[i] train0._X[i] = x[:train0.ncol()] train1._X[i] = x[train0.ncol():train0.ncol()+train1.ncol()] if test: j = train0.ncol()+train1.ncol() test._X[i] = x[j:j+test.ncol()] if normref: j = train0.ncol()+train1.ncol() if test: j += test.ncol() normref._X[i] = x[j:j+normref.ncol()] def dwd_normalize_matrices( train0, train1, test, version=None, matlab=None, dwd_path=None): from genomicode import Matrix from genomicode import dwdnorm from genomicode import matrixlib # test must be specified to dwd normalize matrices. assert test, "DWD normalization requires a test set." matrixlib.assert_rows_aligned(train0, train1, test, None) assert train0.ncol() and train1.ncol(), "No training samples found." assert test.ncol(), "No test samples found." X = [None] * train0.nrow() for i in range(len(X)): X[i] = train0._X[i] + train1._X[i] + test._X[i] DATA = Matrix.InMemoryMatrix(X) # Y is a list of -1, 1 indicating the class of each sample. -1 is # the training data, and 1 is the test data. Y = [-1]*(train0.ncol()+train1.ncol()) + [1]*test.ncol() if version == "bild": # Run Andrea's version. Here, 1 is train0, -1 is train1, and # 2 are the tumor samples. Y = [1]*train0.ncol() + [-1]*train1.ncol() + [2]*test.ncol() if version == "bild": print "Normalizing with DWD (Bild)." else: print "Normalizing with DWD." DATA_n = dwdnorm.normalize( DATA, Y, version=version, matlab=matlab, dwd_path=dwd_path) assert DATA.dim() == DATA_n.dim() # Reassign normalized values in place. X_n = DATA_n._X for i in range(len(X_n)): x = X_n[i] train0._X[i] = x[:train0.ncol()] train1._X[i] = x[train0.ncol():train0.ncol()+train1.ncol()] test._X[i] = x[-test.ncol():] def shiftscale_normalize_matrices( train0, train1, test, normref, matlab=None, binreg_path=None): if not normref: _shiftscale_normalize_standard( train0, train1, test, matlab=matlab, binreg_path=binreg_path) else: _shiftscale_normalize_normref( train0, train1, test, normref, matlab=matlab, binreg_path=binreg_path) def _shiftscale_normalize_standard( train0, train1, test, matlab=None, binreg_path=None): from genomicode import Matrix from genomicode import matrixlib from genomicode import shiftscalenorm print "Normalizing with shift-scale."; sys.stdout.flush() # test must be specified to shiftscale normalize matrices. assert test, "Shift-scale normalization requires a test set." assert train0.ncol() and train1.ncol(), "Training samples missing." assert test.ncol(), "No test samples found." matrixlib.assert_rows_aligned(train0, train1, test, None) # Shift-scale will normalize X to Y. X is the test data and Y is # the training data. Y = [None] * train0.nrow() X = [None] * test.nrow() for i in range(len(Y)): Y[i] = train0._X[i] + train1._X[i] X[i] = test._X[i] DATA_X = Matrix.InMemoryMatrix(X) DATA_Y = Matrix.InMemoryMatrix(Y) DATA_n = shiftscalenorm.normalize( DATA_X, DATA_Y, matlab=matlab, binreg_path=binreg_path) assert DATA_n.dim() == DATA_X.dim() # Reassign normalized values in place. X_n = DATA_n._X for i in range(len(X_n)): test._X[i] = X_n[i] def _shiftscale_normalize_normref( train0, train1, test, normref, matlab=None, binreg_path=None): from genomicode import Matrix from genomicode import matrixlib from genomicode import shiftscalenorm # test must be specified to shiftscale normalize matrices. assert test, "Shift-scale normalization requires a test set." assert train0.ncol() and train1.ncol(), "Training samples missing." assert test.ncol(), "No test samples found." assert normref.ncol(), "No normalization reference samples found." matrixlib.assert_rows_aligned(train0, train1, test, normref) print("Normalizing with shift-scale, " "using a normalization reference with %d samples." % normref.ncol()) # Shift-scale will normalize X to Y. X is the test data and Y is # the training data. Y = [None] * train0.nrow() for i in range(len(Y)): Y[i] = train0._X[i] + train1._X[i] DATA_Y = Matrix.InMemoryMatrix(Y) # Normalize one sample at a time. for j in range(test.ncol()): print "Shift-scale normalizing sample %d of %d." % (j+1, test.ncol()) sys.stdout.flush() sample = [x[j] for x in test._X] X = [None] * normref.nrow() for i in range(len(X)): X[i] = [sample[i]] + normref._X[i] DATA_X = Matrix.InMemoryMatrix(X) assert DATA_X.ncol() == normref.ncol() + 1 DATA_n = shiftscalenorm.normalize( DATA_X, DATA_Y, matlab=matlab, binreg_path=binreg_path) assert DATA_n.dim() == DATA_X.dim() # For debugging: #arrayio.tdf.write(DATA_X, open("SAMPLE%02d_nonorm.out"%j, 'w')) #arrayio.tdf.write(DATA_n, open("SAMPLE%02d_norm.out"%j, 'w')) # Reassign normalized values in place. X_n = DATA_n._X for i in range(len(X_n)): test._X[i][j] = X_n[i][0] def filter_missing_values(train0, train1, test, normref): import math # Optimization: Assume that the rows are aligned. I = [] for i in range(train0.nrow()): x = train0._X[i] + train1._X[i] if test: x += test._X[i] if normref: x += normref._X[i] x = [x for x in x if math.isnan(x)] if not x: I.append(i) else: print "Filtering out nan's found in row %d." % (i+1) if len(I) < train0.nrow(): train0 = train0.matrix(I, None) train1 = train1.matrix(I, None) if test: test = test.matrix(I, None) if normref: normref = normref.matrix(I, None) x = train0, train1, test, normref return x def write_dataset(filename, train0, train1, test): # test can be None. import arrayio from genomicode import matrixlib matrices = [train0, train1] if test: matrices.append(test) DATA = matrixlib.merge_gct_matrices(*matrices) arrayio.gct_format.write(DATA, open(filename, 'w')) def write_files_for_binreg(train0, train1, test, file_layout): # Format the files for binreg. test can be None. from genomicode import binreg x = binreg.format_data_files(train0, train1, test) desc, exp = x open(file_layout.BR_DESCRIPTION, 'w').write(desc) open(file_layout.BR_EXPRESSION, 'w').write(exp) def run_analysis(analysis, options, train0, train1, test, normref): import time start_time = time.time() x = "Analyzing with %d genes and %d metagenes." % ( analysis.params.genes, analysis.params.metagenes) if analysis.params.metagenes == 1: x = x.replace("metagenes", "metagene") print x # Format the parameters and output files for binreg. print "Formatting data for binreg analysis." file_layout = make_file_layout(options.outpath, analysis.subpath) init_paths(file_layout) if False and normref: # This gives exactly the same results as the standard # analysis. Don't bother running it. It's slower. _run_binreg_normref( analysis, options, file_layout, train0, train1, test, normref) else: _run_binreg_standard( analysis, options, file_layout, train0, train1, test) # Generate some files for output. print "Summarizing results."; sys.stdout.flush() summarize_model(file_layout) summarize_parameters(analysis.params, file_layout) summarize_probabilities(train0, train1, test, file_layout) summarize_signature_dataset(file_layout) # Make some plots, if desired. if not analysis.params.noplots: summarize_signature_heatmap( options.python, options.arrayplot, options.cluster, file_layout, options.libpath) summarize_dataset_heatmap( options.python, options.arrayplot, options.cluster, file_layout, options.libpath) summarize_predictions( options.povray, analysis.params.label_samples, analysis.params.draw_error_bars, file_layout) # Make a report for this analysis. summarize_report(options.outpath, analysis, start_time) sys.stdout.flush() def _run_binreg_standard(analysis, options, file_layout, train0, train1, test): from genomicode import binreg print "Running binreg."; sys.stdout.flush() write_files_for_binreg(train0, train1, test, file_layout) params = analysis.params br_params = binreg.BinregParams( binreg_version=params.binreg_version, cross_validate=int(params.cross_validate), make_plots=0, num_genes=params.genes, num_metagenes=params.metagenes, quantile_normalize=0, shift_scale_normalize=0, num_burnin=params.burnin, num_iterations=params.samples, num_skips=params.skips, credible_interval=params.credible_interval) r = binreg.binreg_raw( file_layout.BR_EXPRESSION, file_layout.BR_DESCRIPTION, 1, br_params, matlab=options.matlab, binreg_path=options.binreg_path, outpath=file_layout.BINREG) br_output = r.read() binreg.check_output(br_output) print br_output sys.stdout.flush() def _run_binreg_normref( analysis, options, file_layout, train0, train1, test, normref): import shutil from genomicode import Matrix from genomicode import matrixlib from genomicode import binreg from genomicode import filelib import arrayio # test must be specified to shiftscale normalize matrices. assert test, "Shift-scale normalization requires a test set." assert train0.ncol() and train1.ncol(), "Training samples missing." assert test.ncol(), "No test samples found." assert normref.ncol(), "No normalization reference samples found." matrixlib.assert_rows_aligned(train0, train1, test, normref) print("Running binreg " "using a normalization reference with %d samples." % normref.ncol()) for j in range(test.ncol()): print "Running binreg on sample %d of %d." % (j+1, test.ncol()) sys.stdout.flush() # Put the test sample in the context of the normalization reference. X = [None] * test.nrow() for i in range(test.nrow()): X[i] = [test._X[i][j]] + normref._X[i] synonyms = { arrayio.ROW_ID : test._synonyms[arrayio.ROW_ID] } test_j = Matrix.InMemoryMatrix( X, row_names=test._row_names, synonyms=synonyms) #test_j = Matrix.add_synonyms(x, synonyms) write_files_for_binreg(train0, train1, test_j, file_layout) params = analysis.params br_params = binreg.BinregParams( binreg_version=params.binreg_version, cross_validate=int(params.cross_validate), make_plots=0, num_genes=params.genes, num_metagenes=params.metagenes, quantile_normalize=0, shift_scale_normalize=0, num_burnin=params.burnin, num_iterations=params.samples, num_skips=params.skips, credible_interval=params.credible_interval) r = binreg.binreg_raw( file_layout.BR_EXPRESSION, file_layout.BR_DESCRIPTION, 1, br_params, matlab=options.matlab, binreg_path=options.binreg_path, outpath=file_layout.BINREG) br_output = r.read() binreg.check_output(br_output) assert os.path.exists(file_layout.BR_VALIDATION), \ "I could not find the validation file." sample_file = "%s.%04d" % (file_layout.BR_VALIDATION, j) shutil.move(file_layout.BR_VALIDATION, sample_file) # Print out last one, so user can see if there are any errors. print br_output sys.stdout.flush() # Combine the validation cases file. data = [] # list of (index, type, prob, lower_ci, upper_ci, mgene) for j in range(test.ncol()): sample_file = "%s.%04d" % (file_layout.BR_VALIDATION, j) assert os.path.exists(sample_file) iter_ = filelib.read_cols(sample_file) x = iter_.next() assert len(x) == 6 data.append(x) # Fix the indexes. assert data and len(data) == test.ncol() first_index = int(data[0][0]) for j in range(test.ncol()): x = data[j] x[0] = first_index + j data[j] = x # Write out the new validationcases file. assert not os.path.exists(file_layout.BR_VALIDATION) handle = open(file_layout.BR_VALIDATION, 'w') for x in data: print >>handle, "\t".join(map(str, x)) handle.close() def summarize_model(file_layout): from genomicode import filelib assert filelib.exists_nz(file_layout.BR_COEFFICIENTS), \ "Cannot find Binreg model. Binreg failed?" handle = open(file_layout.MODEL, 'w') print >>handle, "%s\t%s" % ("Name", "Coefficient") for line in open(file_layout.BR_COEFFICIENTS): x = line.strip().split() assert len(x) == 2 coef, gene = x x = gene, coef print >>handle, "\t".join(x) handle.close() def summarize_parameters(params, file_layout): handle = open(file_layout.PARAMETERS, 'w') print >>handle, "NAME\tVALUE" print >>handle, "Binreg Version\t%d" % params.binreg_version print >>handle, "Genes\t%d" % params.genes print >>handle, "Metagenes\t%d" % params.metagenes print >>handle, "Train0\t%s" % os.path.split(params.train0_file)[1] print >>handle, "Train1\t%s" % os.path.split(params.train1_file)[1] x = "" if params.test_file: x = os.path.split(params.test_file)[1] print >>handle, "Test\t%s" % x x = "" if params.normref_file: x = os.path.split(params.normref_file)[1] print >>handle, "Normalization Reference File\t%s" % x print >>handle, "Log Train0\t%d" % int(params.log_train0) print >>handle, "Log Train1\t%d" % int(params.log_train1) print >>handle, "Log Test\t%d" % int(params.log_test) print >>handle, "Log Normalization Reference\t%d" % int(params.log_normref) print >>handle, "Strip AFFX control\t%d" % int(params.strip_affx) print >>handle, "Quantile Normalize\t%d" % int(params.quantile) print >>handle, "Shift-Scale Normalize\t%d" % int(params.shiftscale) print >>handle, "DWD Normalize\t%d" % int(params.dwd) print >>handle, "DWD Normalize (Bild)\t%d" % int(params.dwd_bild) print >>handle, "Burn In\t%d" % params.burnin print >>handle, "Samples\t%d" % params.samples print >>handle, "Skips\t%d" % params.skips print >>handle, "Credible Interval\t%d" % params.credible_interval print >>handle, "Cross Validate\t%d" % int(params.cross_validate) print >>handle, "Make Plots\t%d" % int(not params.noplots) print >>handle, "Label Samples\t%d" % int(params.label_samples) print >>handle, "Draw Error Bars\t%d" % int(params.draw_error_bars) handle.close() def summarize_probabilities(train0, train1, test, file_layout): from genomicode import binreg x = binreg.format_predictions( train0, train1, test, outpath=file_layout.BINREG) open(file_layout.PROBABILITIES, 'w').write(x) def summarize_signature_dataset(file_layout): import arrayio from genomicode import filelib from genomicode import jmath from genomicode import hashlib # Read the gene_ids of interest. assert filelib.exists_nz(file_layout.BR_COEFFICIENTS) x = [x[1] for x in filelib.read_cols(file_layout.BR_COEFFICIENTS)] gene_ids = hashlib.hash_many_geneids(x) assert gene_ids[0] == hashlib.hash_geneid("Intercept") gene_ids.pop(0) # Read the dataset. Should be in GCT format. DATA = arrayio.read(file_layout.DS_FINAL) assert arrayio.gct_format.is_matrix(DATA) # Hash the IDs to make sure they match the ones in the coefficient file. x = hashlib.hash_many_geneids(DATA.row_names("NAME")) DATA._row_names["NAME"] = x # Select only the signature genes. DATA_sig = DATA.matrix(row=gene_ids, row_header=arrayio.ROW_ID) assert len(gene_ids) == DATA_sig.nrow(), "%d %d" % ( len(gene_ids), DATA_sig.nrow()) # Figure out whether the data is training or test. type2i = { "train0" : 0, "train1" : 1, "test" : 2 } # Can not use sample names because they may not be unique across # data sets. #sample2type = {} #for d in filelib.read_row(files.probabilities, header=1): # if d.Sample in sample2type: # assert sample2type[d.Sample] == type2i[d.Type], \ # "Conflicting types for sample %s: %s %s" % ( # d.Sample, sample2type[d.Sample], type2i[d.Type]) # sample2type[d.Sample] = type2i[d.Type] #TYPES = [sample2type[x] for x in DATA.col_names()] TYPES = [None] * DATA.ncol() for d in filelib.read_row(file_layout.PROBABILITIES, header=1): d.Index = int(d.Index) if TYPES[d.Index] is not None: assert TYPES[d.Index] == type2i[d.Type], \ "Conflicting types for index %d: %s %s" % ( d.Index, TYPES[d.Index], type2i[d.Type]) TYPES[d.Index] = type2i[d.Type] # Pull out just the training data. I = [i for (i, t) in enumerate(TYPES) if t in [0, 1]] DATA_train = DATA_sig.matrix(None, I) TYPES_train = [x for x in TYPES if x in [0, 1]] # Sort the genes by decreasing correlation to the outcome. cors = [None] * DATA_train.nrow() for i in range(DATA_train.nrow()): x, y = TYPES_train, DATA_train[(i, None)] cors[i] = jmath.cor(x, y, safe=1) O = jmath.order(cors, decreasing=1) DATA_train = DATA_train.matrix(O, None) DATA_sig = DATA_sig.matrix(O, None) # Write out the dataset with the signature. handle = open(file_layout.DS_SIG, 'w') arrayio.gct_format.write(DATA_sig, handle) handle.close() # Normalize the data. #X = DATA_train._X #for i in range(len(X)): # m = jmath.mean(X[i]) # # Mean center. # X[i] = [x-m for x in X[i]] # # Normalize to stddev of 1. # s = jmath.stddev(X[i]) # if s == 0: # continue # X[i] = [x/s for x in X[i]] # Write it out in gct_format handle = open(file_layout.SIGNATURE_GCT, 'w') arrayio.gct_format.write(DATA_train, handle) handle.close() def summarize_signature_heatmap( python, arrayplot, cluster, file_layout, libpath=[]): import arrayio from genomicode import graphlib DATA = arrayio.gct_format.read(file_layout.SIGNATURE_GCT) nrow, ncol = DATA.dim() # Make the heatmap big enough to read the gene names. SCALE 1.2 # is probably the minimum size, but the names are a bit fuzzy. SCALE = 1.5 x = graphlib.find_tall_heatmap_size( nrow, ncol, min_box_height=1, min_box_width=1, max_box_height=40, max_box_width=40, max_total_height=768*SCALE, max_total_width=1024*SCALE) xpix, ypix = x #print ypix, xpix, nrow, ncol; sys.stdout.flush() graphlib.plot_heatmap( file_layout.SIGNATURE_GCT, file_layout.SIGNATURE_PNG, xpix, ypix, color="bild", show_colorbar=True, show_grid=True, gene_center="mean", gene_normalize="var", gene_label=True, array_label=True, python=python, arrayplot=arrayplot, cluster=cluster, libpath=libpath) def summarize_dataset_heatmap( python, arrayplot, cluster, file_layout, libpath=[]): import arrayio from genomicode import graphlib DATA = arrayio.gct_format.read(file_layout.DS_SIG) nrow, ncol = DATA.dim() # 10 won't work for large data sets (e.g. 1000 samples). #min_box_width = 10 min_box_width = 1 x = graphlib.find_tall_heatmap_size( nrow, ncol, min_box_width=min_box_width, max_total_height=768*3, max_total_width=1024*3) xpix, ypix = x #print xpix, ypix, ncol, nrow; sys.stdout.flush() graphlib.plot_heatmap( file_layout.DS_SIG, file_layout.DS_SIG_PNG, xpix, ypix, color="bild", show_colorbar=True, show_grid=True, cluster_genes=True, gene_center="mean", gene_normalize="var", array_label=True, python=python, arrayplot=arrayplot, cluster=cluster, libpath=libpath) def summarize_predictions(povray, label_samples, draw_error_bars, file_layout): # May not plot anything if there are problems with the BinReg # output (e.g. all predictions are nan). import math from genomicode import filelib from genomicode import graphlib from genomicode import graphconst assert filelib.exists_nz(file_layout.PROBABILITIES) COL_train0 = 0.17, 0.51, 0.99 COL_train1 = 0.84, 0.10, 0.11 COL_test = 0.15, 0.15, 0.16 X, Y, error_bar = [], [], [] pch = [] color = [] sample = [] onpoint_label = [] num_points = {} # "test", "train0", "train1" -> count for d in filelib.read_row(file_layout.PROBABILITIES, header=1): if d.Method == "FITTED": continue x = float(d.Metagene) y = float(d.Probability) if math.isnan(x) or math.isnan(y): continue sample.append(d.Sample) # Calculate the error bars. err_l, err_u = y-float(d.Lower_CI), float(d.Upper_CI)-y if math.isnan(err_l): err_l = 0 if math.isnan(err_u): err_u = 0 # Sometimes BinReg will generate negative errors. If it's not # too bad, then just ignore it. # Have seen negative errors as low as -0.032. assert err_l >= -0.05 and err_u >= -0.05, "%g %g" % (err_l, err_u) err_l, err_u = max(err_l, 0), max(err_u, 0) error = round(err_l, 3), round(err_u, 3) # Set the color. col = COL_test if d.Type == "train0": col = COL_train0 elif d.Type == "train1": col = COL_train1 # Set the shape. p = graphconst.SQUARE if d.Type in ["train0", "train1"]: p = graphconst.CIRCLE # Set the label. np = num_points.get(d.Type, 0) num_points[d.Type] = np+1 onpoint_label.append(np+1) X.append(x) Y.append(y) pch.append(p) error_bar.append(error) color.append(col) assert X, "BinReg predictions didn't work. Nothing to plot." assert len(X) == len(Y) xtick = graphlib.place_ticks(min(X), max(X)) xtick_label = True ytick = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] ytick_label = ["%d%%" % int(x*100) for x in ytick] plot_width, plot_height = 1024, 768 plot_width, plot_height = int(plot_width*1.5), int(plot_height*1.5) font = os.path.join( os.path.split(graphlib.__file__)[0], "Verdana Bold.ttf") onpoint_label = None # Don't display labels. overpoint_label = sample if not label_samples: overpoint_label = None if not draw_error_bars: error_bar = None points = zip(X, Y) graph = graphlib.scatter( points, color=color, shape=pch, error_bar=error_bar, point_size=1, onpoint_label=onpoint_label, overpoint_label=overpoint_label, ylim=(0, 1.02), xtick=xtick, xtick_label=xtick_label, ytick=ytick, ytick_label=ytick_label, tick_size=1, xlabel="Metagene Score", ylabel="Probability", label_size=1, width=plot_width, height=plot_height, font=font) x = graph.write(file_layout.PREDICTIONS_PNG, povray_bin=povray) print x; sys.stdout.flush() assert filelib.exists_nz(file_layout.PREDICTIONS_PNG), \ "Failed to plot predictions." # povray -D -J +Opredictions.png -H768 -W1024 +A0.5 predictions.pov def summarize_report(outpath, analysis, start_time): import time from genomicode import parselib from genomicode import htmllib params = analysis.params def highlight(s): return htmllib.SPAN(s, style="background-color:yellow") lines = [] w = lines.append w("<HTML>") w(htmllib.HEAD(htmllib.TITLE("CreateSignatures Report"))) w("<BODY>") w(htmllib.CENTER(htmllib.H1(htmllib.EM("CreateSignatures") + " Report"))) # Describe the analysis in human language. w(htmllib.H3("I. Analysis")) items = [] # Files. t0 = os.path.split(params.train0_file)[1] t1 = os.path.split(params.train1_file)[1] te = None nr = None if params.test_file: te = os.path.split(params.test_file)[1] if params.normref_file: nr = os.path.split(params.normref_file)[1] x = "I ran a signature analysis using a training set of %s and %s." % ( highlight(t0), highlight(t1)) if te: x += " I generated predictions on %s." % highlight(te) items.append(x) # Algorithm. genes = highlight("%d genes" % params.genes) metagenes = highlight("%d metagenes" % params.metagenes) if params.metagenes == 1: metagenes = metagenes.replace("genes", "gene") x = "I used the %s algorithm with %s and %s." % ( highlight("BinReg %d" % params.binreg_version), genes, metagenes) items.append(x) # Logging the data. logged = [] if params.log_train0: logged.append(t0) if params.log_train1: logged.append(t1) if params.log_test: assert te logged.append(te) if params.log_normref: assert nr logged.append(nr) # Make sure there are no duplicates in logged. logged = [logged[i] for i in range(len(logged)) if logged[i] not in logged[:i]] logged_str = None if len(logged) == 1: logged_str = logged[0] elif len(logged) == 2: logged_str = "%s and %s" % tuple(logged) elif len(logged) == 3: logged_str = "%s, %s, and %s" % tuple(logged) elif len(logged) == 4: logged_str = "%s, %s, %s, and %s" % tuple(logged) elif len(logged): raise AssertionError, "Too many logged files." if logged_str: x = "I logged the expression values in %s." % logged_str items.append(x) # Normalization. norm = [] if params.quantile: norm.append("quantile") if params.shiftscale: norm.append("Shift-Scale") if params.dwd: norm.append("DWD") if params.dwd_bild: norm.append("DWD (Bild method)") norm_str = None if len(norm) == 1: norm_str = highlight(norm[0]) elif len(norm) == 2: norm_str = "%s and %s" % tuple(map(highlight, norm)) elif len(norm) == 3: norm_str = "%s, %s, and %s" % tuple(map(highlight, norm)) elif len(norm) == 4: norm_str = "%s, %s, %s, and %s" % tuple(map(highlight, norm)) if norm_str: x = "I applied %s normalization." % norm_str else: x = "I did not normalize the data." if params.normref_file: if params.shiftscale: nrf = os.path.split(params.normref_file)[1] x += " For shift-scale, I used %s as a normalization reference."\ % nrf items.append(x) # Strip Affymetrix control probes. if params.strip_affx: x = "As requested, I stripped the Affymetrix control probes." items.append(x) # MCMC x = ("For the statistical (Markov chain Monte Carlo) simulation, I " "discarded %s samples for the burn-in and then collected %s " "samples for the model." % ( parselib.pretty_int(params.burnin), parselib.pretty_int(params.samples))) if params.skips > 1: x += " During the sampling, I recorded every %s sample." % ( parselib.pretty_ordinal(params.skips)) items.append(x) items = [htmllib.LI() + x for x in items] items_str = "\n".join(items) w(htmllib.UL(items_str)) # Put together a table with the results. w(htmllib.P()) w(htmllib.H3("II. Results")) rows = [] file_layout = make_file_layout(outpath, analysis.subpath) x = read_matrices( params.train0_file, params.train1_file, params.test_file, params.normref_file) train0, train1, test, normref = x x = _make_signature_figure(file_layout.SIGNATURE_PNG, train0, train1) figure, legend = x figure_col1 = htmllib.TD(figure) legend_col1 = htmllib.TD(legend, valign="TOP") x = _make_predictions_figure( file_layout.PREDICTIONS_PNG, file_layout.PROBABILITIES, params) figure, legend = x figure_col2 = htmllib.TD(figure) legend_col2 = htmllib.TD(legend, valign="TOP") x = htmllib.TR(figure_col1+"\n"+figure_col2) rows.append(x) x = htmllib.TR(legend_col1+"\n"+legend_col2) rows.append(x) rows_str = "\n".join(rows) w(htmllib.TABLE(rows_str, border=0, cellspacing=10)) # Write the footer. w(htmllib.P()) w(htmllib.HR()) end_time = time.time() w(_make_footer(start_time, end_time)) w("</BODY>") w("</HTML>") x = "\n".join(lines) + "\n" outfile = file_layout.REPORT open(outfile, 'w').write(x) def summarize_all_report(outpath, analyses, start_time): import time from genomicode import htmllib #def highlight(s): # return htmllib.SPAN(s, style="background-color:yellow") def yesno(x): if x: return "Yes" return "No" lines = [] w = lines.append w("<HTML>") w(htmllib.HEAD(htmllib.TITLE("CreateSignatures Report"))) w("<BODY>") w(htmllib.CENTER(htmllib.H1(htmllib.EM("CreateSignatures") + " Report"))) # Put together a table with the summary. w(htmllib.P()) w(htmllib.H3("I ran %d analyses:" % len(analyses))) rows = [] # Make a header. cols = [ htmllib.TD("#"), htmllib.TH("Version"), htmllib.TH("Genes"), htmllib.TH("Metagenes"), htmllib.TH("Quantile"), htmllib.TH("Shift-Scale"), htmllib.TH("DWD"), htmllib.TH("DWD (Bild)"), htmllib.TH("Train 0", align="LEFT"), htmllib.TH("Train 1", align="LEFT"), htmllib.TH("Test", align="LEFT"), ] x = htmllib.TR("\n".join(cols)) rows.append(x) for i, analysis in enumerate(analyses): params = analysis.params cols = [] x = htmllib.A("%d." % (i+1), "#analysis%02d" % (i+1)) cols.append(x) cols.append(params.binreg_version) cols.append(params.genes) cols.append(params.metagenes) cols.append(yesno(params.quantile)) cols.append(yesno(params.shiftscale)) cols.append(yesno(params.dwd)) cols.append(yesno(params.dwd_bild)) cols.append(os.path.split(params.train0_file)[1]) cols.append(os.path.split(params.train1_file)[1]) x = "None" if params.test_file: x = os.path.split(params.test_file)[1] cols.append(x) for i in range(len(cols)): if i >= 0 and i < 8: cols[i] = htmllib.TD(cols[i], align="MIDDLE") else: cols[i] = htmllib.TD(cols[i]) x = htmllib.TR("\n".join(cols)) rows.append(x) rows_str = "\n".join(rows) w(htmllib.TABLE(rows_str, border=1, cellpadding=3, cellspacing=0)) # Put together a table with each of the results. w("<P>\n") rows = [] for i, analysis in enumerate(analyses): params = analysis.params file_layout = make_file_layout(outpath, analysis.subpath) if i > 0: # Make a divider between the rows. x = htmllib.TR(htmllib.TD(htmllib.HR(), colspan=2)) rows.append(x) # Make the heading for this set of parameters. x = htmllib.TR( htmllib.TD( htmllib.A( htmllib.H3("%d Genes, %d Metagenes" % ( params.genes, params.metagenes)) , name="analysis%02d" % (i+1)), colspan=2, align="CENTER")) rows.append(x) x = read_matrices( params.train0_file, params.train1_file, params.test_file, params.normref_file) train0, train1, test, normref = x x = _make_signature_figure( file_layout.GLOBAL_SIGNATURE_PNG, train0, train1) figure, legend = x figure_col1 = htmllib.TD(figure) legend_col1 = htmllib.TD(legend, valign="TOP") x = _make_predictions_figure( file_layout.GLOBAL_PREDICTIONS_PNG, file_layout.GLOBAL_PROBABILITIES, params) figure, legend = x figure_col2 = htmllib.TD(figure) legend_col2 = htmllib.TD(legend, valign="TOP") x = htmllib.TR(figure_col1+figure_col2) rows.append(x) x = htmllib.TR(legend_col1+legend_col2) rows.append(x) rows_str = "\n".join(rows) w(htmllib.TABLE(rows_str, border=0, cellspacing=10)) # Write the footer. w(htmllib.P()) w(htmllib.HR()) end_time = time.time() w(_make_footer(start_time, end_time)) w("</BODY>") w("</HTML>") x = "\n".join(lines) + "\n" file_layout = make_file_layout(outpath, analyses[0].subpath) outfile = file_layout.GLOBAL_REPORT open(outfile, 'w').write(x) def _make_signature_figure(png_file, train0, train1): from genomicode import filelib from genomicode import htmllib x = "No plot generated." if filelib.exists_nz(png_file): sig_file = os.path.split(png_file)[1] x = htmllib.A(htmllib.IMG(height=480, src=sig_file), href=sig_file) figure = x legend = ( htmllib.B("Figure 1: Signature Heatmap. ") + "In this heatmap, each row represents a gene in the signature. " "The first %d columns are the samples from the %s " "data set, and the remaining %d columns are the samples from the " "%s data set. " "Warm colors indicate high expression of the gene, and cool " "colors indicate low expression." % ( train0.ncol(), htmllib.EM("train0"), train1.ncol(), htmllib.EM("train1"), )) return figure, legend def _make_predictions_figure(png_file, probabilities_file, params): from genomicode import filelib from genomicode import htmllib x = "No plot generated." if filelib.exists_nz(png_file): pred_file = os.path.split(png_file)[1] x = htmllib.A( htmllib.IMG(height=480, src=pred_file), href=pred_file) figure = x x = ( htmllib.B("Figure 2: Predictions. ") + "This scatter plot shows the predictions from the signature " "for each sample. " "On the Y-axis, high probabilities indicate that the gene " "expression profile of the sample better resembles the train 1 " "class, while low probabilities indicate a closer resemblance " "to train 0. " "The blue and red circles are the predictions (from " "leave-one-out cross-validation) on the train 0 and train 1 " "samples, respectively. ") if params.test_file: x += "The black squares are the predictions on the test samples. " if params.draw_error_bars: x += "The error bars show the %d%% credible interval. " % \ params.credible_interval x += ( "The X-axis, the Metagene Score, is the magnitude of the " "sample on the first principal component. " "This is used to help separate the samples across the plot.") prob_file = os.path.split(probabilities_file)[1] x += htmllib.P() + ( "The raw values from this plot are available as a " 'tab-delimited text file: %s.' % htmllib.A(prob_file, href=prob_file)) legend = x return figure, legend def _make_footer(start_time, end_time): from genomicode import parselib from genomicode import htmllib time_str = parselib.pretty_date(start_time) run_time = pretty_runtime(start_time, end_time) hostname = pretty_hostname() footer = htmllib.EM( "This analysis was run on %s on %s. It took %s to complete.\n" % (time_str, hostname, run_time)) return footer ## def make_FILES(files): ## handle = open(files.FILES, 'w') ## w = handle.write ## w("This describes the files created by the analysis.\n") ## w("\n") ## w("Summary of results:\n") ## w("probabilities.txt Predicted probabilities on all samples.\n") ## w("predictions.png Plot of predictions.\n") ## w("signature.png Heatmap of the signature.\n") ## w("FILES This file.\n") ## w("\n") ## w("Raw results:\n") ## w("normalizedX.txt Normalized expression data.\n") ## w("normalizedX.pcl Normalized expression data in PCL format.\n") ## w("signature.pcl Expression profile of the signature in PCL " ## "format.\n") ## w("signature.cdt Same as signature.pcl.\n") ## w("trainingcases.txt Predictions on training set (fitted).\n") ## w("crossvalidation.txt Predictions on training set " ## "(cross-validation).\n") ## w("validationcases.txt Predictions on test set.\n") ## w("genecoefficients.txt Parameters for regression model.\n") ## w("plotdata.mat Internal data for generating plots.\n") ## w("predictions.pov POV-Ray description file.\n") ## w("\n") ## w("Input to BinReg:\n") ## w("description.txt Gene IDs.\n") ## w("expression.txt Expression data.\n") ## w("preferences.dat BinReg preference file.\n") ## handle.close() def pretty_runtime(start_time, end_time): from genomicode import parselib x = end_time-start_time fracs = x - int(x) fracs = int(fracs * 1000) x = int(x) num_hours = x / 3600 x = x % 3600 num_secs = x % 60 num_mins = x / 60 if num_hours == 0 and num_mins == 0: run_time = "%ss" % parselib.pretty_int(num_secs) elif num_hours == 0: run_time = "%02d:%02d.%03d" % (num_mins, num_secs, fracs) else: run_time = "%02d:%02d:%02d.%03d" % ( num_hours, num_mins, num_secs, fracs) return run_time def pretty_hostname(): import subprocess cmd = "hostname" p = subprocess.Popen( cmd, shell=True, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) wh, r = p.stdin, p.stdout wh.close() hostname = r.read().strip() assert hostname, "I could not get the hostname." return hostname def main(): import time # Print the starting message. start_time = time.time() x1 = pretty_hostname() x2 = time.strftime("%A, %d %B %Y, %I:%M %p", time.localtime(start_time)) print "Running pybinreg.py analysis on %s on %s." % (x1, x2) print "Reading input parameters."; sys.stdout.flush() options, param_list = init_params() analyses = make_analyses(param_list) assert analyses assert len(analyses) == len(param_list) # To DEBUG report. #if len(analyses) > 1: # summarize_all_report(options.outpath, analyses, start_time) # To DEBUG summary. #file_layout = make_file_layout(options.outpath, analyses[0].subpath) #summarize_signature_dataset(file_layout) #sys.exit(0) # import modules after init_params, if possible. GenePattern # messes up the PATH variable, so many imports won't work until # init_params fixes it. from genomicode import archive from genomicode import parselib import arrayio print "Setting up a folder for the output files."; sys.stdout.flush() # Should set up a file layout for one of the analyses subpaths. # If I use None, then will create extra directories # (e.g. "binreg") that may not be necessary for a global analysis. file_layout = make_file_layout(options.outpath, analyses[0].subpath) init_paths(file_layout) # Load the files and standardize them to GCT format. print "Reading gene expression matrices."; sys.stdout.flush() # Assume all analyses have the same train0, train1, test, and # normref files. params = analyses[0].params x = read_matrices_all( params.train0_file, params.train1_file, params.test_file, params.normref_file) t0, t1, te, nr, train0, train1, test, normref = x print "train0 file has %s genes and %s samples." % ( tuple(map(parselib.pretty_int, t0.dim()))) print "train1 file has %s genes and %s samples." % ( tuple(map(parselib.pretty_int, t1.dim()))) if te: print "test file has %s genes and %s samples." % ( tuple(map(parselib.pretty_int, te.dim()))) if nr: print "normalization reference file has %s genes and %s samples." % ( tuple(map(parselib.pretty_int, nr.dim()))) print "Merged file has %s genes." % (parselib.pretty_int(train0.nrow())) # Make sure there are enough genes to analyze. num_genes = train0.nrow() for params in param_list: assert params.genes < num_genes, "I cannot analyze with %d genes." % ( params.genes) # Write out the data sets. train0 = arrayio.convert(train0, to_format=arrayio.gct_format) train1 = arrayio.convert(train1, to_format=arrayio.gct_format) if test: test = arrayio.convert(test, to_format=arrayio.gct_format) if normref: normref = arrayio.convert(normref, to_format=arrayio.gct_format) write_dataset(file_layout.DS_ORIG, train0, train1, test) if normref: arrayio.gct_format.write(normref, open(file_layout.NR_ORIG, 'w')) sys.stdout.flush() # Remove the Affymetrix control probes. Do this before any # normalization. if params.strip_affx: x = strip_affx_control_probes(train0, train1, test, normref) train0, train1, test, normref = x # Log normalize each of the files, if necessary. Will log in place. logged = log_matrices( train0, train1, test, normref, params.log_train0, params.log_train1, params.log_test, params.log_normref) if logged: write_dataset(file_layout.DS_LOG, train0, train1, test) # Apply the appropriate normalizations. if params.quantile: quantile_normalize_matrices( train0, train1, test, normref, matlab=options.matlab, binreg_path=options.binreg_path) write_dataset(file_layout.DS_QNORM, train0, train1, test) if normref: arrayio.gct_format.write(normref, open(file_layout.NR_QNORM, 'w')) if params.dwd: dwd_normalize_matrices( train0, train1, test, matlab=options.matlab, dwd_path=options.dwd_path) write_dataset(file_layout.DS_DWD, train0, train1, test) if params.dwd_bild: dwd_normalize_matrices( train0, train1, test, version="bild", matlab=options.matlab, dwd_path=options.dwd_path) write_dataset(file_layout.DS_DWD_BILD, train0, train1, test) if params.shiftscale: shiftscale_normalize_matrices( train0, train1, test, normref, matlab=options.matlab, binreg_path=options.binreg_path) write_dataset(file_layout.DS_SS, train0, train1, test) # Make sure there are no NA's, or BinReg will not do the # predictions correctly. x = filter_missing_values(train0, train1, test, normref) train0, train1, test, normref = x print "Writing processed dataset."; sys.stdout.flush() write_dataset(file_layout.DS_FINAL, train0, train1, test) if normref: arrayio.gct_format.write(normref, open(file_layout.NR_FINAL, 'w')) # Run each of the binreg analyses. for i, analysis in enumerate(analyses): if len(analyses) > 1: print "Running analysis %d of %d." % (i+1, len(analyses)) sys.stdout.flush() run_analysis(analysis, options, train0, train1, test, normref) # If there were multiple analyses specified, make a copy of # some files for convenience. Need to copy it rather than # symlink, in case we archive it later. if len(analyses) > 1: for analysis in analyses: file_layout = make_file_layout(options.outpath, analysis.subpath) files_to_copy = [ (file_layout.PROBABILITIES, file_layout.GLOBAL_PROBABILITIES), (file_layout.PREDICTIONS_PNG, file_layout.GLOBAL_PREDICTIONS_PNG), (file_layout.SIGNATURE_PNG, file_layout.GLOBAL_SIGNATURE_PNG), ] for src, dst in files_to_copy: assert os.path.exists(src) os.system("cp -p '%s' '%s'" % (src, dst)) if analysis.params.archive: archive.zip_path(file_layout.ANALYSIS) summarize_all_report(options.outpath, analyses, start_time) # Assume all archive options are the same. params = analyses[0].params if params.archive: print "Compressing results."; sys.stdout.flush() file_layout = make_file_layout(options.outpath, analyses[0].subpath) if os.path.exists(file_layout.BINREG): archive.zip_path(file_layout.BINREG) if os.path.exists(file_layout.ATTIC): archive.zip_path(file_layout.ATTIC) if os.path.exists(file_layout.GLOBAL_ATTIC): archive.zip_path(file_layout.GLOBAL_ATTIC) #make_FILES(files) x = time.strftime("%A, %d %B %Y, %I:%M %p", time.localtime()) print "Finished pybinreg.py analysis on %s." % x if __name__ == '__main__': #import sys #print "Running python: %s" % sys.executable main() #import profile; profile.run("main()")
{ "content_hash": "1ca92e747129262a7153bd70f78600bf", "timestamp": "", "source": "github", "line_count": 2009, "max_line_length": 79, "avg_line_length": 36.038327526132406, "alnum_prop": 0.6097429593513902, "repo_name": "jefftc/changlab", "id": "061d5f287d658158faed6d68b7d629fec60e991a", "size": "72424", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/pybinreg.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "116953" }, { "name": "CSS", "bytes": "75418" }, { "name": "Groff", "bytes": "10237" }, { "name": "HTML", "bytes": "200459" }, { "name": "JavaScript", "bytes": "159618" }, { "name": "Makefile", "bytes": "11719" }, { "name": "Python", "bytes": "9300228" }, { "name": "R", "bytes": "94670" }, { "name": "Shell", "bytes": "63514" }, { "name": "TeX", "bytes": "64" } ], "symlink_target": "" }
<?xml version="1.0"?> <package format="2"> <name>igvc_sandbox</name> <version>0.0.0</version> <description>The RoboJackets' IGVC code base</description> <maintainer email="mhannay3@gatech.edu">Matthew Hannay</maintainer> <license>MIT</license> <author email="matthew.barulic@gmail.com">Matthew Barulic</author> <author email="chaussee.al@gmail.com">Al Chaussee</author> <url type="website">http://www.robojackets.org</url> <url type="website">http://www.github.com/robojackets/igvc-software</url> <url type="website">http://robojackets.github.io/igvc-software</url> <url type="website">http://www.noruts.com</url> </package>
{ "content_hash": "0b07560450b120cc31e4123803a1f467", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 75, "avg_line_length": 34.31578947368421, "alnum_prop": 0.7147239263803681, "repo_name": "RoboJackets/igvc-software", "id": "fe13a44cfb14889b4c3d8da2c0174722d8493950", "size": "652", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "igvc_sandbox/package.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "128580" }, { "name": "C++", "bytes": "541208" }, { "name": "CMake", "bytes": "52931" }, { "name": "Dockerfile", "bytes": "681" }, { "name": "Makefile", "bytes": "310" }, { "name": "Python", "bytes": "91108" }, { "name": "Shell", "bytes": "4496" } ], "symlink_target": "" }
<mat-table #table [dataSource]="dataSource"> <ng-container matColumnDef="number"> <mat-header-cell *matHeaderCellDef [ngClass]="'flex75'"> N° </mat-header-cell> <mat-cell *matCellDef="let element" [ngClass]="'flex75'"> {{element.movementNumber}} </mat-cell> </ng-container> <ng-container matColumnDef="date"> <mat-header-cell *matHeaderCellDef [innerHTML]="'Date' | translate"></mat-header-cell> <mat-cell *matCellDef="let element"> {{element.movementDate | date:'yyyy-MM-dd'}} </mat-cell> </ng-container> <ng-container matColumnDef="amount"> <mat-header-cell *matHeaderCellDef [ngClass]="'flex100Right'" [innerHTML]="'Amount' | translate"></mat-header-cell> <mat-cell *matCellDef="let element" [ngClass]="'flex100Right'"> {{element.movementAmount | currencyFormat}} </mat-cell> </ng-container> <ng-container matColumnDef="payment"> <mat-header-cell *matHeaderCellDef [ngClass]="'flex100Center'" [innerHTML]="'Payment' | translate"></mat-header-cell> <mat-cell *matCellDef="let element" [ngClass]="'flex100Center'"> {{element.movementPayment}} </mat-cell> </ng-container> <ng-container matColumnDef="status"> <mat-header-cell *matHeaderCellDef [innerHTML]="'Status' | translate"></mat-header-cell> <mat-cell *matCellDef="let element"> {{element.movementStatus}} </mat-cell> </ng-container> <ng-container matColumnDef="doc"> <mat-header-cell *matHeaderCellDef [ngClass]="'fix100Center'"></mat-header-cell> <mat-cell *matCellDef="let element" [ngClass]="'fix100Center'"> <button mat-button routerLink="/document/{{element.movementId}}"><mat-icon>picture_as_pdf</mat-icon></button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
{ "content_hash": "7ad47301cb89db422e56565af0337505", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 127, "avg_line_length": 52.567567567567565, "alnum_prop": 0.662210796915167, "repo_name": "gerardogrisolini/Webretail", "id": "ae61a3e7c47fd31bd624096a00a6de9215768929", "size": "1946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebUI/src/app/order/app.orders.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20920" }, { "name": "Dockerfile", "bytes": "944" }, { "name": "HTML", "bytes": "248464" }, { "name": "JavaScript", "bytes": "4341" }, { "name": "Swift", "bytes": "410687" }, { "name": "TypeScript", "bytes": "353858" } ], "symlink_target": "" }
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'filter'}) export class searchPipe implements PipeTransform { item:any; transform(items:any, filter:any) { if(filter) { return items.filter(itemc); function itemc(item:any) { for (let key in item) { if ((typeof item[key] === 'string' || item[key] instanceof String) && (item[key].toString().toLowerCase().indexOf(filter.toString().toLowerCase()) !== -1)) { return true; } } } } return items; } // /let item :string; //todo.fname.indexOf(filter)!==-1 /*return value.filter(item =>{ for(let key in item){ if((typeof item[key]==='string' || item[key] instanceof String) && (item[key].indexOf(args[0])!==1)){ return true; } } });*/ //} }
{ "content_hash": "1aad2a52f9daae2712f2ce4bd3fb20c1", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 115, "avg_line_length": 31.757575757575758, "alnum_prop": 0.44274809160305345, "repo_name": "debasiskar-devel-007/angular2ts", "id": "d968c73a180159b9143e33d5176a3b5c205cd50b", "size": "1048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/services/search.pipe.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "496" }, { "name": "CSS", "bytes": "906319" }, { "name": "HTML", "bytes": "1417809" }, { "name": "JavaScript", "bytes": "19138" }, { "name": "TypeScript", "bytes": "790227" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.8.10 - v0.8.12: v8::ExtensionConfiguration Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.8.10 - v0.8.12 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_extension_configuration.html">ExtensionConfiguration</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#friends">Friends</a> &#124; <a href="classv8_1_1_extension_configuration-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::ExtensionConfiguration Class Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="v8_8h_source.html">v8.h</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a1189e46efe963db4aa7340cc767f276a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1189e46efe963db4aa7340cc767f276a"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>ExtensionConfiguration</b> (int name_count, const char *names[])</td></tr> <tr class="separator:a1189e46efe963db4aa7340cc767f276a"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a> Friends</h2></td></tr> <tr class="memitem:ac7b520085953e146d849e05253267f72"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac7b520085953e146d849e05253267f72"></a> class&#160;</td><td class="memItemRight" valign="bottom"><b>ImplementationUtilities</b></td></tr> <tr class="separator:ac7b520085953e146d849e05253267f72"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Ignore </p> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:48:22 for V8 API Reference Guide for node.js v0.8.10 - v0.8.12 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "dec4d94de612594b0ca989fbe5272060", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 189, "avg_line_length": 47.574803149606296, "alnum_prop": 0.6638530287984111, "repo_name": "v8-dox/v8-dox.github.io", "id": "a5e5bcc0dbb886ffecb3f592245956fec3563385", "size": "6042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "4165f73/html/classv8_1_1_extension_configuration.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package nl.eernie.as; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import nl.eernie.as.application_server.ApplicationServer; import nl.eernie.as.configuration.Configuration; import nl.eernie.as.parsers.ConfigurationParser; import nl.eernie.as.parsers.DefaultJbossParser; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.mockito.internal.util.reflection.Whitebox; public class ASConfigCreatorTest { @Test public void testInitialization() { Configuration configuration = new Configuration(); configuration.getApplicationServers().add(ApplicationServer.WILDFLY); ASConfigCreator creator = new ASConfigCreator(configuration); @SuppressWarnings("unchecked") Map<ApplicationServer, Set<ConfigurationParser>> configurationParsers = (Map<ApplicationServer, Set<ConfigurationParser>>) Whitebox.getInternalState(creator, "configurationParsers"); assertTrue(configurationParsers.containsKey(ApplicationServer.WILDFLY)); assertTrue(configurationParsers.containsKey(null)); assertTrue(configurationParsers.get(ApplicationServer.WILDFLY).iterator().next() instanceof DefaultJbossParser); } @Test public void testInclude() throws IOException { Path outputDirectory = Files.createTempDirectory("asConfig"); Configuration configuration = new Configuration(); configuration.getApplicationServers().add(ApplicationServer.WILDFLY); configuration.getContexts().add("core"); configuration.setOutputDirectoryPath(outputDirectory.toFile()); ASConfigCreator creator = new ASConfigCreator(configuration); creator.createConfigFiles(getClass().getResource("/includeFiles/master.xml").getPath()); String outputFile = outputDirectory.toString() + "/wildfly.cli"; List<String> expected = Arrays.asList("batch", "/system-property=property:add(value=property)", "run-batch", "batch", "/system-property=property:add(value=property)", "run-batch"); List<String> actual = Files.readAllLines(Paths.get(outputFile), Charset.defaultCharset()); List<String> filteredActual = filterActual(actual); assertEquals(expected, filteredActual); } @Test public void testTags() throws IOException { Path outputDirectory = Files.createTempDirectory("asConfig"); Configuration configuration = new Configuration(); configuration.getApplicationServers().add(ApplicationServer.WILDFLY); configuration.getContexts().add("core"); configuration.setFromTag("1.0.0"); configuration.setToTag("1.0.1"); configuration.setOutputDirectoryPath(outputDirectory.toFile()); ASConfigCreator creator = new ASConfigCreator(configuration); creator.createConfigFiles(getClass().getResource("/tags.xml").getPath()); String outputFile = outputDirectory.toString() + "/wildfly.cli"; List<String> expected = Arrays.asList("batch", "/system-property=property that will be processed:add(value=value)", "run-batch"); List<String> actual = Files.readAllLines(Paths.get(outputFile), Charset.defaultCharset()); List<String> filteredActual = filterActual(actual); assertEquals(expected, filteredActual); } private List<String> filterActual(List<String> actual) { List<String> filtered = new ArrayList<>(actual.size()); for (String s : actual) { if (!s.startsWith("##") && StringUtils.isNotBlank(s)) { filtered.add(s); } } return filtered; } @Test public void testApplicationServer() throws IOException { Path outputDirectory = Files.createTempDirectory("asConfig"); Configuration configuration = new Configuration(); configuration.getApplicationServers().add(ApplicationServer.WILDFLY); configuration.getContexts().add("core"); configuration.setOutputDirectoryPath(outputDirectory.toFile()); ASConfigCreator creator = new ASConfigCreator(configuration); creator.createConfigFiles(getClass().getResource("/applicationServer.xml").getPath()); String outputFile = outputDirectory.toString() + "/wildfly.cli"; List<String> expected = Arrays.asList("batch", "/system-property=property that will be processed:add(value=value)", "run-batch","batch", "/system-property=property that will be processed:add(value=value)", "run-batch"); List<String> actual = Files.readAllLines(Paths.get(outputFile), Charset.defaultCharset()); List<String> filteredActual = filterActual(actual); assertEquals(expected, filteredActual); } }
{ "content_hash": "d4274158e31fc2e208e6d0ba0f78133f", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 221, "avg_line_length": 38.516666666666666, "alnum_prop": 0.7771527477282562, "repo_name": "Eernie/ASConfigCreator", "id": "85972d99d248d2b5620d6207235b0c5b0eb7e7d1", "size": "4622", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "core/src/test/java/nl/eernie/as/ASConfigCreatorTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "117999" } ], "symlink_target": "" }
<?php require_once '../../bootstrap.php'; use Pop\Code; try { // Create the code generator object $code = new Code\Generator('code.php'); $code->setBody("// Let's get some stuff to happen here." . PHP_EOL . "\$blah = 'Sounds like a good idea';") ->appendToBody("echo \$blah;", false) ->setClose(true); // Render and output the code $code->output(); } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL . PHP_EOL; }
{ "content_hash": "6b29693dedec889f3e647e346f825884", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 111, "avg_line_length": 25.88888888888889, "alnum_prop": 0.5858369098712446, "repo_name": "nicksagona/PopPHP", "id": "4824fbc150e3928259b6be88d08f84d5e2a204ad", "size": "466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/examples/code/code.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "235" }, { "name": "Batchfile", "bytes": "820" }, { "name": "HTML", "bytes": "3861" }, { "name": "PHP", "bytes": "105810" }, { "name": "Shell", "bytes": "1044" } ], "symlink_target": "" }
Mac OS X thepandacoind build instructions ==================================== Authors ------- * Laszlo Hanyecz <solar@heliacal.net> * Douglas Huff <dhuff@jrbobdobbs.org> * Colin Dean <cad@cad.cx> * Gavin Andresen <gavinandresen@gmail.com> License ------- Copyright (c) 2009-2012 Bitcoin Developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/). This product includes cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard. Notes ----- See `doc/readme-qt.rst` for instructions on building ThePandacoin-Qt, the graphical user interface. Tested on OS X 10.5 through 10.8 on Intel processors only. PPC is not supported because it is big-endian. All of the commands should be executed in a Terminal application. The built-in one is located in `/Applications/Utilities`. Preparation ----------- You need to install XCode with all the options checked so that the compiler and everything is available in /usr not just /Developer. XCode should be available on your OS X installation media, but if not, you can get the current version from https://developer.apple.com/xcode/. If you install Xcode 4.3 or later, you'll need to install its command line tools. This can be done in `Xcode > Preferences > Downloads > Components` and generally must be re-done or updated every time Xcode is updated. There's an assumption that you already have `git` installed, as well. If not, it's the path of least resistance to install [Github for Mac](https://mac.github.com/) (OS X 10.7+) or [Git for OS X](https://code.google.com/p/git-osx-installer/). It is also available via Homebrew or MacPorts. You will also need to install [Homebrew](http://mxcl.github.io/homebrew/) or [MacPorts](https://www.macports.org/) in order to install library dependencies. It's largely a religious decision which to choose, but, as of December 2012, MacPorts is a little easier because you can just install the dependencies immediately - no other work required. If you're unsure, read the instructions through first in order to assess what you want to do. Homebrew is a little more popular among those newer to OS X. The installation of the actual dependencies is covered in the Instructions sections below. Instructions: MacPorts ---------------------- ### Install dependencies Installing the dependencies using MacPorts is very straightforward. sudo port install boost db48@+no_java openssl miniupnpc ### Building `thepandacoind` 1. Clone the github tree to get the source code and go into the directory. git clone git@github.com:thepandacoin/thepandacoin.git thepandacoin cd thepandacoin 2. Build thepandacoind: cd src make -f makefile.osx 3. It is a good idea to build and run the unit tests, too: make -f makefile.osx test Instructions: HomeBrew ---------------------- #### Install dependencies using Homebrew brew install boost miniupnpc openssl berkeley-db4 Note: After you have installed the dependencies, you should check that the Brew installed version of OpenSSL is the one available for compilation. You can check this by typing openssl version into Terminal. You should see OpenSSL 1.0.1e 11 Feb 2013. If not, you can ensure that the Brew OpenSSL is correctly linked by running brew link openssl --force Rerunning "openssl version" should now return the correct version. ### Building `thepandacoind` 1. Clone the github tree to get the source code and go into the directory. git clone git@github.com:thepandacoin/thepandacoin.git thepandacoin cd thepandacoin 2. Modify source in order to pick up the `openssl` library. Edit `makefile.osx` to account for library location differences. There's a diff in `contrib/homebrew/makefile.osx.patch` that shows what you need to change, or you can just patch by doing patch -p1 < contrib/homebrew/makefile.osx.patch 3. Build thepandacoind: cd src make -f makefile.osx 4. It is a good idea to build and run the unit tests, too: make -f makefile.osx test Creating a release build ------------------------ A thepandacoind binary is not included in the ThePandacoin-Qt.app bundle. You can ignore this section if you are building `thepandacoind` for your own use. If you are building `litecond` for others, your build machine should be set up as follows for maximum compatibility: All dependencies should be compiled with these flags: -mmacosx-version-min=10.5 -arch i386 -isysroot /Developer/SDKs/MacOSX10.5.sdk For MacPorts, that means editing your macports.conf and setting `macosx_deployment_target` and `build_arch`: macosx_deployment_target=10.5 build_arch=i386 ... and then uninstalling and re-installing, or simply rebuilding, all ports. As of December 2012, the `boost` port does not obey `macosx_deployment_target`. Download `http://gavinandresen-bitcoin.s3.amazonaws.com/boost_macports_fix.zip` for a fix. Some ports also seem to obey either `build_arch` or `macosx_deployment_target`, but not both at the same time. For example, building on an OS X 10.6 64-bit machine fails. Official release builds of ThePandacoin-Qt are compiled on an OS X 10.6 32-bit machine to workaround that problem. Once dependencies are compiled, creating `ThePandacoin-Qt.app` is easy: make -f Makefile.osx RELEASE=1 Running ------- It's now available at `./thepandacoind`, provided that you are still in the `src` directory. We have to first create the RPC configuration file, though. Run `./thepandacoind` to get the filename where it should be put, or just try these commands: echo -e "rpcuser=thepandacoinrpc\nrpcpassword=$(xxd -l 16 -p /dev/urandom)" > "/Users/${USER}/Library/Application Support/ThePandacoin/thepandacoin.conf" chmod 600 "/Users/${USER}/Library/Application Support/ThePandacoin/thepandacoin.conf" When next you run it, it will start downloading the blockchain, but it won't output anything while it's doing this. This process may take several hours. Other commands: ./thepandacoind --help # for a list of command-line options. ./thepandacoind -daemon # to start the thepandacoin daemon. ./thepandacoind help # When the daemon is running, to get a list of RPC commands
{ "content_hash": "975f6b6df336861bfb7df75967dffdb3", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 175, "avg_line_length": 35.08108108108108, "alnum_prop": 0.7432973805855162, "repo_name": "chaosagent/pandacoin", "id": "9971c112b170f80711eaaca1a03eaa08a8d4381b", "size": "6490", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/build-osx.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "102879" }, { "name": "C++", "bytes": "2536494" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14707" }, { "name": "Objective-C", "bytes": "5864" }, { "name": "Python", "bytes": "37275" }, { "name": "Shell", "bytes": "9775" }, { "name": "TypeScript", "bytes": "5253196" } ], "symlink_target": "" }
<?php /** * Base class that represents a query for the 'abnorm' table. * * * * @method AbnormQuery orderByAutoctr($order = Criteria::ASC) Order by the AutoCtr column * @method AbnormQuery orderByFamily($order = Criteria::ASC) Order by the Family column * @method AbnormQuery orderByGenus($order = Criteria::ASC) Order by the Genus column * @method AbnormQuery orderBySpecies($order = Criteria::ASC) Order by the Species column * @method AbnormQuery orderByCommonname($order = Criteria::ASC) Order by the CommonName column * @method AbnormQuery orderBySpeccode($order = Criteria::ASC) Order by the SpecCode column * @method AbnormQuery orderByStockcode($order = Criteria::ASC) Order by the StockCode column * @method AbnormQuery orderByLifestage($order = Criteria::ASC) Order by the LifeStage column * @method AbnormQuery orderByLocation($order = Criteria::ASC) Order by the Location column * @method AbnormQuery orderBySeason($order = Criteria::ASC) Order by the Season column * @method AbnormQuery orderByAbnormalitydisease($order = Criteria::ASC) Order by the AbnormalityDisease column * @method AbnormQuery orderByPrevalence($order = Criteria::ASC) Order by the Prevalence column * @method AbnormQuery orderByStressor($order = Criteria::ASC) Order by the Stressor column * @method AbnormQuery orderByLabfield($order = Criteria::ASC) Order by the LabField column * @method AbnormQuery orderByConcentration($order = Criteria::ASC) Order by the Concentration column * @method AbnormQuery orderByAbnormrefno($order = Criteria::ASC) Order by the ABNORMRefNo column * @method AbnormQuery orderBySecondrefno($order = Criteria::ASC) Order by the SecondRefNo column * @method AbnormQuery orderByNotes($order = Criteria::ASC) Order by the Notes column * @method AbnormQuery orderByEntered($order = Criteria::ASC) Order by the Entered column * @method AbnormQuery orderByDateentered($order = Criteria::ASC) Order by the DateEntered column * @method AbnormQuery orderByModified($order = Criteria::ASC) Order by the Modified column * @method AbnormQuery orderByDatemodified($order = Criteria::ASC) Order by the DateModified column * @method AbnormQuery orderByExpert($order = Criteria::ASC) Order by the Expert column * @method AbnormQuery orderByDatechecked($order = Criteria::ASC) Order by the DateChecked column * @method AbnormQuery orderByTs($order = Criteria::ASC) Order by the TS column * * @method AbnormQuery groupByAutoctr() Group by the AutoCtr column * @method AbnormQuery groupByFamily() Group by the Family column * @method AbnormQuery groupByGenus() Group by the Genus column * @method AbnormQuery groupBySpecies() Group by the Species column * @method AbnormQuery groupByCommonname() Group by the CommonName column * @method AbnormQuery groupBySpeccode() Group by the SpecCode column * @method AbnormQuery groupByStockcode() Group by the StockCode column * @method AbnormQuery groupByLifestage() Group by the LifeStage column * @method AbnormQuery groupByLocation() Group by the Location column * @method AbnormQuery groupBySeason() Group by the Season column * @method AbnormQuery groupByAbnormalitydisease() Group by the AbnormalityDisease column * @method AbnormQuery groupByPrevalence() Group by the Prevalence column * @method AbnormQuery groupByStressor() Group by the Stressor column * @method AbnormQuery groupByLabfield() Group by the LabField column * @method AbnormQuery groupByConcentration() Group by the Concentration column * @method AbnormQuery groupByAbnormrefno() Group by the ABNORMRefNo column * @method AbnormQuery groupBySecondrefno() Group by the SecondRefNo column * @method AbnormQuery groupByNotes() Group by the Notes column * @method AbnormQuery groupByEntered() Group by the Entered column * @method AbnormQuery groupByDateentered() Group by the DateEntered column * @method AbnormQuery groupByModified() Group by the Modified column * @method AbnormQuery groupByDatemodified() Group by the DateModified column * @method AbnormQuery groupByExpert() Group by the Expert column * @method AbnormQuery groupByDatechecked() Group by the DateChecked column * @method AbnormQuery groupByTs() Group by the TS column * * @method AbnormQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method AbnormQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query * @method AbnormQuery innerJoin($relation) Adds a INNER JOIN clause to the query * * @method Abnorm findOne(PropelPDO $con = null) Return the first Abnorm matching the query * @method Abnorm findOneOrCreate(PropelPDO $con = null) Return the first Abnorm matching the query, or a new Abnorm object populated from the query conditions when no match is found * * @method Abnorm findOneByFamily(string $Family) Return the first Abnorm filtered by the Family column * @method Abnorm findOneByGenus(string $Genus) Return the first Abnorm filtered by the Genus column * @method Abnorm findOneBySpecies(string $Species) Return the first Abnorm filtered by the Species column * @method Abnorm findOneByCommonname(string $CommonName) Return the first Abnorm filtered by the CommonName column * @method Abnorm findOneBySpeccode(int $SpecCode) Return the first Abnorm filtered by the SpecCode column * @method Abnorm findOneByStockcode(int $StockCode) Return the first Abnorm filtered by the StockCode column * @method Abnorm findOneByLifestage(string $LifeStage) Return the first Abnorm filtered by the LifeStage column * @method Abnorm findOneByLocation(string $Location) Return the first Abnorm filtered by the Location column * @method Abnorm findOneBySeason(string $Season) Return the first Abnorm filtered by the Season column * @method Abnorm findOneByAbnormalitydisease(string $AbnormalityDisease) Return the first Abnorm filtered by the AbnormalityDisease column * @method Abnorm findOneByPrevalence(string $Prevalence) Return the first Abnorm filtered by the Prevalence column * @method Abnorm findOneByStressor(string $Stressor) Return the first Abnorm filtered by the Stressor column * @method Abnorm findOneByLabfield(string $LabField) Return the first Abnorm filtered by the LabField column * @method Abnorm findOneByConcentration(string $Concentration) Return the first Abnorm filtered by the Concentration column * @method Abnorm findOneByAbnormrefno(int $ABNORMRefNo) Return the first Abnorm filtered by the ABNORMRefNo column * @method Abnorm findOneBySecondrefno(int $SecondRefNo) Return the first Abnorm filtered by the SecondRefNo column * @method Abnorm findOneByNotes(string $Notes) Return the first Abnorm filtered by the Notes column * @method Abnorm findOneByEntered(int $Entered) Return the first Abnorm filtered by the Entered column * @method Abnorm findOneByDateentered(string $DateEntered) Return the first Abnorm filtered by the DateEntered column * @method Abnorm findOneByModified(int $Modified) Return the first Abnorm filtered by the Modified column * @method Abnorm findOneByDatemodified(string $DateModified) Return the first Abnorm filtered by the DateModified column * @method Abnorm findOneByExpert(int $Expert) Return the first Abnorm filtered by the Expert column * @method Abnorm findOneByDatechecked(string $DateChecked) Return the first Abnorm filtered by the DateChecked column * @method Abnorm findOneByTs(string $TS) Return the first Abnorm filtered by the TS column * * @method array findByAutoctr(int $AutoCtr) Return Abnorm objects filtered by the AutoCtr column * @method array findByFamily(string $Family) Return Abnorm objects filtered by the Family column * @method array findByGenus(string $Genus) Return Abnorm objects filtered by the Genus column * @method array findBySpecies(string $Species) Return Abnorm objects filtered by the Species column * @method array findByCommonname(string $CommonName) Return Abnorm objects filtered by the CommonName column * @method array findBySpeccode(int $SpecCode) Return Abnorm objects filtered by the SpecCode column * @method array findByStockcode(int $StockCode) Return Abnorm objects filtered by the StockCode column * @method array findByLifestage(string $LifeStage) Return Abnorm objects filtered by the LifeStage column * @method array findByLocation(string $Location) Return Abnorm objects filtered by the Location column * @method array findBySeason(string $Season) Return Abnorm objects filtered by the Season column * @method array findByAbnormalitydisease(string $AbnormalityDisease) Return Abnorm objects filtered by the AbnormalityDisease column * @method array findByPrevalence(string $Prevalence) Return Abnorm objects filtered by the Prevalence column * @method array findByStressor(string $Stressor) Return Abnorm objects filtered by the Stressor column * @method array findByLabfield(string $LabField) Return Abnorm objects filtered by the LabField column * @method array findByConcentration(string $Concentration) Return Abnorm objects filtered by the Concentration column * @method array findByAbnormrefno(int $ABNORMRefNo) Return Abnorm objects filtered by the ABNORMRefNo column * @method array findBySecondrefno(int $SecondRefNo) Return Abnorm objects filtered by the SecondRefNo column * @method array findByNotes(string $Notes) Return Abnorm objects filtered by the Notes column * @method array findByEntered(int $Entered) Return Abnorm objects filtered by the Entered column * @method array findByDateentered(string $DateEntered) Return Abnorm objects filtered by the DateEntered column * @method array findByModified(int $Modified) Return Abnorm objects filtered by the Modified column * @method array findByDatemodified(string $DateModified) Return Abnorm objects filtered by the DateModified column * @method array findByExpert(int $Expert) Return Abnorm objects filtered by the Expert column * @method array findByDatechecked(string $DateChecked) Return Abnorm objects filtered by the DateChecked column * @method array findByTs(string $TS) Return Abnorm objects filtered by the TS column * * @package propel.generator.fbapp.om */ abstract class BaseAbnormQuery extends ModelCriteria { /** * Initializes internal state of BaseAbnormQuery object. * * @param string $dbName The dabase name * @param string $modelName The phpName of a model, e.g. 'Book' * @param string $modelAlias The alias for the model in this query, e.g. 'b' */ public function __construct($dbName = null, $modelName = null, $modelAlias = null) { if (null === $dbName) { $dbName = 'fbapp'; } if (null === $modelName) { $modelName = 'Abnorm'; } parent::__construct($dbName, $modelName, $modelAlias); } /** * Returns a new AbnormQuery object. * * @param string $modelAlias The alias of a model in the query * @param AbnormQuery|Criteria $criteria Optional Criteria to build the query from * * @return AbnormQuery */ public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof AbnormQuery) { return $criteria; } $query = new AbnormQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; } /** * Find object by primary key. * Propel uses the instance pool to skip the database if the object exists. * Go fast if the query is untouched. * * <code> * $obj = $c->findPk(12, $con); * </code> * * @param mixed $key Primary key to use for the query * @param PropelPDO $con an optional connection object * * @return Abnorm|Abnorm[]|mixed the result, formatted by the current formatter */ public function findPk($key, $con = null) { if ($key === null) { return null; } if ((null !== ($obj = AbnormPeer::getInstanceFromPool((string) $key))) && !$this->formatter) { // the object is already in the instance pool return $obj; } if ($con === null) { $con = Propel::getConnection(AbnormPeer::DATABASE_NAME, Propel::CONNECTION_READ); } $this->basePreSelect($con); if ($this->formatter || $this->modelAlias || $this->with || $this->select || $this->selectColumns || $this->asColumns || $this->selectModifiers || $this->map || $this->having || $this->joins) { return $this->findPkComplex($key, $con); } else { return $this->findPkSimple($key, $con); } } /** * Alias of findPk to use instance pooling * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return Abnorm A model object, or null if the key is not found * @throws PropelException */ public function findOneByAutoctr($key, $con = null) { return $this->findPk($key, $con); } /** * Find object by primary key using raw SQL to go fast. * Bypass doSelect() and the object formatter by using generated code. * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return Abnorm A model object, or null if the key is not found * @throws PropelException */ protected function findPkSimple($key, $con) { $sql = 'SELECT `AutoCtr`, `Family`, `Genus`, `Species`, `CommonName`, `SpecCode`, `StockCode`, `LifeStage`, `Location`, `Season`, `AbnormalityDisease`, `Prevalence`, `Stressor`, `LabField`, `Concentration`, `ABNORMRefNo`, `SecondRefNo`, `Notes`, `Entered`, `DateEntered`, `Modified`, `DateModified`, `Expert`, `DateChecked`, `TS` FROM `abnorm` WHERE `AutoCtr` = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e); } $obj = null; if ($row = $stmt->fetch(PDO::FETCH_NUM)) { $obj = new Abnorm(); $obj->hydrate($row); AbnormPeer::addInstanceToPool($obj, (string) $key); } $stmt->closeCursor(); return $obj; } /** * Find object by primary key. * * @param mixed $key Primary key to use for the query * @param PropelPDO $con A connection object * * @return Abnorm|Abnorm[]|mixed the result, formatted by the current formatter */ protected function findPkComplex($key, $con) { // As the query uses a PK condition, no limit(1) is necessary. $criteria = $this->isKeepQuery() ? clone $this : $this; $stmt = $criteria ->filterByPrimaryKey($key) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->formatOne($stmt); } /** * Find objects by primary key * <code> * $objs = $c->findPks(array(12, 56, 832), $con); * </code> * @param array $keys Primary keys to use for the query * @param PropelPDO $con an optional connection object * * @return PropelObjectCollection|Abnorm[]|mixed the list of results, formatted by the current formatter */ public function findPks($keys, $con = null) { if ($con === null) { $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ); } $this->basePreSelect($con); $criteria = $this->isKeepQuery() ? clone $this : $this; $stmt = $criteria ->filterByPrimaryKeys($keys) ->doSelect($con); return $criteria->getFormatter()->init($criteria)->format($stmt); } /** * Filter the query by primary key * * @param mixed $key Primary key to use for the query * * @return AbnormQuery The current query, for fluid interface */ public function filterByPrimaryKey($key) { return $this->addUsingAlias(AbnormPeer::AUTOCTR, $key, Criteria::EQUAL); } /** * Filter the query by a list of primary keys * * @param array $keys The list of primary key to use for the query * * @return AbnormQuery The current query, for fluid interface */ public function filterByPrimaryKeys($keys) { return $this->addUsingAlias(AbnormPeer::AUTOCTR, $keys, Criteria::IN); } /** * Filter the query on the AutoCtr column * * Example usage: * <code> * $query->filterByAutoctr(1234); // WHERE AutoCtr = 1234 * $query->filterByAutoctr(array(12, 34)); // WHERE AutoCtr IN (12, 34) * $query->filterByAutoctr(array('min' => 12)); // WHERE AutoCtr >= 12 * $query->filterByAutoctr(array('max' => 12)); // WHERE AutoCtr <= 12 * </code> * * @param mixed $autoctr The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByAutoctr($autoctr = null, $comparison = null) { if (is_array($autoctr)) { $useMinMax = false; if (isset($autoctr['min'])) { $this->addUsingAlias(AbnormPeer::AUTOCTR, $autoctr['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($autoctr['max'])) { $this->addUsingAlias(AbnormPeer::AUTOCTR, $autoctr['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::AUTOCTR, $autoctr, $comparison); } /** * Filter the query on the Family column * * Example usage: * <code> * $query->filterByFamily('fooValue'); // WHERE Family = 'fooValue' * $query->filterByFamily('%fooValue%'); // WHERE Family LIKE '%fooValue%' * </code> * * @param string $family The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByFamily($family = null, $comparison = null) { if (null === $comparison) { if (is_array($family)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $family)) { $family = str_replace('*', '%', $family); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::FAMILY, $family, $comparison); } /** * Filter the query on the Genus column * * Example usage: * <code> * $query->filterByGenus('fooValue'); // WHERE Genus = 'fooValue' * $query->filterByGenus('%fooValue%'); // WHERE Genus LIKE '%fooValue%' * </code> * * @param string $genus The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByGenus($genus = null, $comparison = null) { if (null === $comparison) { if (is_array($genus)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $genus)) { $genus = str_replace('*', '%', $genus); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::GENUS, $genus, $comparison); } /** * Filter the query on the Species column * * Example usage: * <code> * $query->filterBySpecies('fooValue'); // WHERE Species = 'fooValue' * $query->filterBySpecies('%fooValue%'); // WHERE Species LIKE '%fooValue%' * </code> * * @param string $species The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterBySpecies($species = null, $comparison = null) { if (null === $comparison) { if (is_array($species)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $species)) { $species = str_replace('*', '%', $species); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::SPECIES, $species, $comparison); } /** * Filter the query on the CommonName column * * Example usage: * <code> * $query->filterByCommonname('fooValue'); // WHERE CommonName = 'fooValue' * $query->filterByCommonname('%fooValue%'); // WHERE CommonName LIKE '%fooValue%' * </code> * * @param string $commonname The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByCommonname($commonname = null, $comparison = null) { if (null === $comparison) { if (is_array($commonname)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $commonname)) { $commonname = str_replace('*', '%', $commonname); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::COMMONNAME, $commonname, $comparison); } /** * Filter the query on the SpecCode column * * Example usage: * <code> * $query->filterBySpeccode(1234); // WHERE SpecCode = 1234 * $query->filterBySpeccode(array(12, 34)); // WHERE SpecCode IN (12, 34) * $query->filterBySpeccode(array('min' => 12)); // WHERE SpecCode >= 12 * $query->filterBySpeccode(array('max' => 12)); // WHERE SpecCode <= 12 * </code> * * @param mixed $speccode The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterBySpeccode($speccode = null, $comparison = null) { if (is_array($speccode)) { $useMinMax = false; if (isset($speccode['min'])) { $this->addUsingAlias(AbnormPeer::SPECCODE, $speccode['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($speccode['max'])) { $this->addUsingAlias(AbnormPeer::SPECCODE, $speccode['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::SPECCODE, $speccode, $comparison); } /** * Filter the query on the StockCode column * * Example usage: * <code> * $query->filterByStockcode(1234); // WHERE StockCode = 1234 * $query->filterByStockcode(array(12, 34)); // WHERE StockCode IN (12, 34) * $query->filterByStockcode(array('min' => 12)); // WHERE StockCode >= 12 * $query->filterByStockcode(array('max' => 12)); // WHERE StockCode <= 12 * </code> * * @param mixed $stockcode The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByStockcode($stockcode = null, $comparison = null) { if (is_array($stockcode)) { $useMinMax = false; if (isset($stockcode['min'])) { $this->addUsingAlias(AbnormPeer::STOCKCODE, $stockcode['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($stockcode['max'])) { $this->addUsingAlias(AbnormPeer::STOCKCODE, $stockcode['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::STOCKCODE, $stockcode, $comparison); } /** * Filter the query on the LifeStage column * * Example usage: * <code> * $query->filterByLifestage('fooValue'); // WHERE LifeStage = 'fooValue' * $query->filterByLifestage('%fooValue%'); // WHERE LifeStage LIKE '%fooValue%' * </code> * * @param string $lifestage The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByLifestage($lifestage = null, $comparison = null) { if (null === $comparison) { if (is_array($lifestage)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $lifestage)) { $lifestage = str_replace('*', '%', $lifestage); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::LIFESTAGE, $lifestage, $comparison); } /** * Filter the query on the Location column * * Example usage: * <code> * $query->filterByLocation('fooValue'); // WHERE Location = 'fooValue' * $query->filterByLocation('%fooValue%'); // WHERE Location LIKE '%fooValue%' * </code> * * @param string $location The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByLocation($location = null, $comparison = null) { if (null === $comparison) { if (is_array($location)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $location)) { $location = str_replace('*', '%', $location); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::LOCATION, $location, $comparison); } /** * Filter the query on the Season column * * Example usage: * <code> * $query->filterBySeason('fooValue'); // WHERE Season = 'fooValue' * $query->filterBySeason('%fooValue%'); // WHERE Season LIKE '%fooValue%' * </code> * * @param string $season The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterBySeason($season = null, $comparison = null) { if (null === $comparison) { if (is_array($season)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $season)) { $season = str_replace('*', '%', $season); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::SEASON, $season, $comparison); } /** * Filter the query on the AbnormalityDisease column * * Example usage: * <code> * $query->filterByAbnormalitydisease('fooValue'); // WHERE AbnormalityDisease = 'fooValue' * $query->filterByAbnormalitydisease('%fooValue%'); // WHERE AbnormalityDisease LIKE '%fooValue%' * </code> * * @param string $abnormalitydisease The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByAbnormalitydisease($abnormalitydisease = null, $comparison = null) { if (null === $comparison) { if (is_array($abnormalitydisease)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $abnormalitydisease)) { $abnormalitydisease = str_replace('*', '%', $abnormalitydisease); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::ABNORMALITYDISEASE, $abnormalitydisease, $comparison); } /** * Filter the query on the Prevalence column * * Example usage: * <code> * $query->filterByPrevalence('fooValue'); // WHERE Prevalence = 'fooValue' * $query->filterByPrevalence('%fooValue%'); // WHERE Prevalence LIKE '%fooValue%' * </code> * * @param string $prevalence The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByPrevalence($prevalence = null, $comparison = null) { if (null === $comparison) { if (is_array($prevalence)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $prevalence)) { $prevalence = str_replace('*', '%', $prevalence); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::PREVALENCE, $prevalence, $comparison); } /** * Filter the query on the Stressor column * * Example usage: * <code> * $query->filterByStressor('fooValue'); // WHERE Stressor = 'fooValue' * $query->filterByStressor('%fooValue%'); // WHERE Stressor LIKE '%fooValue%' * </code> * * @param string $stressor The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByStressor($stressor = null, $comparison = null) { if (null === $comparison) { if (is_array($stressor)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $stressor)) { $stressor = str_replace('*', '%', $stressor); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::STRESSOR, $stressor, $comparison); } /** * Filter the query on the LabField column * * Example usage: * <code> * $query->filterByLabfield('fooValue'); // WHERE LabField = 'fooValue' * $query->filterByLabfield('%fooValue%'); // WHERE LabField LIKE '%fooValue%' * </code> * * @param string $labfield The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByLabfield($labfield = null, $comparison = null) { if (null === $comparison) { if (is_array($labfield)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $labfield)) { $labfield = str_replace('*', '%', $labfield); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::LABFIELD, $labfield, $comparison); } /** * Filter the query on the Concentration column * * Example usage: * <code> * $query->filterByConcentration('fooValue'); // WHERE Concentration = 'fooValue' * $query->filterByConcentration('%fooValue%'); // WHERE Concentration LIKE '%fooValue%' * </code> * * @param string $concentration The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByConcentration($concentration = null, $comparison = null) { if (null === $comparison) { if (is_array($concentration)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $concentration)) { $concentration = str_replace('*', '%', $concentration); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::CONCENTRATION, $concentration, $comparison); } /** * Filter the query on the ABNORMRefNo column * * Example usage: * <code> * $query->filterByAbnormrefno(1234); // WHERE ABNORMRefNo = 1234 * $query->filterByAbnormrefno(array(12, 34)); // WHERE ABNORMRefNo IN (12, 34) * $query->filterByAbnormrefno(array('min' => 12)); // WHERE ABNORMRefNo >= 12 * $query->filterByAbnormrefno(array('max' => 12)); // WHERE ABNORMRefNo <= 12 * </code> * * @param mixed $abnormrefno The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByAbnormrefno($abnormrefno = null, $comparison = null) { if (is_array($abnormrefno)) { $useMinMax = false; if (isset($abnormrefno['min'])) { $this->addUsingAlias(AbnormPeer::ABNORMREFNO, $abnormrefno['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($abnormrefno['max'])) { $this->addUsingAlias(AbnormPeer::ABNORMREFNO, $abnormrefno['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::ABNORMREFNO, $abnormrefno, $comparison); } /** * Filter the query on the SecondRefNo column * * Example usage: * <code> * $query->filterBySecondrefno(1234); // WHERE SecondRefNo = 1234 * $query->filterBySecondrefno(array(12, 34)); // WHERE SecondRefNo IN (12, 34) * $query->filterBySecondrefno(array('min' => 12)); // WHERE SecondRefNo >= 12 * $query->filterBySecondrefno(array('max' => 12)); // WHERE SecondRefNo <= 12 * </code> * * @param mixed $secondrefno The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterBySecondrefno($secondrefno = null, $comparison = null) { if (is_array($secondrefno)) { $useMinMax = false; if (isset($secondrefno['min'])) { $this->addUsingAlias(AbnormPeer::SECONDREFNO, $secondrefno['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($secondrefno['max'])) { $this->addUsingAlias(AbnormPeer::SECONDREFNO, $secondrefno['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::SECONDREFNO, $secondrefno, $comparison); } /** * Filter the query on the Notes column * * Example usage: * <code> * $query->filterByNotes('fooValue'); // WHERE Notes = 'fooValue' * $query->filterByNotes('%fooValue%'); // WHERE Notes LIKE '%fooValue%' * </code> * * @param string $notes The value to use as filter. * Accepts wildcards (* and % trigger a LIKE) * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByNotes($notes = null, $comparison = null) { if (null === $comparison) { if (is_array($notes)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $notes)) { $notes = str_replace('*', '%', $notes); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(AbnormPeer::NOTES, $notes, $comparison); } /** * Filter the query on the Entered column * * Example usage: * <code> * $query->filterByEntered(1234); // WHERE Entered = 1234 * $query->filterByEntered(array(12, 34)); // WHERE Entered IN (12, 34) * $query->filterByEntered(array('min' => 12)); // WHERE Entered >= 12 * $query->filterByEntered(array('max' => 12)); // WHERE Entered <= 12 * </code> * * @param mixed $entered The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByEntered($entered = null, $comparison = null) { if (is_array($entered)) { $useMinMax = false; if (isset($entered['min'])) { $this->addUsingAlias(AbnormPeer::ENTERED, $entered['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($entered['max'])) { $this->addUsingAlias(AbnormPeer::ENTERED, $entered['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::ENTERED, $entered, $comparison); } /** * Filter the query on the DateEntered column * * Example usage: * <code> * $query->filterByDateentered('2011-03-14'); // WHERE DateEntered = '2011-03-14' * $query->filterByDateentered('now'); // WHERE DateEntered = '2011-03-14' * $query->filterByDateentered(array('max' => 'yesterday')); // WHERE DateEntered < '2011-03-13' * </code> * * @param mixed $dateentered The value to use as filter. * Values can be integers (unix timestamps), DateTime objects, or strings. * Empty strings are treated as NULL. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByDateentered($dateentered = null, $comparison = null) { if (is_array($dateentered)) { $useMinMax = false; if (isset($dateentered['min'])) { $this->addUsingAlias(AbnormPeer::DATEENTERED, $dateentered['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($dateentered['max'])) { $this->addUsingAlias(AbnormPeer::DATEENTERED, $dateentered['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::DATEENTERED, $dateentered, $comparison); } /** * Filter the query on the Modified column * * Example usage: * <code> * $query->filterByModified(1234); // WHERE Modified = 1234 * $query->filterByModified(array(12, 34)); // WHERE Modified IN (12, 34) * $query->filterByModified(array('min' => 12)); // WHERE Modified >= 12 * $query->filterByModified(array('max' => 12)); // WHERE Modified <= 12 * </code> * * @param mixed $modified The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByModified($modified = null, $comparison = null) { if (is_array($modified)) { $useMinMax = false; if (isset($modified['min'])) { $this->addUsingAlias(AbnormPeer::MODIFIED, $modified['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($modified['max'])) { $this->addUsingAlias(AbnormPeer::MODIFIED, $modified['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::MODIFIED, $modified, $comparison); } /** * Filter the query on the DateModified column * * Example usage: * <code> * $query->filterByDatemodified('2011-03-14'); // WHERE DateModified = '2011-03-14' * $query->filterByDatemodified('now'); // WHERE DateModified = '2011-03-14' * $query->filterByDatemodified(array('max' => 'yesterday')); // WHERE DateModified < '2011-03-13' * </code> * * @param mixed $datemodified The value to use as filter. * Values can be integers (unix timestamps), DateTime objects, or strings. * Empty strings are treated as NULL. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByDatemodified($datemodified = null, $comparison = null) { if (is_array($datemodified)) { $useMinMax = false; if (isset($datemodified['min'])) { $this->addUsingAlias(AbnormPeer::DATEMODIFIED, $datemodified['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($datemodified['max'])) { $this->addUsingAlias(AbnormPeer::DATEMODIFIED, $datemodified['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::DATEMODIFIED, $datemodified, $comparison); } /** * Filter the query on the Expert column * * Example usage: * <code> * $query->filterByExpert(1234); // WHERE Expert = 1234 * $query->filterByExpert(array(12, 34)); // WHERE Expert IN (12, 34) * $query->filterByExpert(array('min' => 12)); // WHERE Expert >= 12 * $query->filterByExpert(array('max' => 12)); // WHERE Expert <= 12 * </code> * * @param mixed $expert The value to use as filter. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByExpert($expert = null, $comparison = null) { if (is_array($expert)) { $useMinMax = false; if (isset($expert['min'])) { $this->addUsingAlias(AbnormPeer::EXPERT, $expert['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($expert['max'])) { $this->addUsingAlias(AbnormPeer::EXPERT, $expert['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::EXPERT, $expert, $comparison); } /** * Filter the query on the DateChecked column * * Example usage: * <code> * $query->filterByDatechecked('2011-03-14'); // WHERE DateChecked = '2011-03-14' * $query->filterByDatechecked('now'); // WHERE DateChecked = '2011-03-14' * $query->filterByDatechecked(array('max' => 'yesterday')); // WHERE DateChecked < '2011-03-13' * </code> * * @param mixed $datechecked The value to use as filter. * Values can be integers (unix timestamps), DateTime objects, or strings. * Empty strings are treated as NULL. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByDatechecked($datechecked = null, $comparison = null) { if (is_array($datechecked)) { $useMinMax = false; if (isset($datechecked['min'])) { $this->addUsingAlias(AbnormPeer::DATECHECKED, $datechecked['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($datechecked['max'])) { $this->addUsingAlias(AbnormPeer::DATECHECKED, $datechecked['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::DATECHECKED, $datechecked, $comparison); } /** * Filter the query on the TS column * * Example usage: * <code> * $query->filterByTs('2011-03-14'); // WHERE TS = '2011-03-14' * $query->filterByTs('now'); // WHERE TS = '2011-03-14' * $query->filterByTs(array('max' => 'yesterday')); // WHERE TS < '2011-03-13' * </code> * * @param mixed $ts The value to use as filter. * Values can be integers (unix timestamps), DateTime objects, or strings. * Empty strings are treated as NULL. * Use scalar values for equality. * Use array values for in_array() equivalent. * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL * * @return AbnormQuery The current query, for fluid interface */ public function filterByTs($ts = null, $comparison = null) { if (is_array($ts)) { $useMinMax = false; if (isset($ts['min'])) { $this->addUsingAlias(AbnormPeer::TS, $ts['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($ts['max'])) { $this->addUsingAlias(AbnormPeer::TS, $ts['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AbnormPeer::TS, $ts, $comparison); } /** * Exclude object from result * * @param Abnorm $abnorm Object to remove from the list of results * * @return AbnormQuery The current query, for fluid interface */ public function prune($abnorm = null) { if ($abnorm) { $this->addUsingAlias(AbnormPeer::AUTOCTR, $abnorm->getAutoctr(), Criteria::NOT_EQUAL); } return $this; } }
{ "content_hash": "18fcc996e859756fceeab9f54a0ef089", "timestamp": "", "source": "github", "line_count": 1215, "max_line_length": 375, "avg_line_length": 42.82798353909465, "alnum_prop": 0.6000269044507649, "repo_name": "royrusso/fishbase", "id": "e30dc97ec9cbe7ac726672127afde6727bbba133", "size": "52036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "classes/fbapp/om/BaseAbnormQuery.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54469" }, { "name": "JavaScript", "bytes": "257574" }, { "name": "PHP", "bytes": "43155398" } ], "symlink_target": "" }
package com.Dibike.common; import java.io.Serializable; /** * 结果对象 * @author * {"status":"0","msg":"成功","data":xxx} */ public class Result implements Serializable { private static final long serialVersionUID = 1L; private String status;//0表示成功,其他表示失败 private String msg;//消息 private Object data;//返回的数据 public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
{ "content_hash": "9cc76528341421cf388eb90e700cd34d", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 49, "avg_line_length": 16, "alnum_prop": 0.678125, "repo_name": "Saw85/DibikeManagement", "id": "9eae4464b4d93ab3565c49e1ddbe19a87a71db49", "size": "686", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/com/Dibike/common/Result.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42189" }, { "name": "HTML", "bytes": "108981" }, { "name": "Java", "bytes": "254437" }, { "name": "JavaScript", "bytes": "65321" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- <parent> <groupId>net.shibboleth.idp</groupId> <artifactId>idp-parent</artifactId> <version>3.2.0-SNAPSHOT</version> <relativePath>/Users/stroucki/svn/shib/java-identity-provider/trunk/idp-parent</relativePath> </parent> --> <repositories> <repository> <id>shib-release</id> <url>https://build.shibboleth.net/nexus/content/groups/public</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <properties> <java-support.version>7.2.0-SNAPSHOT</java-support.version> <jetty9-dta-ssl.version>1.0.0</jetty9-dta-ssl.version> <shib.groupId>net.shibboleth.idp</shib.groupId> <shib.version>3.2.0</shib.version> <opensaml.groupId>org.opensaml</opensaml.groupId> <opensaml.version>3.2.0</opensaml.version> <spring.version>4.2.3.RELEASE</spring.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <name>PrivacyLens</name> <groupId>edu.cmu.ece</groupId> <artifactId>PrivacyLens</artifactId> <version>3</version> <packaging>jar</packaging> <dependencies> <!-- Compile Dependencies --> <!-- Gson: Java to Json conversion --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> <scope>compile</scope> </dependency> <!-- Apache commons lang --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.4</version> <scope>compile</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <!-- db --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-attribute-api</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-authn-api</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-profile-api</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-profile-impl</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-consent-api</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-consent-impl</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-session-api</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-ui</artifactId> <version>${shib.version}</version> </dependency> <dependency> <groupId>${opensaml.groupId}</groupId> <artifactId>opensaml-saml-api</artifactId> <version>${opensaml.version}</version> </dependency> <dependency> <groupId>${opensaml.groupId}</groupId> <artifactId>opensaml-storage-api</artifactId> <version>${opensaml.version}</version> </dependency> <dependency> <groupId>${opensaml.groupId}</groupId> <artifactId>opensaml-storage-impl</artifactId> <version>${opensaml.version}</version> </dependency> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.0</version> </dependency> <!-- Provided Dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- Runtime Dependencies --> <!-- hsql --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.3.3</version> <scope>runtime</scope> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> <scope>runtime</scope> </dependency> <!-- joda jsp tags --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time-jsptags</artifactId> <version>1.1.1</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <scope>runtime</scope> <version>1.0.4</version> </dependency> <!-- Test Dependencies --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.6</version> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>junit</groupId> <artifactId>junit</artifactId> </exclusion> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-profile-api</artifactId> <version>${shib.version}</version> <scope>test</scope> <type>test-jar</type> </dependency> <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-saml-impl</artifactId> <version>${shib.version}</version> <scope>test</scope> </dependency> <!-- <dependency> <groupId>${shib.groupId}</groupId> <artifactId>idp-profile-impl</artifactId> <version>${shib.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>${opensaml.groupId}</groupId> <artifactId>opensaml-storage-impl</artifactId> <version>${opensaml.version}</version> <scope>test</scope> </dependency> --> <!-- Managed Dependencies --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <debug>true</debug> </configuration> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <phase>prepare-package</phase> <configuration> <tasks> <taskdef classpathref="maven.plugin.classpath" resource="wikitexttasks.properties" /> <wikitext-to-html markupLanguage="Textile" file="${basedir}/manual/manual.textile" htmlFilenameFormat="$1.html" formatOutput="true" emitDoctype="false" title="${project.name}-${project.version}"> <markupLanguageConfiguration locale="en"/> <stylesheet url="style.css" /> </wikitext-to-html> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>com.datastax.wikitext</groupId> <artifactId>wikitext-core-ant</artifactId> <version>1.3</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.fusesource.wikitext</groupId> <artifactId>textile-core</artifactId> <version>1.3</version> <scope>runtime</scope> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.11</version> <configuration> <suiteXmlFiles> <suiteXmlFile>${basedir}/src/test/resources/testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptors> <descriptor>src/main/assembly/distribution.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <!-- Project Metadata --> <url>http://www.privacylens.org</url> <inceptionYear>2011</inceptionYear> <licenses> <license> <name>BSD</name> <url>http://www.opensource.org/licenses/BSD-3-Clause</url> </license> </licenses> <issueManagement> <system>GitHub</system> <url>https://github.com/organizations/cmu-cylab-privacylens/PrivacyLens/issues</url> </issueManagement> <scm> <url>https://github.com/cmu-cylab-privacylens/PrivacyLens.git</url> </scm> <developers> <developer> <id>stroucki</id> <name>Michael Stroucken</name> <organization>CMU Cylab</organization> <organizationUrl>http://www.cylab.cmu.edu/</organizationUrl> <timezone>-5</timezone> </developer> </developers> </project>
{ "content_hash": "1901dbf3898809ea5936c925d54c1967", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 121, "avg_line_length": 34.62059620596206, "alnum_prop": 0.5204696673189824, "repo_name": "cmu-cylab-privacylens/PrivacyLens", "id": "d7dba8feadeffbf28bf8f47563efbc4c84439146", "size": "12775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "6150" }, { "name": "Groovy", "bytes": "4084" }, { "name": "HTML", "bytes": "1790" }, { "name": "Java", "bytes": "460842" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Shoes</title> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css"> <link rel="stylesheet" href="css/demo-la-shoes.css"> <script src="https://use.typekit.net/etx2zxm.js"></script> <script>try{Typekit.load({ async: true });}catch(e){}</script> <script src="js/shapes-polyfill.min.js"></script> </head> <body> <div class="runner-1"> <img src="img/runner-1.png"/> </div> <div class="shoe-print"> <img src="img/shoe-prnt.png"/> </div> <div class="introduction"> <h1>Enjoy the <em>burn</em></h1> <div class="copy"> <p>Running is a road to self-awareness and reliance-you can push yourself to extremes and learn the harsh reality of your physical and mental limitations or coast quietly down a solitary path watching the earth spin beneath your feet.</p> </div> </div> <div class="runner-2"> <img src="img/runner-2.png"/> </div> <div class="shoes"> <h2>Run</h2> <div class="copy"> <div class="shape"></div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deseruntmollit anim id est laborum.</p> <img src="img/shoe.png"/> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p> </div> </div> <div class="runner-3"> <img src="img/runner-3.png"/> <div class="quote"> <div class="line">Run when you can</div> <div class="line">Walk if you have to</div> <div class="line">Crawl if you must</div> <div class="line">Just <em>never</em> give up.</div> <div class="author">- Dean Karnazes</div> </div> </div> </body> </html>
{ "content_hash": "e2a278f8e0f08d975c771f8593f06d79", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 456, "avg_line_length": 46.471698113207545, "alnum_prop": 0.6987413723101908, "repo_name": "Landerson352/uniform", "id": "8ad9821efc3794e6913b468c190aa8cc2ff04dcd", "size": "2463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demos/demo-la-shoes.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7115" }, { "name": "HTML", "bytes": "845" }, { "name": "JavaScript", "bytes": "1760" } ], "symlink_target": "" }
Two approaches 1. greedy. we pick the the element with most value ratio first. **Heap** problem. All elements are picked in sorted order. 1. partition. Better. The picked elements are not even in sorted order. We partition them basing on segments property. #WeightedMedian. We can partition element. 1. quick sort: partition based on the number elements on each side. 1. weighted median: partition based on the total sum of each segment.
{ "content_hash": "c61e21697b7731c771b8a29ae3369c34", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 122, "avg_line_length": 49, "alnum_prop": 0.780045351473923, "repo_name": "jasonzhang2022/algorithm", "id": "6e2d8a5bdab27b058ed6eaff5906ff638ca25bbc", "size": "467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/jason/algorithm/select/readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "59105" }, { "name": "Java", "bytes": "691161" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Workspace</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root>Loading...</app-root> </body> </html>
{ "content_hash": "8152f75ab4c650ab396214d3899066db", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 70, "avg_line_length": 21.142857142857142, "alnum_prop": 0.6385135135135135, "repo_name": "cumulous/web", "id": "487ef63a0585e3a4c8f0374958d19b203fc11463", "size": "296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1157" }, { "name": "Gherkin", "bytes": "1957" }, { "name": "HTML", "bytes": "2488" }, { "name": "JavaScript", "bytes": "2626" }, { "name": "Shell", "bytes": "2575" }, { "name": "TypeScript", "bytes": "158108" } ], "symlink_target": "" }
//___________________________________________________________________________________ // // Copyright (C) 2018, Mariusz Postol LODZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI //___________________________________________________________________________________ using System.Collections.Generic; using System.Diagnostics; using UAOOI.Common.Infrastructure.Diagnostic; namespace UAOOI.Configuration.Networking.UnitTest.Instrumentation { public class Logger : ITraceSource { public class TraceLogEntity { public TraceEventType EventType { get; private set; } public int Id { get; private set; } public object Data { get; private set; } public TraceLogEntity(TraceEventType eventType, int id, object data) { this.EventType = eventType; this.Id = id; this.Data = data; } } public List<TraceLogEntity> TraceLogList { get; } = new List<TraceLogEntity>(); #region ITraceSource public void TraceData(TraceEventType eventType, int id, object data) { TraceLogList.Add(new TraceLogEntity(eventType, id, data)); } #endregion } }
{ "content_hash": "4db849923ffaa49e9b467be254691b14", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 86, "avg_line_length": 29.65, "alnum_prop": 0.5826306913996627, "repo_name": "mpostol/OPC-UA-OOI", "id": "d8c2fb8ef69bda78d33bd390535bf7edae3ffe96", "size": "1188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Configuration/Tests/NetworkingUnitTest/Instrumentation/Logger.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8495" }, { "name": "C#", "bytes": "4749023" }, { "name": "Vim Snippet", "bytes": "1008" } ], "symlink_target": "" }
all: g++ displayExample.cpp ../src/JHLEDBackpack.cpp -I../src -o displayExample
{ "content_hash": "f76dd9d8ff4855aa326982a1fc0e3773", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 75, "avg_line_length": 40.5, "alnum_prop": 0.7283950617283951, "repo_name": "jetsonhacks/JHLEDBackpack", "id": "6500281747fc6ce3c322167f5bc92c6dceda5055", "size": "81", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/Makefile", "mode": "33261", "license": "mit", "language": [ { "name": "C++", "bytes": "15086" }, { "name": "Makefile", "bytes": "81" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About JohnKeyoin</source> <translation>О JohnKeyoin-у</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;JohnKeyoin&lt;/b&gt; version</source> <translation>&lt;b&gt;JohnKeyoin&lt;/b&gt; верзија</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The JohnKeyoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Адресар</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Кликните два пута да промените адресу и/или етикету</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Прави нову адресу</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копира изабрану адресу на системски клипборд</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Нова адреса</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your JohnKeyoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ово су Ваше JohnKeyoin адресе за примање уплата. Можете да сваком пошиљаоцу дате другачију адресу да би пратили ко је вршио уплате.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Prikaži &amp;QR kod</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a JohnKeyoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified JohnKeyoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Избриши</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your JohnKeyoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Извоз података из адресара</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(без етикете)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Унесите лозинку</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Нова лозинка</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Поновите нову лозинку</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Унесите нову лозинку за приступ новчанику.&lt;br/&gt;Молимо Вас да лозинка буде &lt;b&gt;10 или више насумице одабраних знакова&lt;/b&gt;, или &lt;b&gt;осам или више речи&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Шифровање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ова акција захтева лозинку Вашег новчаника да би га откључала.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Откључавање новчаника</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ова акција захтева да унесете лозинку да би дешифловала новчаник.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Дешифровање новчаника</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Промена лозинке</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Унесите стару и нову лозинку за шифровање новчаника.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Одобрите шифровање новчаника</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Упозорење: Ако се ваш новчаник шифрује а потом изгубите лозинкзу, ви ћете &lt;b&gt;ИЗГУБИТИ СВЕ JohnKeyoin-Е&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Да ли сте сигурни да желите да се новчаник шифује?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Новчаник је шифрован</translation> </message> <message> <location line="-56"/> <source>JohnKeyoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your johnkeyoins from being stolen by malware infecting your computer.</source> <translation>JohnKeyoin će se sad zatvoriti da bi završio proces enkripcije. Zapamti da enkripcija tvog novčanika ne može u potpunosti da zaštiti tvoje JohnKeyoine da ne budu ukradeni od malawarea koji bi inficirao tvoj kompjuter.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Неуспело шифровање новчаника</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Настала је унутрашња грешка током шифровања новчаника. Ваш новчаник није шифрован.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Лозинке које сте унели се не подударају.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Неуспело откључавање новчаника</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Лозинка коју сте унели за откључавање новчаника је нетачна.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Неуспело дешифровање новчаника</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Лозинка за приступ новчанику је успешно промењена.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронизација са мрежом у току...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Општи преглед</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Погледајте општи преглед новчаника</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Трансакције</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Претражите историјат трансакција</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Уредите запамћене адресе и њихове етикете</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Прегледајте листу адреса на којима прихватате уплате</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>I&amp;zlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Напустите програм</translation> </message> <message> <location line="+4"/> <source>Show information about JohnKeyoin</source> <translation>Прегледајте информације о JohnKeyoin-у</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>О &amp;Qt-у</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Прегледајте информације о Qt-у</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>П&amp;оставке...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Шифровање новчаника...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup новчаника</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Промени &amp;лозинку...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a JohnKeyoin address</source> <translation>Пошаљите новац на JohnKeyoin адресу</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for JohnKeyoin</source> <translation>Изаберите могућности JohnKeyoin-а</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Мењање лозинке којом се шифрује новчаник</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>JohnKeyoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About JohnKeyoin</source> <translation>&amp;О JohnKeyoin-у</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your JohnKeyoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified JohnKeyoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Фајл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Подешавања</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>П&amp;омоћ</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Трака са картицама</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>JohnKeyoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to JohnKeyoin network</source> <translation><numerusform>%n активна веза са JohnKeyoin мрежом</numerusform><numerusform>%n активне везе са JohnKeyoin мрежом</numerusform><numerusform>%n активних веза са JohnKeyoin мрежом</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ажурно</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ажурирање у току...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Послана трансакција</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Придошла трансакција</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1⏎ Iznos: %2⏎ Tip: %3⏎ Adresa: %4⏎</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid JohnKeyoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;откључан&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Новчаник јс &lt;b&gt;шифрован&lt;/b&gt; и тренутно &lt;b&gt;закључан&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. JohnKeyoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Измени адресу</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Унешена адреса &quot;%1&quot; се већ налази у адресару.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid JohnKeyoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Немогуће откључати новчаник.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>JohnKeyoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>верзија</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Поставке</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start JohnKeyoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start JohnKeyoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the JohnKeyoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the JohnKeyoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting JohnKeyoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Јединица за приказивање износа:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show JohnKeyoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting JohnKeyoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the JohnKeyoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Непотврђено:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>новчаник</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Недавне трансакције&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start johnkeyoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Zatraži isplatu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Poruka:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Snimi kao...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the JohnKeyoin-Qt help message to get a list with possible JohnKeyoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>JohnKeyoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>JohnKeyoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the JohnKeyoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the JohnKeyoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Ukloni sva polja sa transakcijama</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Потврди акцију слања</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Пошаљи</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Да ли сте сигурни да желите да пошаљете %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>и</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Етикета</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Izaberite adresu iz adresara</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a JohnKeyoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite JohnKeyoin adresu (n.pr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this JohnKeyoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified JohnKeyoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a JohnKeyoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Unesite JohnKeyoin adresu (n.pr. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter JohnKeyoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The JohnKeyoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otvorite do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrdjeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrde</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>етикета</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nije još uvek uspešno emitovan</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ovaj odeljak pokazuje detaljan opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>iznos</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otvoreno do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline * van mreže (%1 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrdjeno (%1 of %2 potvrdjenih)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrdjena (%1 potvrdjenih)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ovaj blok nije primljen od ostalih čvorova (nodova) i verovatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generisan ali nije prihvaćen</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Isplata samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status vaše transakcije. Predjite mišem preko ovog polja da bi ste videli broj konfirmacija</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vreme primljene transakcije.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tip transakcije</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destinacija i adresa transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen ili dodat balansu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>ove nedelje</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovog meseca</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošlog meseca</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Opseg...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljen sa</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslat ka</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Vama - samom sebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minirano</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Drugi</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Navedite adresu ili naziv koji bi ste potražili</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>kopiraj adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>kopiraj naziv</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>promeni naziv</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Izvezi podatke o transakcijama</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Зарезом одвојене вредности (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrdjen</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Етикета</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адреса</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Грешка током извоза</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Није могуће писати у фајл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Opseg:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Слање новца</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>JohnKeyoin version</source> <translation>JohnKeyoin верзија</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Korišćenje:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or johnkeyoind</source> <translation>Pošalji naredbu na -server ili johnkeyoinid </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listaj komande</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Zatraži pomoć za komande</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcije</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: johnkeyoin.conf)</source> <translation>Potvrdi željeni konfiguracioni fajl (podrazumevani:JohnKeyoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: johnkeyoind.pid)</source> <translation>Konkretizuj pid fajl (podrazumevani: JohnKeyoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Gde je konkretni data direktorijum </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Slušaj konekcije na &lt;port&gt; (default: 9333 or testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; konekcija po priključku (default: 125) </translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komandnu liniju i JSON-RPC komande</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Radi u pozadini kao daemon servis i prihvati komande</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Koristi testnu mrežu</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=johnkeyoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;JohnKeyoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. JohnKeyoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong JohnKeyoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the JohnKeyoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC konekcije</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC konekcije</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC konekcije sa posebne IP adrese</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande to nodu koji radi na &lt;ip&gt; (default: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Odredi veličinu zaštićenih ključeva na &lt;n&gt; (default: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovo skeniraj lanac blokova za nedostajuće transakcije iz novčanika</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC konekcije</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>privatni ključ za Server (podrazumevan: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Prihvatljive cifre (podrazumevano: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ova poruka Pomoći</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>učitavam adrese....</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of JohnKeyoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart JohnKeyoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Učitavam blok indeksa...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. JohnKeyoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Новчаник се учитава...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ponovo skeniram...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Završeno učitavanje</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{ "content_hash": "55230b081718d54b02109ad18076f6a4", "timestamp": "", "source": "github", "line_count": 2919, "max_line_length": 395, "avg_line_length": 34.715998629667695, "alnum_prop": 0.5996585616167995, "repo_name": "JohnKeyCoin/JohnKeyoin", "id": "971359a10aaaa6a7909937182b428403fa13bbb8", "size": "103522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_sr.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "96512" }, { "name": "C++", "bytes": "2519687" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14634" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "37264" }, { "name": "Shell", "bytes": "2527" }, { "name": "TypeScript", "bytes": "5239467" } ], "symlink_target": "" }
package com.qumasoft.qvcslib; import com.qumasoft.qvcslib.commandargs.CreateArchiveCommandArgs; import java.io.IOException; import java.util.Collection; import javax.swing.event.ChangeListener; /** * Directory manager interface. These are the methods that must be implemented by a client-side Directory manager. * @author Jim Voris */ public interface DirectoryManagerInterface { /** * Get the archive directory manager associated with this directory. * @return the archive directory manager associated with this directory. */ ArchiveDirManagerInterface getArchiveDirManager(); /** * Get the workfile directory manager associated with this directory. * @return the workfile directory manager associated with this directory. */ WorkfileDirectoryManagerInterface getWorkfileDirectoryManager(); /** * Merge the respective file collections of the workfile directory manager and the archive directory manager so that they can be presented as a single collection of files. * @throws QVCSException for any QVCS problems. */ void mergeManagers() throws QVCSException; /** * Get the user name. * @return the user name. */ String getUserName(); /** * Get the project name for this directory. * @return the project name for this directory. */ String getProjectName(); /** * Get the branch name for this directory. * @return the branch name for this directory. */ String getBranchName(); /** * Get the appended path for this directory. * @return the appended path for this directory. */ String getAppendedPath(); /** * Get the number of files in the collection for this directory (includes the merged set of version controlled files and un-controlled files). * @return the number of files in the collection for this directory. */ int getCount(); /** * Create an archive in this directory. * @param commandLineArgs the create archive command arguments. * @param fullWorkfilename the full workfile name. * @return true if the create was successful. * @throws IOException for file I/O problems. * @throws QVCSException for a QVCS specific problem. */ boolean createArchive(CreateArchiveCommandArgs commandLineArgs, String fullWorkfilename) throws IOException, QVCSException; /** * Get the Collection of merged info instances for this directory. * @return the Collection of merged info instances for this directory. */ Collection<MergedInfoInterface> getMergedInfoCollection(); /** * Get the 'has changed' flag for this directory. * @return the 'has changed' flag for this directory. */ boolean getHasChanged(); /** * Set the 'has changed' flag for this directory. * @param flag the 'has changed' flag for this directory. */ void setHasChanged(boolean flag); /** * Lookup the merged info for the given short workfile name. * @param shortWorkfileName the short workfile name. * @return the merged info for the given short workfile name; null if the not found. */ MergedInfoInterface getMergedInfo(String shortWorkfileName); /** * Lookup the merged info for the given fileId. * @param fileId the fileId. * @return the merged info for the given fileId; null if the not found. */ MergedInfoInterface getMergedInfoByFileId(Integer fileId); /** * Add a change listener. * @param listener a change listener. */ void addChangeListener(ChangeListener listener); /** * Remove a change listener. * @param listener a change listener. */ void removeChangeListener(ChangeListener listener); }
{ "content_hash": "f5f94f8a3485d4965b04a02aba841d54", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 175, "avg_line_length": 32.61206896551724, "alnum_prop": 0.6917790113666402, "repo_name": "jimv39/qvcsos", "id": "aa208215cc3a1a348a001aaf7b72ebcb78a969c1", "size": "4397", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "qvcse-qvcslib/src/main/java/com/qumasoft/qvcslib/DirectoryManagerInterface.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "141449" }, { "name": "CSS", "bytes": "6903" }, { "name": "HTML", "bytes": "286613" }, { "name": "Java", "bytes": "5740856" }, { "name": "JavaScript", "bytes": "21974" }, { "name": "PLpgSQL", "bytes": "144136" }, { "name": "Shell", "bytes": "7928" } ], "symlink_target": "" }
/* $OpenBSD: lebuffervar.h,v 1.2 2001/08/20 19:48:33 jason Exp $ */ /* $NetBSD: lebuffervar.h,v 1.2 1998/07/27 19:25:34 pk Exp $ */ /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Paul Kranenburg. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ struct lebuf_softc { struct device sc_dev; /* us as a device */ bus_space_tag_t sc_bustag; bus_dma_tag_t sc_dmatag; struct sbusdev sc_sd; /* sbus device */ u_int sc_rev; /* revision */ int sc_node; /* PROM node ID */ int sc_burst; /* DVMA burst size in effect */ caddr_t sc_buffer; /* VA of the buffer we provide */ int sc_bufsiz; /* Size of buffer */ int attached; /* 1: in use by `le' device */ };
{ "content_hash": "ff90446d6624cab995538a5c2939c200", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 78, "avg_line_length": 48.84313725490196, "alnum_prop": 0.7314331593737455, "repo_name": "MarginC/kame", "id": "42bac0f1972cd11d103bb6c83b7e0d8667d8c852", "size": "2491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openbsd/sys/dev/sbus/lebuffervar.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arc", "bytes": "7491" }, { "name": "Assembly", "bytes": "14375563" }, { "name": "Awk", "bytes": "313712" }, { "name": "Batchfile", "bytes": "6819" }, { "name": "C", "bytes": "356715789" }, { "name": "C++", "bytes": "4231647" }, { "name": "DIGITAL Command Language", "bytes": "11155" }, { "name": "Emacs Lisp", "bytes": "790" }, { "name": "Forth", "bytes": "253695" }, { "name": "GAP", "bytes": "9964" }, { "name": "Groff", "bytes": "2220485" }, { "name": "Lex", "bytes": "168376" }, { "name": "Logos", "bytes": "570213" }, { "name": "Makefile", "bytes": "1778847" }, { "name": "Mathematica", "bytes": "16549" }, { "name": "Objective-C", "bytes": "529629" }, { "name": "PHP", "bytes": "11283" }, { "name": "Perl", "bytes": "151251" }, { "name": "Perl6", "bytes": "2572" }, { "name": "Ruby", "bytes": "7283" }, { "name": "Scheme", "bytes": "76872" }, { "name": "Shell", "bytes": "583253" }, { "name": "Stata", "bytes": "408" }, { "name": "Yacc", "bytes": "606054" } ], "symlink_target": "" }
const config = require('./index'); config.extends = [ ...config.extends, "plugin:@typescript-eslint/eslint-recommended", 'plugin:@typescript-eslint/recommended' ]; config.plugins = [ ...config.plugins, '@typescript-eslint' ]; delete config.parser; config.parserOptions = { project: './tsconfig.json' }; config.rules = { ...config.rules, "no-unused-vars": 0, '@typescript-eslint/ban-types': 0, '@typescript-eslint/explicit-module-boundary-types': 0, '@typescript-eslint/array-type': 0, '@typescript-eslint/eofline': 0, '@typescript-eslint/max-classes-per-file': 0, '@typescript-eslint/max-line-length': 0, '@typescript-eslint/member-access': 0, '@typescript-eslint/member-ordering': 0, '@typescript-eslint/no-conditional-assignment': 0, '@typescript-eslint/no-empty': 0, '@typescript-eslint/no-empty-function': 0, '@typescript-eslint/no-empty-interface': 0, '@typescript-eslint/no-explicit-any': 0, '@typescript-eslint/no-unused-vars': [2, { 'argsIgnorePattern': '_' }], '@typescript-eslint/object-literal-sort-keys': 0, '@typescript-eslint/object-literal-shorthand': 0, '@typescript-eslint/ordered-imports': 0, '@typescript-eslint/prefer-const': 0, '@typescript-eslint/prefer-for-of': 0, '@typescript-eslint/space-before-function-paren': [0, 'always'], '@typescript-eslint/unified-signatures': 0, '@typescript-eslint/variable-name': 0 } module.exports = config;
{ "content_hash": "ff6205eaf8de5a48ac79aa1a02ed61ba", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 75, "avg_line_length": 31.638297872340427, "alnum_prop": 0.6691324815063887, "repo_name": "plotly/dash", "id": "e47a6f51e68237c2fb4a480fe9e0ca4cd0938b15", "size": "1487", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "@plotly/eslint-config-dash/typescript.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17191" }, { "name": "HTML", "bytes": "1729" }, { "name": "JavaScript", "bytes": "638735" }, { "name": "Less", "bytes": "22320" }, { "name": "Python", "bytes": "1304969" }, { "name": "Shell", "bytes": "224" }, { "name": "TypeScript", "bytes": "840257" } ], "symlink_target": "" }
package ca.corefacility.bioinformatics.irida.ria.unit.web; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.MessageSource; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.ui.ExtendedModelMap; import ca.corefacility.bioinformatics.irida.model.user.PasswordReset; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.ria.web.login.PasswordResetController; import ca.corefacility.bioinformatics.irida.service.EmailController; import ca.corefacility.bioinformatics.irida.service.user.PasswordResetService; import ca.corefacility.bioinformatics.irida.service.user.UserService; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; /** * */ public class PasswordResetControllerTest { private PasswordResetService passwordResetService; private PasswordResetController controller; @BeforeEach public void setUp() { passwordResetService = mock(PasswordResetService.class); controller = new PasswordResetController(passwordResetService); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void testGetResetPage() { User user = new User(1L, "tom", null, null, null, null, null); PasswordReset passwordReset = new PasswordReset(user); String resetId = passwordReset.getId(); ExtendedModelMap model = new ExtendedModelMap(); when(passwordResetService.read(resetId)).thenReturn(passwordReset); String resetPage = controller.getResetPage(resetId, false, model); assertEquals(PasswordResetController.PASSWORD_RESET_PAGE, resetPage); assertTrue(model.containsKey("errors")); assertTrue(model.containsKey("passwordReset")); assertTrue(model.containsKey("user")); verify(passwordResetService).read(resetId); } }
{ "content_hash": "d8086d573a0eaac3be0afb96dccd1e4d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 82, "avg_line_length": 31.234375, "alnum_prop": 0.8084042021010506, "repo_name": "phac-nml/irida", "id": "c5689144b48a632b4e7407a1911fb919e8a15f96", "size": "1999", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/PasswordResetControllerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22180" }, { "name": "Dockerfile", "bytes": "4941" }, { "name": "HTML", "bytes": "44649" }, { "name": "Java", "bytes": "5071675" }, { "name": "JavaScript", "bytes": "941290" }, { "name": "Kotlin", "bytes": "19144" }, { "name": "Perl", "bytes": "6980" }, { "name": "Python", "bytes": "8985" }, { "name": "Shell", "bytes": "13029" }, { "name": "TypeScript", "bytes": "344558" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>alexagc.github.io</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="manifest" href="manifest.json"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <meta name="theme-color" content="#1976d2"> <script> (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-106397567-1', 'auto'); ga('send', 'pageview'); </script> </head> <body> <app-root></app-root> <noscript>Please enable JavaScript to continue using this application.</noscript> </body> </html>
{ "content_hash": "05c27e230bd72cfa6d549b3ca726495e", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 88, "avg_line_length": 29.666666666666668, "alnum_prop": 0.6151685393258427, "repo_name": "alexagc/web-page", "id": "f8c81028831dddf1a27663f0034b99971fd07e6b", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "147" }, { "name": "HTML", "bytes": "1207" }, { "name": "JavaScript", "bytes": "1910" }, { "name": "TypeScript", "bytes": "6974" } ], "symlink_target": "" }
#ifndef ASTRO_OS #define ASTRO_OS #include <astro/astro.h> #if ASTRO_PLATFORM_WIN32 || ASTRO_PLATFORM_WINRT # define WIN32_LEAN_AND_MEAN 1 # include <windows.h> #elif ASTRO_PLATFORM_NACL == 0 && ASTRO_PLATFORM_EMSCRIPTEN == 0 # include <dlfcn.h> #endif #if ASTRO_PLATFORM_OSX # define ASTRO_DL_EXT "dylib" #elif ASTRO_PLATFORM_WIN32 || ASTRO_PLATFORM_WINRT # define ASTRO_DL_EXT "dll" #else # define ASTRO_DL_EXT "so" #endif namespace astro { inline void* dlopen(const char* path) { #if ASTRO_PLATFORM_WIN32 return (void*) ::LoadLibraryA(path); #elif ASTRO_PLATFORM_NACL || ASTRO_PLATFORM_EMSCRIPTEN || ASTRO_PLATFORM_WINRT return nullptr; #else return ::dlopen(path, RTLD_LOCAL | RTLD_LAZY); #endif } inline int dlclose(void* handle) { #if ASTRO_PLATFORM_WIN32 return ::FreeLibrary((HMODULE) handle); #elif ASTRO_PLATFORM_NACL || ASTRO_PLATFORM_EMSCRIPTEN || ASTRO_PLATFORM_WINRT return 0; #else return ::dlclose(handle); #endif } inline void* dlsym(void* handle, const char* symbol) { #if ASTRO_PLATFORM_WIN32 return (void*) ::GetProcAddress((HMODULE)handle, symbol); #elif ASTRO_PLATFORM_NACL || ASTRO_PLATFORM_EMSCRIPTEN || ASTRO_PLATFORM_WINRT return nullptr; #else return ::dlsym(handle, symbol); #endif } } #endif
{ "content_hash": "059e26e6c04ce7c0cd6bd4e7d307ccbb", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 78, "avg_line_length": 21.76271186440678, "alnum_prop": 0.7032710280373832, "repo_name": "team-astro/astro", "id": "6de2576336e88b600528a8efb2727e8a0ad90886", "size": "1340", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "include/astro/os.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1349" }, { "name": "C", "bytes": "124090" }, { "name": "C++", "bytes": "86112" }, { "name": "Lua", "bytes": "45315" }, { "name": "Makefile", "bytes": "7325" } ], "symlink_target": "" }
namespace RandomTests.Entities.App { public class Intrebare : IEntityBase { public int ID { get; set; } public string Text { get; set; } public int? CapitolId { get; set; } public virtual Capitol Capitol { get; set; } public int? SubcapitolId { get; set; } public virtual SubCapitol SubCapitol { get; set; } public string V1 { get; set; } public string V2 { get; set; } public string V3 { get; set; } public int Raspuns { get; set; } public int Nivel { get; set; } public byte[] Imagine { get; set; } public bool Eseu { get; set; } public string RaspunsEseu { get; set; } } }
{ "content_hash": "4fa7b9c1dfe8851204a99a7e3978953e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 52, "avg_line_length": 30.4, "alnum_prop": 0.6546052631578947, "repo_name": "mihaibulaicon/RandomTests1", "id": "f5ef59ea9aa82a1304e9902f32094598b73a3e79", "size": "610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RandomTests.Entities/App/Intrebare.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "98" }, { "name": "C#", "bytes": "235875" }, { "name": "CSS", "bytes": "76931" }, { "name": "HTML", "bytes": "66523" }, { "name": "JavaScript", "bytes": "283244" }, { "name": "SQLPL", "bytes": "3016" } ], "symlink_target": "" }
<?php /** * Swift Mailer LOGIN Authenticator Mechanism * Please read the LICENSE file * @author Chris Corbyn <chris@w3style.co.uk> * @package Swift_Authenticator * @license GNU Lesser General Public License */ require_once dirname(__FILE__) . "/../ClassLoader.php"; Swift_ClassLoader::load("Swift_Authenticator"); /** * Swift LOGIN Authenticator * @package Swift_Authenticator * @author Chris Corbyn <chris@w3style.co.uk> */ class Swift_Authenticator_LOGIN extends Swift_Authenticator { /** * Try to authenticate using the username and password * Returns false on failure * @param string The username * @param string The password * @param Swift The instance of Swift this authenticator is used in * @return boolean */ function isAuthenticated($user, $pass, &$swift) { Swift_ClassLoader::load("Swift_Errors"); Swift_Errors::expect($e, "Swift_ConnectionException"); if (!$e) $swift->command("AUTH LOGIN", 334); if (!$e) $swift->command(base64_encode($user), 334); if (!$e) $swift->command(base64_encode($pass), 235); if ($e) { $swift->reset(); return false; } Swift_Errors::clear("Swift_ConnectionException"); return true; } /** * Return the name of the AUTH extension this is for * @return string */ function getAuthExtensionName() { return "LOGIN"; } }
{ "content_hash": "a600bfb470a0a84c2da12c2f305fdb5a", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 69, "avg_line_length": 26.862745098039216, "alnum_prop": 0.6649635036496351, "repo_name": "hammadalinaqvi/bookstoregenie", "id": "a50cecdcfedd6cbc7ba275b3446640cdbd2d169f", "size": "1370", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "projMan/activecollab/angie/classes/swiftmailer/Swift/Authenticator/LOGIN.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7164" }, { "name": "CSS", "bytes": "1707795" }, { "name": "Frege", "bytes": "285235" }, { "name": "JavaScript", "bytes": "4892721" }, { "name": "PHP", "bytes": "34467676" }, { "name": "Perl", "bytes": "121014" }, { "name": "Python", "bytes": "10525" }, { "name": "Ruby", "bytes": "294210" }, { "name": "SQL", "bytes": "2429" }, { "name": "Shell", "bytes": "1458" } ], "symlink_target": "" }
@interface B2DPolygonShapeTest : SenTestCase @end
{ "content_hash": "10b15a8ae915ef61ac79050b1178c14d", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 45, "avg_line_length": 17.333333333333332, "alnum_prop": 0.8076923076923077, "repo_name": "CurveBeryl/Joybox-Box2D", "id": "6c12dd3d4feb76934885a855d75418882a11a7ce", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Box2DTests/Collision/Shapes/B2DPolygonShapeTest.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6006" }, { "name": "C++", "bytes": "515750" }, { "name": "Objective-C", "bytes": "204433" } ], "symlink_target": "" }
\PHPUnit\Framework\MockObject\Generator::generate('Foo', [], 'MockFoo', true, true) --FILE-- <?php abstract class Foo { public function one() { } abstract public function two(); abstract protected function three(); } require __DIR__ . '/../../../../vendor/autoload.php'; $generator = new \PHPUnit\Framework\MockObject\Generator; $mock = $generator->generate( 'Foo', [], 'MockFoo', true, true ); print $mock['code']; ?> --EXPECT-- class MockFoo extends Foo implements PHPUnit\Framework\MockObject\MockObject { private $__phpunit_invocationMocker; private $__phpunit_originalObject; private $__phpunit_configurable = ['one', 'two', 'three']; private $__phpunit_returnValueGeneration = true; public function __clone() { $this->__phpunit_invocationMocker = clone $this->__phpunit_getInvocationMocker(); } public function one() { $__phpunit_arguments = []; $__phpunit_count = func_num_args(); if ($__phpunit_count > 0) { $__phpunit_arguments_tmp = func_get_args(); for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) { $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i]; } } $__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke( new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation( 'Foo', 'one', $__phpunit_arguments, '', $this, true ) ); return $__phpunit_result; } public function two() { $__phpunit_arguments = []; $__phpunit_count = func_num_args(); if ($__phpunit_count > 0) { $__phpunit_arguments_tmp = func_get_args(); for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) { $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i]; } } $__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke( new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation( 'Foo', 'two', $__phpunit_arguments, '', $this, true ) ); return $__phpunit_result; } protected function three() { $__phpunit_arguments = []; $__phpunit_count = func_num_args(); if ($__phpunit_count > 0) { $__phpunit_arguments_tmp = func_get_args(); for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) { $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i]; } } $__phpunit_result = $this->__phpunit_getInvocationMocker()->invoke( new \PHPUnit\Framework\MockObject\Invocation\ObjectInvocation( 'Foo', 'three', $__phpunit_arguments, '', $this, true ) ); return $__phpunit_result; } public function expects(\PHPUnit\Framework\MockObject\Matcher\Invocation $matcher) { return $this->__phpunit_getInvocationMocker()->expects($matcher); } public function method() { $any = new \PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount; $expects = $this->expects($any); return call_user_func_array([$expects, 'method'], func_get_args()); } public function __phpunit_setOriginalObject($originalObject) { $this->__phpunit_originalObject = $originalObject; } public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration) { $this->__phpunit_returnValueGeneration = $returnValueGeneration; } public function __phpunit_getInvocationMocker() { if ($this->__phpunit_invocationMocker === null) { $this->__phpunit_invocationMocker = new \PHPUnit\Framework\MockObject\InvocationMocker($this->__phpunit_configurable, $this->__phpunit_returnValueGeneration); } return $this->__phpunit_invocationMocker; } public function __phpunit_hasMatchers() { return $this->__phpunit_getInvocationMocker()->hasMatchers(); } public function __phpunit_verify($unsetInvocationMocker = true) { $this->__phpunit_getInvocationMocker()->verify(); if ($unsetInvocationMocker) { $this->__phpunit_invocationMocker = null; } } }
{ "content_hash": "4d34f01c6e148ebcd0563ddf3a582f5f", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 170, "avg_line_length": 28.73856209150327, "alnum_prop": 0.5731180350238799, "repo_name": "rongeb/anit_cms_for_zf3", "id": "e9afc972520cbe8a27115ee405354993e4cebb0a", "size": "4406", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/phpunit/phpunit/tests/Framework/MockObject/Generator/abstract_class.phpt", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "256" }, { "name": "CSS", "bytes": "2694675" }, { "name": "HTML", "bytes": "4886165" }, { "name": "JavaScript", "bytes": "2027617" }, { "name": "PHP", "bytes": "940878" }, { "name": "TSQL", "bytes": "158269" } ], "symlink_target": "" }
__author__ = 'olga' import unittest from gscripts.mapping.map_paired_or_single_with_STAR import MapSTAR import tests import os import shutil import sys class Test(unittest.TestCase): out_dir = 'test_output' def setUp(self): os.mkdir(self.out_dir) def tearDown(self): shutil.rmtree(self.out_dir) def test_map_paired_or_single_with_STAR(self): job_name = 'STAR' out_sh = '{}/{}.sh'.format(self.out_dir, job_name) MapSTAR(genome='/projects/ps-yeolab/genomes/hg19/star_sjdb/', job_name=job_name, out_sh=out_sh, directory='data/', submit=False) true_result = """#!/bin/bash #PBS -N STAR #PBS -o test_output/STAR.sh.out #PBS -e test_output/STAR.sh.err #PBS -V #PBS -l walltime=0:30:00 #PBS -l nodes=1:ppn=8 #PBS -A yeo-group #PBS -q home #PBS -t 1-2%20 # Go to the directory from which the script was called cd $PBS_O_WORKDIR cmd[1]="STAR --runMode alignReads --runThreadN 8 --genomeDir /projects/ps-yeolab/genomes/hg19/star_sjdb/ --genomeLoad LoadAndRemove --readFilesCommand zcat --readFilesIn --outFileNamePrefix ./test1_01. --outReadsUnmapped Fastx --outFilterMismatchNmax 5 --outFilterMismatchNoverLmax 0.3 --outFilterMultimapNmax 5 --outFilterScoreMin 10 --outFilterType BySJout --outSAMattributes All --outSAMstrandField intronMotif --clip5pNbases 0 --clip3pNbases 0 " cmd[2]="STAR --runMode alignReads --runThreadN 8 --genomeDir /projects/ps-yeolab/genomes/hg19/star_sjdb/ --genomeLoad LoadAndRemove --readFilesCommand zcat --readFilesIn --outFileNamePrefix ./test1_02. --outReadsUnmapped Fastx --outFilterMismatchNmax 5 --outFilterMismatchNoverLmax 0.3 --outFilterMultimapNmax 5 --outFilterScoreMin 10 --outFilterType BySJout --outSAMattributes All --outSAMstrandField intronMotif --clip5pNbases 0 --clip3pNbases 0 " eval ${cmd[$PBS_ARRAYID]} """ true_result = true_result.split('\n') # with open(out_sh) as f: # for line in f: # print line, for true, test in zip(true_result, open(out_sh)): self.assertEqual(true.strip().split(), test.strip().split()) if __name__ == "__main__": unittest.main()
{ "content_hash": "16015fadb2f3bcc0fe6cd0987f1ba035", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 595, "avg_line_length": 46.490566037735846, "alnum_prop": 0.606737012987013, "repo_name": "YeoLab/gscripts", "id": "d83a3a92236c39287dc290e7b8f23cd7ab2f95ed", "size": "2464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_map_paired_or_single_with_STAR.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "6662" }, { "name": "Perl", "bytes": "542826" }, { "name": "Python", "bytes": "816916" }, { "name": "R", "bytes": "370788" }, { "name": "Scala", "bytes": "215735" }, { "name": "Shell", "bytes": "12592" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
{ "content_hash": "0a5d4bb03b95ad540977b23ddfcb905a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 90, "avg_line_length": 26.333333333333332, "alnum_prop": 0.6582278481012658, "repo_name": "donnellyk/KVNBoundedImageView", "id": "abff9fd461d008cc8d5790fca8425dd75064656e", "size": "297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/BoundedImageExample/BoundedImageExample/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "24714" }, { "name": "Ruby", "bytes": "741" } ], "symlink_target": "" }
import View from '../lib/View'; import ListResultColumnView from './list-result-col'; class ListResultRowView extends View { constructor(opts) { super(opts); this.viewName = 'result'; this.template = ''; this.tag = 'tr'; this.columnOrder = opts.columnOrder || []; } render() { super.render(); if (this.columnOrder.length === 0) { return this.element; } _.each(this.columnOrder, (colKey) => { let col = new ListResultColumnView(); if (colKey === '_id') { col.model = { value: this.model.id, link: true, baseUrl: ADMIN_LOCALS.baseUrl.toLowerCase(), modelName: ADMIN_LOCALS.modelName.toLowerCase(), id: this.model.id }; } else if (typeof this.model[colKey] !== 'object') { col.model = {value: this.model[colKey]}; } else { if (this.model[colKey]._id) { col.model = { value: this.model[colKey].name ? this.model[colKey].name : (this.model[colKey].label ? this.model[colKey].label : this.model[colKey]._id), link: true, modelName: colKey.toLowerCase(), id: this.model[colKey]._id }; } else { col.model = { value: this.model[colKey] }; } } this.element.appendChild(col.render()); }); return this.element; } } export default ListResultRowView;
{ "content_hash": "99ddc8a310139b953363ea6b5e9a2d3f", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 237, "avg_line_length": 30.209302325581394, "alnum_prop": 0.6066204772902233, "repo_name": "joeyfromspace/administrate", "id": "4bde61d08972edd40cd814612278b8384a249919", "size": "1299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/views/list-result-row.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33660" }, { "name": "HTML", "bytes": "7710" }, { "name": "JavaScript", "bytes": "178349" } ], "symlink_target": "" }
var batched = require("../index") var asyncThing = { _state: { 1: 1 , 2: 2 , 3: 3 } , getAll: function (callback) { var state = this._state process.nextTick(function () { callback(null, state) }) } , get: function (id, callback) { var state = this._state process.nextTick(function () { callback(null, state[id]) }) } , set: function (id, value, callback) { var state = this._state process.nextTick(function () { state[id] = value callback(null) }) } , del: function (id, callback) { var state = this._state process.nextTick(function () { delete state[id] callback(null) }) } } batched(asyncThing) .set("foo", "bar") .set("hello", "world") .del("1") .del("2") .get("3", function (err, result) { console.log("result", result) }) .getAll(function (err, results) { console.log("results!", results) }) .on("error", function () { // no errors! }) .once("finish", function () { console.log("finished") }) console.log("go chain go!")
{ "content_hash": "3013faee6154666b1cb0527c0a364c7e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 43, "avg_line_length": 22.563636363636363, "alnum_prop": 0.48106365834004833, "repo_name": "Raynos/batched", "id": "623ce2a2430dd48ff1c3003392eeee50e16e3571", "size": "1241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/simple.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2810" } ], "symlink_target": "" }