text stringlengths 2 1.04M | meta dict |
|---|---|
// @flow
/**
* @description An MVC-component's builder module.
* @module core/app/connection
* @license MIT
* @author Aleksandr Yackovlev <aleksandryackovlev@yandex.ru>
*/
export interface DbSchemaType {
[key: string]: any;
}
| {
"content_hash": "626056f5faae11c3eb76ecffe10d45b3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 61,
"avg_line_length": 19.833333333333332,
"alnum_prop": 0.6932773109243697,
"repo_name": "StarTag-Team/startag-shop",
"id": "f1db58be70bdecac853d46ddee10322c060e5e2b",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core/app/connection/schema/schema.i.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "347"
},
{
"name": "JavaScript",
"bytes": "5645308"
}
],
"symlink_target": ""
} |
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define((function(require) {
factory(require("devextreme/localization"))
}))
} else if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}(0, (function(localization) {
localization.loadMessages({
hu: {
Yes: "Igen",
No: "Nem",
Cancel: "M\xe9gse",
Clear: "T\xf6rl\xe9s",
Done: "K\xe9sz",
Loading: "Bet\xf6lt\xe9s...",
Select: "V\xe1laszt\xe1s...",
Search: "Keres\xe9s",
Back: "Vissza",
OK: "OK",
"dxCollectionWidget-noDataText": "Nincs megjelen\xedthet\u0151 adat",
"dxDropDownEditor-selectLabel": "V\xe1laszt\xe1s",
"validation-required": "K\xf6telez\u0151",
"validation-required-formatted": "{0} k\xf6telez\u0151",
"validation-numeric": "Az \xe9rt\xe9k sz\xe1m kell legyen",
"validation-numeric-formatted": "{0} sz\xe1m kell legyen",
"validation-range": "Az \xe9rt\xe9k tartom\xe1nyon k\xedv\xfclre esik",
"validation-range-formatted": "{0} tartom\xe1nyon k\xedv\xfclre esik",
"validation-stringLength": "Az \xe9rt\xe9k hossza helytelen",
"validation-stringLength-formatted": "{0} hossza helytelen",
"validation-custom": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"validation-custom-formatted": "{0} \xe9rv\xe9nytelen",
"validation-async": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"validation-async-formatted": "{0} \xe9rv\xe9nytelen",
"validation-compare": "Az \xe9rt\xe9kek nem egyeznek",
"validation-compare-formatted": "{0} nem egyezik",
"validation-pattern": "Az \xe9rt\xe9k nem illeszthet\u0151 a mint\xe1ra",
"validation-pattern-formatted": "{0} nem illeszthet\u0151 a mint\xe1ra",
"validation-email": "\xc9rv\xe9nytelen email",
"validation-email-formatted": "{0} \xe9rv\xe9nytelen email",
"validation-mask": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"dxLookup-searchPlaceholder": "Minimum karaktersz\xe1m: {0}",
"dxList-pullingDownText": "H\xfazza le a friss\xedt\xe9shez...",
"dxList-pulledDownText": "Engedje el a friss\xedt\xe9shez...",
"dxList-refreshingText": "Friss\xedt\xe9s...",
"dxList-pageLoadingText": "Bet\xf6lt\xe9s...",
"dxList-nextButtonText": "Tov\xe1bb",
"dxList-selectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxListEditDecorator-delete": "T\xf6rl\xe9s",
"dxListEditDecorator-more": "T\xf6bb",
"dxScrollView-pullingDownText": "H\xfazza le a friss\xedt\xe9shez...",
"dxScrollView-pulledDownText": "Engedje el a friss\xedt\xe9shez...",
"dxScrollView-refreshingText": "Friss\xedt\xe9s...",
"dxScrollView-reachBottomText": "Bet\xf6lt\xe9s...",
"dxDateBox-simulatedDataPickerTitleTime": "V\xe1lasszon id\u0151t",
"dxDateBox-simulatedDataPickerTitleDate": "V\xe1lasszon d\xe1tumot",
"dxDateBox-simulatedDataPickerTitleDateTime": "V\xe1lasszon d\xe1tumot \xe9s id\u0151t",
"dxDateBox-validation-datetime": "Az \xe9rt\xe9k d\xe1tum vagy id\u0151 kell legyen",
"dxFileUploader-selectFile": "V\xe1lasszon f\xe1jlt",
"dxFileUploader-dropFile": "vagy h\xfazza a f\xe1jlt ide",
"dxFileUploader-bytes": "b\xe1jt",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "Felt\xf6lt\xe9s",
"dxFileUploader-uploaded": "Felt\xf6ltve",
"dxFileUploader-readyToUpload": "Felt\xf6lt\xe9sre k\xe9sz",
"dxFileUploader-uploadAbortedMessage": "TODO",
"dxFileUploader-uploadFailedMessage": "A felt\xf6lt\xe9s sikertelen",
"dxFileUploader-invalidFileExtension": "Nem enged\xe9lyezett f\xe1jlt\xedpus",
"dxFileUploader-invalidMaxFileSize": "T\xfal nagy f\xe1jl",
"dxFileUploader-invalidMinFileSize": "T\xfal kicsi f\xe1jl",
"dxRangeSlider-ariaFrom": "-t\xf3l",
"dxRangeSlider-ariaTill": "-ig",
"dxSwitch-switchedOnText": "BE",
"dxSwitch-switchedOffText": "KI",
"dxForm-optionalMark": "v\xe1laszthat\xf3",
"dxForm-requiredMessage": "{0} k\xf6telez\u0151",
"dxNumberBox-invalidValueMessage": "Az \xe9rt\xe9k sz\xe1m kell legyen",
"dxNumberBox-noDataText": "Nincs adat",
"dxDataGrid-columnChooserTitle": "Oszlopv\xe1laszt\xf3",
"dxDataGrid-columnChooserEmptyText": "H\xfazza ide az oszlopot az elrejt\xe9shez",
"dxDataGrid-groupContinuesMessage": "A k\xf6vetkez\u0151 oldalon folytat\xf3dik",
"dxDataGrid-groupContinuedMessage": "Folytat\xe1s az el\u0151z\u0151 oldalr\xf3l",
"dxDataGrid-groupHeaderText": "Csoportos\xedt\xe1s ezen oszlop szerint",
"dxDataGrid-ungroupHeaderText": "Csoportbont\xe1s",
"dxDataGrid-ungroupAllText": "\xd6sszes csoportbont\xe1sa",
"dxDataGrid-editingEditRow": "Szerkeszt\xe9s",
"dxDataGrid-editingSaveRowChanges": "Ment\xe9s",
"dxDataGrid-editingCancelRowChanges": "M\xe9gse",
"dxDataGrid-editingDeleteRow": "T\xf6rl\xe9s",
"dxDataGrid-editingUndeleteRow": "Vissza\xe1ll\xedt\xe1s",
"dxDataGrid-editingConfirmDeleteMessage": "Biztosan t\xf6rli ezt a rekordot?",
"dxDataGrid-validationCancelChanges": "M\xf3dos\xedt\xe1sok elvet\xe9se",
"dxDataGrid-groupPanelEmptyText": "H\xfazzon ide egy oszlopfejl\xe9cet a csoportos\xedt\xe1shoz",
"dxDataGrid-noDataText": "Nincs adat",
"dxDataGrid-searchPanelPlaceholder": "Keres\xe9s...",
"dxDataGrid-filterRowShowAllText": "(Mind)",
"dxDataGrid-filterRowResetOperationText": "Vissza\xe1ll\xedt\xe1s",
"dxDataGrid-filterRowOperationEquals": "Egyenl\u0151",
"dxDataGrid-filterRowOperationNotEquals": "Nem egyenl\u0151",
"dxDataGrid-filterRowOperationLess": "Kisebb",
"dxDataGrid-filterRowOperationLessOrEquals": "Kisebb vagy egyenl\u0151",
"dxDataGrid-filterRowOperationGreater": "Nagyobb",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Nagyobb vagy egyenl\u0151",
"dxDataGrid-filterRowOperationStartsWith": "Kezd\u0151dik",
"dxDataGrid-filterRowOperationContains": "Tartalmazza",
"dxDataGrid-filterRowOperationNotContains": "Nem tartalmazza",
"dxDataGrid-filterRowOperationEndsWith": "V\xe9gz\u0151dik",
"dxDataGrid-filterRowOperationBetween": "K\xf6z\xf6tt",
"dxDataGrid-filterRowOperationBetweenStartText": "Kezdete",
"dxDataGrid-filterRowOperationBetweenEndText": "V\xe9ge",
"dxDataGrid-applyFilterText": "Sz\u0171r\u0151 alkalmaz\xe1sa",
"dxDataGrid-trueText": "igaz",
"dxDataGrid-falseText": "hamis",
"dxDataGrid-sortingAscendingText": "N\xf6vekv\u0151",
"dxDataGrid-sortingDescendingText": "Cs\xf6kken\u0151",
"dxDataGrid-sortingClearText": "Rendez\xe9s t\xf6rl\xe9se",
"dxDataGrid-editingSaveAllChanges": "M\xf3dos\xedt\xe1sok ment\xe9se",
"dxDataGrid-editingCancelAllChanges": "M\xf3dos\xedt\xe1sok elvet\xe9se",
"dxDataGrid-editingAddRow": "Sor hozz\xe1ad\xe1sa",
"dxDataGrid-summaryMin": "Minimum: {0}",
"dxDataGrid-summaryMinOtherColumn": "{1} minimuma: {0}",
"dxDataGrid-summaryMax": "Maximum: {0}",
"dxDataGrid-summaryMaxOtherColumn": "{1} maximuma: {0}",
"dxDataGrid-summaryAvg": "\xc1tlag: {0}",
"dxDataGrid-summaryAvgOtherColumn": "{1} \xe1tlaga: {0}",
"dxDataGrid-summarySum": "\xd6sszeg: {0}",
"dxDataGrid-summarySumOtherColumn": "{1} \xf6sszege: {0}",
"dxDataGrid-summaryCount": "Darabsz\xe1m: {0}",
"dxDataGrid-columnFixingFix": "R\xf6gz\xedt\xe9s",
"dxDataGrid-columnFixingUnfix": "Felold\xe1s",
"dxDataGrid-columnFixingLeftPosition": "Balra",
"dxDataGrid-columnFixingRightPosition": "Jobbra",
"dxDataGrid-exportTo": "Export\xe1l\xe1s",
"dxDataGrid-exportToExcel": "Export\xe1l\xe1s Excel f\xe1jlba",
"dxDataGrid-exporting": "Export\xe1l\xe1s...",
"dxDataGrid-excelFormat": "Excel f\xe1jl",
"dxDataGrid-selectedRows": "Kiv\xe1lasztott sorok",
"dxDataGrid-exportSelectedRows": "Kiv\xe1lasztott sorok export\xe1l\xe1sa",
"dxDataGrid-exportAll": "Az \xf6sszes adat export\xe1l\xe1sa",
"dxDataGrid-headerFilterEmptyValue": "(\xdcresek)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "M\xe9gse",
"dxDataGrid-ariaColumn": "Oszlop",
"dxDataGrid-ariaValue": "\xc9rt\xe9k",
"dxDataGrid-ariaFilterCell": "Sz\u0171r\u0151 cella",
"dxDataGrid-ariaCollapse": "\xd6sszecsuk\xe1s",
"dxDataGrid-ariaExpand": "Kibont\xe1s",
"dxDataGrid-ariaDataGrid": "Adatr\xe1cs",
"dxDataGrid-ariaSearchInGrid": "Keres\xe9s az adatr\xe1csban",
"dxDataGrid-ariaSelectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxDataGrid-ariaSelectRow": "Sor kiv\xe1laszt\xe1sa",
"dxDataGrid-filterBuilderPopupTitle": "Sz\u0171r\u0151k\xe9sz\xedt\u0151",
"dxDataGrid-filterPanelCreateFilter": "Sz\u0171r\u0151 l\xe9trehoz\xe1sa",
"dxDataGrid-filterPanelClearFilter": "T\xf6rl\xe9s",
"dxDataGrid-filterPanelFilterEnabledHint": "Sz\u0171r\u0151 enged\xe9lyez\xe9se",
"dxTreeList-ariaTreeList": "Fa lista",
"dxTreeList-editingAddRowToNode": "Hozz\xe1ad\xe1s",
"dxPager-infoText": "Oldal: {0}/{1} ({2} elem)",
"dxPager-pagesCountText": "/",
"dxPager-pageSizesAllText": "Mind",
"dxPivotGrid-grandTotal": "Teljes \xf6sszeg",
"dxPivotGrid-total": "{0} \xd6sszeg",
"dxPivotGrid-fieldChooserTitle": "Mez\u0151v\xe1laszt\xf3",
"dxPivotGrid-showFieldChooser": "Mez\u0151v\xe1laszt\xf3 megjelen\xedt\xe9se",
"dxPivotGrid-expandAll": "\xd6sszes kibont\xe1sa",
"dxPivotGrid-collapseAll": "\xd6sszes \xf6sszecsuk\xe1sa",
"dxPivotGrid-sortColumnBySummary": 'Rendez\xe9s "{0}" ezen oszlop alapj\xe1n',
"dxPivotGrid-sortRowBySummary": 'Rendez\xe9s "{0}" ezen sor alapj\xe1n',
"dxPivotGrid-removeAllSorting": "\xd6sszes rendez\xe9s t\xf6rl\xe9se",
"dxPivotGrid-dataNotAvailable": "N/A",
"dxPivotGrid-rowFields": "Sormez\u0151",
"dxPivotGrid-columnFields": "Oszlopmez\u0151",
"dxPivotGrid-dataFields": "Adatmez\u0151",
"dxPivotGrid-filterFields": "Sz\u0171r\u0151mez\u0151",
"dxPivotGrid-allFields": "\xd6sszes mez\u0151",
"dxPivotGrid-columnFieldArea": "H\xfazza az oszlopmez\u0151ket ide",
"dxPivotGrid-dataFieldArea": "H\xfazza az adatmez\u0151ket ide",
"dxPivotGrid-rowFieldArea": "H\xfazza a sormez\u0151ket ide",
"dxPivotGrid-filterFieldArea": "H\xfazza a sz\u0171r\u0151mez\u0151ket ide",
"dxScheduler-editorLabelTitle": "T\xe1rgy",
"dxScheduler-editorLabelStartDate": "Kezd\xe9s d\xe1tuma",
"dxScheduler-editorLabelEndDate": "Befejez\xe9s d\xe1tuma",
"dxScheduler-editorLabelDescription": "Le\xedr\xe1s",
"dxScheduler-editorLabelRecurrence": "Ism\xe9tl\u0151d\xe9s",
"dxScheduler-openAppointment": "Tal\xe1lkoz\xf3 megnyit\xe1sa",
"dxScheduler-recurrenceNever": "Soha",
"dxScheduler-recurrenceMinutely": "Minutely",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "Naponta",
"dxScheduler-recurrenceWeekly": "Hetente",
"dxScheduler-recurrenceMonthly": "Havonta",
"dxScheduler-recurrenceYearly": "\xc9vente",
"dxScheduler-recurrenceRepeatEvery": "Ism\xe9tl\u0151d\xe9s minden",
"dxScheduler-recurrenceRepeatOn": "Ism\xe9tl\u0151d\xe9s",
"dxScheduler-recurrenceEnd": "Ism\xe9tl\u0151d\xe9s v\xe9ge",
"dxScheduler-recurrenceAfter": "Ut\xe1n",
"dxScheduler-recurrenceOn": "Ekkor",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "nap(ok)",
"dxScheduler-recurrenceRepeatWeekly": "h\xe9t(ek)",
"dxScheduler-recurrenceRepeatMonthly": "h\xf3nap(ok)",
"dxScheduler-recurrenceRepeatYearly": "\xe9v(ek)",
"dxScheduler-switcherDay": "Nap",
"dxScheduler-switcherWeek": "H\xe9t",
"dxScheduler-switcherWorkWeek": "Munkah\xe9t",
"dxScheduler-switcherMonth": "H\xf3nap",
"dxScheduler-switcherAgenda": "Napt\xe1r",
"dxScheduler-switcherTimelineDay": "Id\u0151vonal nap",
"dxScheduler-switcherTimelineWeek": "Id\u0151vonal h\xe9t",
"dxScheduler-switcherTimelineWorkWeek": "Id\u0151vonal munkah\xe9t",
"dxScheduler-switcherTimelineMonth": "Id\u0151vonal h\xf3nap",
"dxScheduler-recurrenceRepeatOnDate": "d\xe1tumon",
"dxScheduler-recurrenceRepeatCount": "el\u0151fordul\xe1s(ok)",
"dxScheduler-allDay": "Eg\xe9sz nap",
"dxScheduler-confirmRecurrenceEditMessage": "Csak ezt az alkalmat szeretn\xe9 szerkeszteni, vagy az \xf6sszes ism\xe9tl\u0151d\xe9st?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Csak ezt az alkalmat szeretn\xe9 t\xf6r\xf6lni, vagy az \xf6sszes ism\xe9tl\u0151d\xe9st?",
"dxScheduler-confirmRecurrenceEditSeries": "Ism\xe9tl\u0151d\xe9s szerkeszt\xe9se",
"dxScheduler-confirmRecurrenceDeleteSeries": "Ism\xe9tl\u0151d\xe9s t\xf6rl\xe9se",
"dxScheduler-confirmRecurrenceEditOccurrence": "Alkalom szerkeszt\xe9se",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Alkalom t\xf6rl\xe9se",
"dxScheduler-noTimezoneTitle": "Nincs id\u0151z\xf3na",
"dxScheduler-moreAppointments": "{0} t\xf6bb",
"dxCalendar-todayButtonText": "Ma",
"dxCalendar-ariaWidgetName": "Napt\xe1r",
"dxColorView-ariaRed": "Piros",
"dxColorView-ariaGreen": "Z\xf6ld",
"dxColorView-ariaBlue": "K\xe9k",
"dxColorView-ariaAlpha": "\xc1tl\xe1tsz\xf3s\xe1g",
"dxColorView-ariaHex": "Sz\xednk\xf3d",
"dxTagBox-selected": "{0} kiv\xe1lasztva",
"dxTagBox-allSelected": "\xd6sszes kiv\xe1lasztva ({0})",
"dxTagBox-moreSelected": "{0} t\xf6bb",
"vizExport-printingButtonText": "Nyomtat\xe1s",
"vizExport-titleMenuText": "Export\xe1l\xe1s/Nyomtat\xe1s",
"vizExport-exportButtonText": "{0} f\xe1jl",
"dxFilterBuilder-and": "\xc9s",
"dxFilterBuilder-or": "Vagy",
"dxFilterBuilder-notAnd": "Nem \xc9s",
"dxFilterBuilder-notOr": "Nem Vagy",
"dxFilterBuilder-addCondition": "Felt\xe9tel hozz\xe1ad\xe1sa",
"dxFilterBuilder-addGroup": "Csoport hozz\xe1ad\xe1sa",
"dxFilterBuilder-enterValueText": "<\xedrjon be egy \xe9rt\xe9ket>",
"dxFilterBuilder-filterOperationEquals": "Egyenl\u0151",
"dxFilterBuilder-filterOperationNotEquals": "Nem egyenl\u0151",
"dxFilterBuilder-filterOperationLess": "Kisebb",
"dxFilterBuilder-filterOperationLessOrEquals": "Kisebb vagy egyenl\u0151",
"dxFilterBuilder-filterOperationGreater": "Nagyobb",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Nagyobb vagy egyenl\u0151",
"dxFilterBuilder-filterOperationStartsWith": "Kezd\u0151dik",
"dxFilterBuilder-filterOperationContains": "Tartalmazza",
"dxFilterBuilder-filterOperationNotContains": "Nem tartalmazza",
"dxFilterBuilder-filterOperationEndsWith": "V\xe9gz\u0151dik",
"dxFilterBuilder-filterOperationIsBlank": "\xdcres",
"dxFilterBuilder-filterOperationIsNotBlank": "Nem \xfcres",
"dxFilterBuilder-filterOperationBetween": "K\xf6z\xf6tt",
"dxFilterBuilder-filterOperationAnyOf": "Valamelyik",
"dxFilterBuilder-filterOperationNoneOf": "Egyik sem",
"dxHtmlEditor-dialogColorCaption": "Bet\u0171sz\xedn v\xe1laszt\xe1s",
"dxHtmlEditor-dialogBackgroundCaption": "H\xe1tt\xe9rsz\xedn v\xe1laszt\xe1s",
"dxHtmlEditor-dialogLinkCaption": "Link hozz\xe1ad\xe1sa",
"dxHtmlEditor-dialogLinkUrlField": "URL",
"dxHtmlEditor-dialogLinkTextField": "Sz\xf6veg",
"dxHtmlEditor-dialogLinkTargetField": "Link megnyit\xe1sa \xfaj ablakban",
"dxHtmlEditor-dialogImageCaption": "K\xe9p hozz\xe1ad\xe1sa",
"dxHtmlEditor-dialogImageUrlField": "URL",
"dxHtmlEditor-dialogImageAltField": "Alternat\xedv sz\xf6veg",
"dxHtmlEditor-dialogImageWidthField": "Sz\xe9less\xe9g (px)",
"dxHtmlEditor-dialogImageHeightField": "Magass\xe1g (px)",
"dxHtmlEditor-dialogInsertTableRowsField": "!TODO",
"dxHtmlEditor-dialogInsertTableColumnsField": "!TODO",
"dxHtmlEditor-dialogInsertTableCaption": "!TODO",
"dxHtmlEditor-dialogUpdateImageCaption": "!TODO",
"dxHtmlEditor-dialogImageUpdateButton": "!TODO",
"dxHtmlEditor-dialogImageAddButton": "!TODO",
"dxHtmlEditor-dialogImageSpecifyUrl": "!TODO",
"dxHtmlEditor-dialogImageSelectFile": "!TODO",
"dxHtmlEditor-dialogImageKeepAspectRatio": "!TODO",
"dxHtmlEditor-dialogImageEncodeToBase64": "!TODO",
"dxHtmlEditor-heading": "Fejl\xe9c",
"dxHtmlEditor-normalText": "Norm\xe1l sz\xf6veg",
"dxHtmlEditor-background": "TODO",
"dxHtmlEditor-bold": "TODO",
"dxHtmlEditor-color": "TODO",
"dxHtmlEditor-font": "TODO",
"dxHtmlEditor-italic": "TODO",
"dxHtmlEditor-link": "TODO",
"dxHtmlEditor-image": "TODO",
"dxHtmlEditor-size": "TODO",
"dxHtmlEditor-strike": "TODO",
"dxHtmlEditor-subscript": "TODO",
"dxHtmlEditor-superscript": "TODO",
"dxHtmlEditor-underline": "TODO",
"dxHtmlEditor-blockquote": "TODO",
"dxHtmlEditor-header": "TODO",
"dxHtmlEditor-increaseIndent": "TODO",
"dxHtmlEditor-decreaseIndent": "TODO",
"dxHtmlEditor-orderedList": "TODO",
"dxHtmlEditor-bulletList": "TODO",
"dxHtmlEditor-alignLeft": "TODO",
"dxHtmlEditor-alignCenter": "TODO",
"dxHtmlEditor-alignRight": "TODO",
"dxHtmlEditor-alignJustify": "TODO",
"dxHtmlEditor-codeBlock": "TODO",
"dxHtmlEditor-variable": "TODO",
"dxHtmlEditor-undo": "TODO",
"dxHtmlEditor-redo": "TODO",
"dxHtmlEditor-clear": "TODO",
"dxHtmlEditor-insertTable": "TODO",
"dxHtmlEditor-insertHeaderRow": "TODO",
"dxHtmlEditor-insertRowAbove": "TODO",
"dxHtmlEditor-insertRowBelow": "TODO",
"dxHtmlEditor-insertColumnLeft": "TODO",
"dxHtmlEditor-insertColumnRight": "TODO",
"dxHtmlEditor-deleteColumn": "TODO",
"dxHtmlEditor-deleteRow": "TODO",
"dxHtmlEditor-deleteTable": "TODO",
"dxHtmlEditor-cellProperties": "TODO",
"dxHtmlEditor-tableProperties": "TODO",
"dxHtmlEditor-insert": "TODO",
"dxHtmlEditor-delete": "TODO",
"dxHtmlEditor-border": "TODO",
"dxHtmlEditor-style": "TODO",
"dxHtmlEditor-width": "TODO",
"dxHtmlEditor-height": "TODO",
"dxHtmlEditor-borderColor": "TODO",
"dxHtmlEditor-tableBackground": "TODO",
"dxHtmlEditor-dimensions": "TODO",
"dxHtmlEditor-alignment": "TODO",
"dxHtmlEditor-horizontal": "TODO",
"dxHtmlEditor-vertical": "TODO",
"dxHtmlEditor-paddingVertical": "TODO",
"dxHtmlEditor-paddingHorizontal": "TODO",
"dxHtmlEditor-pixels": "TODO",
"dxHtmlEditor-list": "TODO",
"dxHtmlEditor-ordered": "TODO",
"dxHtmlEditor-bullet": "TODO",
"dxHtmlEditor-align": "TODO",
"dxHtmlEditor-center": "TODO",
"dxHtmlEditor-left": "TODO",
"dxHtmlEditor-right": "TODO",
"dxHtmlEditor-indent": "TODO",
"dxHtmlEditor-justify": "TODO",
"dxFileManager-newDirectoryName": "N\xe9vtelen k\xf6nyvt\xe1r",
"dxFileManager-rootDirectoryName": "F\xe1jlok",
"dxFileManager-errorNoAccess": "Hozz\xe1f\xe9r\xe9s megtagadva. A m\u0171veletet nem lehet befejezni.",
"dxFileManager-errorDirectoryExistsFormat": "'{0}' nev\u0171 k\xf6nyvt\xe1r m\xe1r l\xe9tezik.",
"dxFileManager-errorFileExistsFormat": "'{0}' nev\u0171 f\xe1jl m\xe1r l\xe9tezik.",
"dxFileManager-errorFileNotFoundFormat": "'{0}' nev\u0171 f\xe1jl nem tal\xe1lhat\xf3",
"dxFileManager-errorDirectoryNotFoundFormat": "'{0}' nev\u0171 k\xf6nyvt\xe1r nem tal\xe1lhat\xf3",
"dxFileManager-errorWrongFileExtension": "Nem enged\xe9lyezett f\xe1jlt\xedpus",
"dxFileManager-errorMaxFileSizeExceeded": "A f\xe1jlm\xe9ret meghaladja a megengedett legnagyobb m\xe9retet",
"dxFileManager-errorDefault": "Ismeretlen hiba.",
"dxFileManager-errorDirectoryOpenFailed": "TODO",
"dxDiagram-categoryGeneral": "\xc1ltal\xe1nos",
"dxDiagram-categoryFlowchart": "Folyamat\xe1bra",
"dxDiagram-categoryOrgChart": "Szervezeti \xe1bra",
"dxDiagram-categoryContainers": "T\xe1rol\xf3k",
"dxDiagram-categoryCustom": "Egyedi",
"dxDiagram-commandExportToSvg": "Export\xe1l\xe1s SVG-be",
"dxDiagram-commandExportToPng": "Export\xe1l\xe1s PNG-be",
"dxDiagram-commandExportToJpg": "Export\xe1l\xe1s JPEG-be",
"dxDiagram-commandUndo": "Visszavon\xe1s",
"dxDiagram-commandRedo": "\xdajra",
"dxDiagram-commandFontName": "Bet\u0171t\xedpus",
"dxDiagram-commandFontSize": "Bet\u0171m\xe9ret",
"dxDiagram-commandBold": "F\xe9lk\xf6v\xe9r",
"dxDiagram-commandItalic": "D\u0151lt",
"dxDiagram-commandUnderline": "Al\xe1h\xfazott",
"dxDiagram-commandTextColor": "Bet\u0171sz\xedn",
"dxDiagram-commandLineColor": "Sor sz\xedne",
"dxDiagram-commandLineWidth": "TODO",
"dxDiagram-commandLineStyle": "TODO",
"dxDiagram-commandLineStyleSolid": "TODO",
"dxDiagram-commandLineStyleDotted": "TODO",
"dxDiagram-commandLineStyleDashed": "TODO",
"dxDiagram-commandFillColor": "Kit\xf6lt\u0151 sz\xedn",
"dxDiagram-commandAlignLeft": "Balra igaz\xedt\xe1s",
"dxDiagram-commandAlignCenter": "K\xf6z\xe9pre igaz\xedt\xe1s",
"dxDiagram-commandAlignRight": "Jobbra igaz\xedt\xe1s",
"dxDiagram-commandConnectorLineType": "\xd6sszek\xf6t\u0151 vonal t\xedpusa",
"dxDiagram-commandConnectorLineStraight": "Egyenes",
"dxDiagram-commandConnectorLineOrthogonal": "Mer\u0151leges",
"dxDiagram-commandConnectorLineStart": "\xd6sszek\xf6t\u0151 vonal kezdete",
"dxDiagram-commandConnectorLineEnd": "\xd6sszek\xf6t\u0151 vonal v\xe9ge",
"dxDiagram-commandConnectorLineNone": "Egyik sem",
"dxDiagram-commandConnectorLineArrow": "Ny\xedl",
"dxDiagram-commandFullscreen": "Teljes k\xe9perny\u0151",
"dxDiagram-commandUnits": "Egys\xe9gek",
"dxDiagram-commandPageSize": "Lapm\xe9ret",
"dxDiagram-commandPageOrientation": "T\xe1jol\xe1s",
"dxDiagram-commandPageOrientationLandscape": "Fekv\u0151",
"dxDiagram-commandPageOrientationPortrait": "\xc1ll\xf3",
"dxDiagram-commandPageColor": "Oldal sz\xedne",
"dxDiagram-commandShowGrid": "R\xe1cs megjelen\xedt\xe9se",
"dxDiagram-commandSnapToGrid": "R\xe1cshoz igaz\xedt\xe1s",
"dxDiagram-commandGridSize": "R\xe1cs m\xe9rete",
"dxDiagram-commandZoomLevel": "Nagy\xedt\xe1s",
"dxDiagram-commandAutoZoom": "Automatikus nagy\xedt\xe1s",
"dxDiagram-commandFitToContent": "TODO",
"dxDiagram-commandFitToWidth": "TODO",
"dxDiagram-commandAutoZoomByContent": "TODO",
"dxDiagram-commandAutoZoomByWidth": "TODO",
"dxDiagram-commandSimpleView": "Egyszer\u0171s\xedtett n\xe9zet",
"dxDiagram-commandCut": "Kiv\xe1g\xe1s",
"dxDiagram-commandCopy": "M\xe1sol\xe1s",
"dxDiagram-commandPaste": "Beilleszt\xe9s",
"dxDiagram-commandSelectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxDiagram-commandDelete": "T\xf6rl\xe9s",
"dxDiagram-commandBringToFront": "El\u0151re hoz",
"dxDiagram-commandSendToBack": "H\xe1tra k\xfcld",
"dxDiagram-commandLock": "R\xf6gz\xedt",
"dxDiagram-commandUnlock": "Felold",
"dxDiagram-commandInsertShapeImage": "K\xe9p besz\xfar\xe1sa...",
"dxDiagram-commandEditShapeImage": "K\xe9p cser\xe9je...",
"dxDiagram-commandDeleteShapeImage": "K\xe9p t\xf6rl\xe9se",
"dxDiagram-commandLayoutLeftToRight": "TODO",
"dxDiagram-commandLayoutRightToLeft": "TODO",
"dxDiagram-commandLayoutTopToBottom": "TODO",
"dxDiagram-commandLayoutBottomToTop": "TODO",
"dxDiagram-unitIn": "in",
"dxDiagram-unitCm": "cm",
"dxDiagram-unitPx": "px",
"dxDiagram-dialogButtonOK": "OK",
"dxDiagram-dialogButtonCancel": "M\xe9gse",
"dxDiagram-dialogInsertShapeImageTitle": "K\xe9p besz\xfar\xe1sa",
"dxDiagram-dialogEditShapeImageTitle": "K\xe9p cser\xe9je",
"dxDiagram-dialogEditShapeImageSelectButton": "K\xe9p kiv\xe1laszt\xe1sa",
"dxDiagram-dialogEditShapeImageLabelText": "vagy h\xfazza a f\xe1jlt ide",
"dxDiagram-uiExport": "Export\xe1l\xe1s",
"dxDiagram-uiProperties": "Tulajdons\xe1gok",
"dxDiagram-uiSettings": "TODO",
"dxDiagram-uiShowToolbox": "TODO",
"dxDiagram-uiSearch": "TODO",
"dxDiagram-uiStyle": "TODO",
"dxDiagram-uiLayout": "TODO",
"dxDiagram-uiLayoutTree": "Fa",
"dxDiagram-uiLayoutLayered": "R\xe9teges",
"dxDiagram-uiDiagram": "TODO",
"dxDiagram-uiText": "TODO",
"dxDiagram-uiObject": "TODO",
"dxDiagram-uiConnector": "TODO",
"dxDiagram-uiPage": "TODO",
"dxDiagram-shapeText": "TODO",
"dxDiagram-shapeRectangle": "TODO",
"dxDiagram-shapeEllipse": "TODO",
"dxDiagram-shapeCross": "TODO",
"dxDiagram-shapeTriangle": "TODO",
"dxDiagram-shapeDiamond": "TODO",
"dxDiagram-shapeHeart": "TODO",
"dxDiagram-shapePentagon": "TODO",
"dxDiagram-shapeHexagon": "TODO",
"dxDiagram-shapeOctagon": "TODO",
"dxDiagram-shapeStar": "TODO",
"dxDiagram-shapeArrowLeft": "TODO",
"dxDiagram-shapeArrowUp": "TODO",
"dxDiagram-shapeArrowRight": "TODO",
"dxDiagram-shapeArrowDown": "TODO",
"dxDiagram-shapeArrowUpDown": "TODO",
"dxDiagram-shapeArrowLeftRight": "TODO",
"dxDiagram-shapeProcess": "TODO",
"dxDiagram-shapeDecision": "TODO",
"dxDiagram-shapeTerminator": "TODO",
"dxDiagram-shapePredefinedProcess": "TODO",
"dxDiagram-shapeDocument": "TODO",
"dxDiagram-shapeMultipleDocuments": "TODO",
"dxDiagram-shapeManualInput": "TODO",
"dxDiagram-shapePreparation": "TODO",
"dxDiagram-shapeData": "TODO",
"dxDiagram-shapeDatabase": "TODO",
"dxDiagram-shapeHardDisk": "TODO",
"dxDiagram-shapeInternalStorage": "TODO",
"dxDiagram-shapePaperTape": "TODO",
"dxDiagram-shapeManualOperation": "TODO",
"dxDiagram-shapeDelay": "TODO",
"dxDiagram-shapeStoredData": "TODO",
"dxDiagram-shapeDisplay": "TODO",
"dxDiagram-shapeMerge": "TODO",
"dxDiagram-shapeConnector": "TODO",
"dxDiagram-shapeOr": "TODO",
"dxDiagram-shapeSummingJunction": "TODO",
"dxDiagram-shapeContainerDefaultText": "TODO",
"dxDiagram-shapeVerticalContainer": "TODO",
"dxDiagram-shapeHorizontalContainer": "TODO",
"dxDiagram-shapeCardDefaultText": "TODO",
"dxDiagram-shapeCardWithImageOnLeft": "TODO",
"dxDiagram-shapeCardWithImageOnTop": "TODO",
"dxDiagram-shapeCardWithImageOnRight": "TODO",
"dxGantt-dialogTitle": "TODO",
"dxGantt-dialogStartTitle": "TODO",
"dxGantt-dialogEndTitle": "TODO",
"dxGantt-dialogProgressTitle": "TODO",
"dxGantt-dialogResourcesTitle": "TODO",
"dxGantt-dialogResourceManagerTitle": "TODO",
"dxGantt-dialogTaskDetailsTitle": "TODO",
"dxGantt-dialogEditResourceListHint": "TODO",
"dxGantt-dialogEditNoResources": "TODO",
"dxGantt-dialogButtonAdd": "TODO",
"dxGantt-contextMenuNewTask": "TODO",
"dxGantt-contextMenuNewSubtask": "TODO",
"dxGantt-contextMenuDeleteTask": "TODO",
"dxGantt-contextMenuDeleteDependency": "TODO",
"dxGantt-dialogTaskDeleteConfirmation": "TODO",
"dxGantt-dialogDependencyDeleteConfirmation": "TODO",
"dxGantt-dialogResourcesDeleteConfirmation": "TODO",
"dxGantt-dialogConstraintCriticalViolationMessage": "TODO",
"dxGantt-dialogConstraintViolationMessage": "TODO",
"dxGantt-dialogCancelOperationMessage": "TODO",
"dxGantt-dialogDeleteDependencyMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO",
"dxGantt-dialogConstraintCriticalViolationSeveralTasksMessage": "TODO",
"dxGantt-dialogConstraintViolationSeveralTasksMessage": "TODO",
"dxGantt-dialogDeleteDependenciesMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependenciesMessage": "TODO",
"dxGantt-undo": "TODO",
"dxGantt-redo": "TODO",
"dxGantt-expandAll": "TODO",
"dxGantt-collapseAll": "TODO",
"dxGantt-addNewTask": "TODO",
"dxGantt-deleteSelectedTask": "TODO",
"dxGantt-zoomIn": "TODO",
"dxGantt-zoomOut": "TODO",
"dxGantt-fullScreen": "TODO",
"dxGantt-quarter": "TODO",
"dxGantt-sortingAscendingText": "N\xf6vekv\u0151",
"dxGantt-sortingDescendingText": "Cs\xf6kken\u0151",
"dxGantt-sortingClearText": "Rendez\xe9s t\xf6rl\xe9se",
"dxGantt-showResources": "TODO",
"dxGantt-showDependencies": "TODO",
"dxGantt-dialogStartDateValidation": "TODO",
"dxGantt-dialogEndDateValidation": "TODO"
}
})
}));
| {
"content_hash": "dd9c9539346f4cd23189da42e38098e7",
"timestamp": "",
"source": "github",
"line_count": 542,
"max_line_length": 150,
"avg_line_length": 60.42988929889299,
"alnum_prop": 0.608951851738772,
"repo_name": "cdnjs/cdnjs",
"id": "cda914bdaeb4617c26401675ba871a28fe3efc94",
"size": "32990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/devextreme/22.1.3/js/localization/dx.messages.hu.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'''
Copyright (c) 2011, Universidad Industrial de Santander, Colombia
University of Delaware
All rights reserved.
@author: Sergio Pino
@author: Henry Arguello
Website: http://www.eecis.udel.edu/
emails : sergiop@udel.edu - henarfu@udel.edu
Date : Jul, 2011
'''
from receiver.RxUsrp import RxUSRP
from receiver.RXData import RXData
from receiver.RXControlApp import RXControlApp
from gnuradio import gr
import time
class RXApp(object):
'''
Application life cycle
'''
def __init__(self, fc, dec, gain, eth, sync, filename, *params):
'''
Create the instances of the gui and data:
in:
- fc = center frequency at bandpass
- dec = usrp decimation factor
- gain = RF gain
- eth = name of the ethernet
- sync = True if u wanna sync with external clock
'''
# desired signal sample rate
outSampRate = float(100e6)/dec
if len(params) > 0:
self.rx = RxUSRP(fc, params[0], dec, gain, eth, outSampRate, sync)
self.data = RXData(self, outSampRate, 1, 1, filename)
self.tb = gr.top_block()
# if recording_time <= 0:
# recording_time = 1
#
# self.control = RXControlApp(self, recording_time) if(recording_time > 0) else None
def launch(self):
'''
calls startup
'''
print "i: launch"
self.__startup__()
print "i: end launch"
def __startup__(self):
'''
Responsible for starting the application; for creating and showing
the initial GUI.
'''
print "i: startup"
# from the antenna to the file
self.tb.connect((self.rx, 0), (self.data, 0))
# if self.control <> None:
# self.control.start()
# running
self.tb.start()
print "i: end startup"
def stopApp(self):
"""
Stop app
"""
try:
self.tb.stop()
except Exception, e:
print("e: ", e)
return False
return True
| {
"content_hash": "35462653dc13c369b096f71224c1fc05",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 91,
"avg_line_length": 25.651162790697676,
"alnum_prop": 0.529918404351768,
"repo_name": "spino327/sdr_testbed",
"id": "c1da774fad53ff7772bd059d47a239feeda0867f",
"size": "2206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DistributedTestbed/receiver/RXApp.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "79507"
}
],
"symlink_target": ""
} |
package clouduseraccounts // import "google.golang.org/api/clouduseraccounts/vm_beta"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
context "golang.org/x/net/context"
ctxhttp "golang.org/x/net/context/ctxhttp"
gensupport "google.golang.org/api/gensupport"
googleapi "google.golang.org/api/googleapi"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = ctxhttp.Do
const apiId = "clouduseraccounts:vm_beta"
const apiName = "clouduseraccounts"
const apiVersion = "vm_beta"
const basePath = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/"
// OAuth2 scopes used by this API.
const (
// View and manage your data across Google Cloud Platform services
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// View your data across Google Cloud Platform services
CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only"
// Manage your Google Cloud User Accounts
CloudUseraccountsScope = "https://www.googleapis.com/auth/cloud.useraccounts"
// View your Google Cloud User Accounts
CloudUseraccountsReadonlyScope = "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.GlobalAccountsOperations = NewGlobalAccountsOperationsService(s)
s.Groups = NewGroupsService(s)
s.Linux = NewLinuxService(s)
s.Users = NewUsersService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
GlobalAccountsOperations *GlobalAccountsOperationsService
Groups *GroupsService
Linux *LinuxService
Users *UsersService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewGlobalAccountsOperationsService(s *Service) *GlobalAccountsOperationsService {
rs := &GlobalAccountsOperationsService{s: s}
return rs
}
type GlobalAccountsOperationsService struct {
s *Service
}
func NewGroupsService(s *Service) *GroupsService {
rs := &GroupsService{s: s}
return rs
}
type GroupsService struct {
s *Service
}
func NewLinuxService(s *Service) *LinuxService {
rs := &LinuxService{s: s}
return rs
}
type LinuxService struct {
s *Service
}
func NewUsersService(s *Service) *UsersService {
rs := &UsersService{s: s}
return rs
}
type UsersService struct {
s *Service
}
// AuthorizedKeysView: A list of authorized public keys for a user
// account.
type AuthorizedKeysView struct {
// Keys: [Output Only] The list of authorized public keys in SSH format.
Keys []string `json:"keys,omitempty"`
// Sudoer: [Output Only] Whether the user has the ability to elevate on
// the instance that requested the authorized keys.
Sudoer bool `json:"sudoer,omitempty"`
// ForceSendFields is a list of field names (e.g. "Keys") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *AuthorizedKeysView) MarshalJSON() ([]byte, error) {
type noMethod AuthorizedKeysView
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// Group: A Group resource.
type Group struct {
// CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text
// format.
CreationTimestamp string `json:"creationTimestamp,omitempty"`
// Description: An optional textual description of the resource;
// provided by the client when the resource is created.
Description string `json:"description,omitempty"`
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id uint64 `json:"id,omitempty,string"`
// Kind: [Output Only] Type of the resource. Always
// clouduseraccounts#group for groups.
Kind string `json:"kind,omitempty"`
// Members: [Output Only] A list of URLs to User resources who belong to
// the group. Users may only be members of groups in the same project.
Members []string `json:"members,omitempty"`
// Name: Name of the resource; provided by the client when the resource
// is created.
Name string `json:"name,omitempty"`
// SelfLink: [Output Only] Server defined URL for the resource.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CreationTimestamp")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Group) MarshalJSON() ([]byte, error) {
type noMethod Group
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type GroupList struct {
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id string `json:"id,omitempty"`
// Items: [Output Only] A list of Group resources.
Items []*Group `json:"items,omitempty"`
// Kind: [Output Only] Type of resource. Always
// clouduseraccounts#groupList for lists of groups.
Kind string `json:"kind,omitempty"`
// NextPageToken: [Output Only] A token used to continue a truncated
// list request.
NextPageToken string `json:"nextPageToken,omitempty"`
// SelfLink: [Output Only] Server defined URL for this resource.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *GroupList) MarshalJSON() ([]byte, error) {
type noMethod GroupList
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type GroupsAddMemberRequest struct {
// Users: Fully-qualified URLs of the User resources to add.
Users []string `json:"users,omitempty"`
// ForceSendFields is a list of field names (e.g. "Users") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *GroupsAddMemberRequest) MarshalJSON() ([]byte, error) {
type noMethod GroupsAddMemberRequest
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type GroupsRemoveMemberRequest struct {
// Users: Fully-qualified URLs of the User resources to remove.
Users []string `json:"users,omitempty"`
// ForceSendFields is a list of field names (e.g. "Users") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *GroupsRemoveMemberRequest) MarshalJSON() ([]byte, error) {
type noMethod GroupsRemoveMemberRequest
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// LinuxAccountViews: A list of all Linux accounts for this project.
// This API is only used by Compute Engine virtual machines to get
// information about user accounts for a project or instance. Linux
// resources are read-only views into users and groups managed by the
// Compute Engine Accounts API.
type LinuxAccountViews struct {
// GroupViews: [Output Only] A list of all groups within a project.
GroupViews []*LinuxGroupView `json:"groupViews,omitempty"`
// Kind: [Output Only] Type of the resource. Always
// clouduseraccounts#linuxAccountViews for Linux resources.
Kind string `json:"kind,omitempty"`
// UserViews: [Output Only] A list of all users within a project.
UserViews []*LinuxUserView `json:"userViews,omitempty"`
// ForceSendFields is a list of field names (e.g. "GroupViews") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *LinuxAccountViews) MarshalJSON() ([]byte, error) {
type noMethod LinuxAccountViews
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type LinuxGetAuthorizedKeysViewResponse struct {
// Resource: [Output Only] A list of authorized public keys for a user.
Resource *AuthorizedKeysView `json:"resource,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Resource") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *LinuxGetAuthorizedKeysViewResponse) MarshalJSON() ([]byte, error) {
type noMethod LinuxGetAuthorizedKeysViewResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type LinuxGetLinuxAccountViewsResponse struct {
// Resource: [Output Only] A list of authorized user accounts and
// groups.
Resource *LinuxAccountViews `json:"resource,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Resource") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *LinuxGetLinuxAccountViewsResponse) MarshalJSON() ([]byte, error) {
type noMethod LinuxGetLinuxAccountViewsResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// LinuxGroupView: A detailed view of a Linux group.
type LinuxGroupView struct {
// Gid: [Output Only] The Group ID.
Gid int64 `json:"gid,omitempty"`
// GroupName: [Output Only] Group name.
GroupName string `json:"groupName,omitempty"`
// Members: [Output Only] List of user accounts that belong to the
// group.
Members []string `json:"members,omitempty"`
// ForceSendFields is a list of field names (e.g. "Gid") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *LinuxGroupView) MarshalJSON() ([]byte, error) {
type noMethod LinuxGroupView
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// LinuxUserView: A detailed view of a Linux user account.
type LinuxUserView struct {
// Gecos: [Output Only] The GECOS (user information) entry for this
// account.
Gecos string `json:"gecos,omitempty"`
// Gid: [Output Only] User's default group ID.
Gid int64 `json:"gid,omitempty"`
// HomeDirectory: [Output Only] The path to the home directory for this
// account.
HomeDirectory string `json:"homeDirectory,omitempty"`
// Shell: [Output Only] The path to the login shell for this account.
Shell string `json:"shell,omitempty"`
// Uid: [Output Only] User ID.
Uid int64 `json:"uid,omitempty"`
// Username: [Output Only] The username of the account.
Username string `json:"username,omitempty"`
// ForceSendFields is a list of field names (e.g. "Gecos") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *LinuxUserView) MarshalJSON() ([]byte, error) {
type noMethod LinuxUserView
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// Operation: An Operation resource, used to manage asynchronous API
// requests.
type Operation struct {
// ClientOperationId: [Output Only] An optional identifier specified by
// the client when the mutation was initiated. Must be unique for all
// Operation resources in the project.
ClientOperationId string `json:"clientOperationId,omitempty"`
// CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text
// format.
CreationTimestamp string `json:"creationTimestamp,omitempty"`
// EndTime: [Output Only] The time that this operation was completed.
// This is in RFC3339 text format.
EndTime string `json:"endTime,omitempty"`
// Error: [Output Only] If errors are generated during processing of the
// operation, this field will be populated.
Error *OperationError `json:"error,omitempty"`
// HttpErrorMessage: [Output Only] If the operation fails, this field
// contains the HTTP error message that was returned, such as NOT FOUND.
HttpErrorMessage string `json:"httpErrorMessage,omitempty"`
// HttpErrorStatusCode: [Output Only] If the operation fails, this field
// contains the HTTP error message that was returned, such as 404.
HttpErrorStatusCode int64 `json:"httpErrorStatusCode,omitempty"`
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id uint64 `json:"id,omitempty,string"`
// InsertTime: [Output Only] The time that this operation was requested.
// This is in RFC3339 text format.
InsertTime string `json:"insertTime,omitempty"`
// Kind: [Output Only] Type of the resource. Always compute#operation
// for Operation resources.
Kind string `json:"kind,omitempty"`
// Name: [Output Only] Name of the resource.
Name string `json:"name,omitempty"`
// OperationType: [Output Only] Type of the operation, such as insert,
// compute.instanceGroups.update, or compute.instanceGroups.delete.
OperationType string `json:"operationType,omitempty"`
// Progress: [Output Only] An optional progress indicator that ranges
// from 0 to 100. There is no requirement that this be linear or support
// any granularity of operations. This should not be used to guess at
// when the operation will be complete. This number should monotonically
// increase as the operation progresses.
Progress int64 `json:"progress,omitempty"`
// Region: [Output Only] URL of the region where the operation resides.
// Only applicable for regional resources.
Region string `json:"region,omitempty"`
// SelfLink: [Output Only] Server-defined URL for the resource.
SelfLink string `json:"selfLink,omitempty"`
// StartTime: [Output Only] The time that this operation was started by
// the server. This is in RFC3339 text format.
StartTime string `json:"startTime,omitempty"`
// Status: [Output Only] Status of the operation. Can be one of the
// following: PENDING, RUNNING, or DONE.
//
// Possible values:
// "DONE"
// "PENDING"
// "RUNNING"
Status string `json:"status,omitempty"`
// StatusMessage: [Output Only] An optional textual description of the
// current status of the operation.
StatusMessage string `json:"statusMessage,omitempty"`
// TargetId: [Output Only] Unique target ID which identifies a
// particular incarnation of the target.
TargetId uint64 `json:"targetId,omitempty,string"`
// TargetLink: [Output Only] URL of the resource the operation is
// mutating.
TargetLink string `json:"targetLink,omitempty"`
// User: [Output Only] User who requested the operation, for example:
// user@example.com.
User string `json:"user,omitempty"`
// Warnings: [Output Only] If warning messages are generated during
// processing of the operation, this field will be populated.
Warnings []*OperationWarnings `json:"warnings,omitempty"`
// Zone: [Output Only] URL of the zone where the operation resides.
Zone string `json:"zone,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ClientOperationId")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Operation) MarshalJSON() ([]byte, error) {
type noMethod Operation
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// OperationError: [Output Only] If errors are generated during
// processing of the operation, this field will be populated.
type OperationError struct {
// Errors: [Output Only] The array of errors encountered while
// processing this operation.
Errors []*OperationErrorErrors `json:"errors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Errors") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *OperationError) MarshalJSON() ([]byte, error) {
type noMethod OperationError
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type OperationErrorErrors struct {
// Code: [Output Only] The error type identifier for this error.
Code string `json:"code,omitempty"`
// Location: [Output Only] Indicates the field in the request which
// caused the error. This property is optional.
Location string `json:"location,omitempty"`
// Message: [Output Only] An optional, human-readable error message.
Message string `json:"message,omitempty"`
// ForceSendFields is a list of field names (e.g. "Code") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *OperationErrorErrors) MarshalJSON() ([]byte, error) {
type noMethod OperationErrorErrors
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type OperationWarnings struct {
// Code: [Output Only] The warning type identifier for this warning.
//
// Possible values:
// "DEPRECATED_RESOURCE_USED"
// "DISK_SIZE_LARGER_THAN_IMAGE_SIZE"
// "INJECTED_KERNELS_DEPRECATED"
// "NEXT_HOP_ADDRESS_NOT_ASSIGNED"
// "NEXT_HOP_CANNOT_IP_FORWARD"
// "NEXT_HOP_INSTANCE_NOT_FOUND"
// "NEXT_HOP_INSTANCE_NOT_ON_NETWORK"
// "NEXT_HOP_NOT_RUNNING"
// "NOT_CRITICAL_ERROR"
// "NO_RESULTS_ON_PAGE"
// "REQUIRED_TOS_AGREEMENT"
// "RESOURCE_NOT_DELETED"
// "SINGLE_INSTANCE_PROPERTY_TEMPLATE"
// "UNREACHABLE"
Code string `json:"code,omitempty"`
// Data: [Output Only] Metadata for this warning in key: value format.
Data []*OperationWarningsData `json:"data,omitempty"`
// Message: [Output Only] Optional human-readable details for this
// warning.
Message string `json:"message,omitempty"`
// ForceSendFields is a list of field names (e.g. "Code") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *OperationWarnings) MarshalJSON() ([]byte, error) {
type noMethod OperationWarnings
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type OperationWarningsData struct {
// Key: [Output Only] A key for the warning data.
Key string `json:"key,omitempty"`
// Value: [Output Only] A warning data value corresponding to the key.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *OperationWarningsData) MarshalJSON() ([]byte, error) {
type noMethod OperationWarningsData
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// OperationList: Contains a list of Operation resources.
type OperationList struct {
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id string `json:"id,omitempty"`
// Items: [Output Only] The Operation resources.
Items []*Operation `json:"items,omitempty"`
// Kind: [Output Only] Type of resource. Always compute#operations for
// Operations resource.
Kind string `json:"kind,omitempty"`
// NextPageToken: [Output Only] A token used to continue a truncate.
NextPageToken string `json:"nextPageToken,omitempty"`
// SelfLink: [Output Only] Server-defined URL for this resource.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *OperationList) MarshalJSON() ([]byte, error) {
type noMethod OperationList
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// PublicKey: A public key for authenticating to guests.
type PublicKey struct {
// CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text
// format.
CreationTimestamp string `json:"creationTimestamp,omitempty"`
// Description: An optional textual description of the resource;
// provided by the client when the resource is created.
Description string `json:"description,omitempty"`
// ExpirationTimestamp: Optional expiration timestamp. If provided, the
// timestamp must be in RFC3339 text format. If not provided, the public
// key never expires.
ExpirationTimestamp string `json:"expirationTimestamp,omitempty"`
// Fingerprint: [Output Only] The fingerprint of the key is defined by
// RFC4716 to be the MD5 digest of the public key.
Fingerprint string `json:"fingerprint,omitempty"`
// Key: Public key text in SSH format, defined by RFC4253 section 6.6.
Key string `json:"key,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreationTimestamp")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *PublicKey) MarshalJSON() ([]byte, error) {
type noMethod PublicKey
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// User: A User resource.
type User struct {
// CreationTimestamp: [Output Only] Creation timestamp in RFC3339 text
// format.
CreationTimestamp string `json:"creationTimestamp,omitempty"`
// Description: An optional textual description of the resource;
// provided by the client when the resource is created.
Description string `json:"description,omitempty"`
// Groups: [Output Only] A list of URLs to Group resources who contain
// the user. Users are only members of groups in the same project.
Groups []string `json:"groups,omitempty"`
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id uint64 `json:"id,omitempty,string"`
// Kind: [Output Only] Type of the resource. Always
// clouduseraccounts#user for users.
Kind string `json:"kind,omitempty"`
// Name: Name of the resource; provided by the client when the resource
// is created.
Name string `json:"name,omitempty"`
// Owner: Email address of account's owner. This account will be
// validated to make sure it exists. The email can belong to any domain,
// but it must be tied to a Google account.
Owner string `json:"owner,omitempty"`
// PublicKeys: [Output Only] Public keys that this user may use to
// login.
PublicKeys []*PublicKey `json:"publicKeys,omitempty"`
// SelfLink: [Output Only] Server defined URL for the resource.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CreationTimestamp")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *User) MarshalJSON() ([]byte, error) {
type noMethod User
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
type UserList struct {
// Id: [Output Only] Unique identifier for the resource; defined by the
// server.
Id string `json:"id,omitempty"`
// Items: [Output Only] A list of User resources.
Items []*User `json:"items,omitempty"`
// Kind: [Output Only] Type of resource. Always
// clouduseraccounts#userList for lists of users.
Kind string `json:"kind,omitempty"`
// NextPageToken: [Output Only] A token used to continue a truncated
// list request.
NextPageToken string `json:"nextPageToken,omitempty"`
// SelfLink: [Output Only] Server defined URL for this resource.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *UserList) MarshalJSON() ([]byte, error) {
type noMethod UserList
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields)
}
// method id "clouduseraccounts.globalAccountsOperations.delete":
type GlobalAccountsOperationsDeleteCall struct {
s *Service
project string
operation string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// Delete: Deletes the specified operation resource.
func (r *GlobalAccountsOperationsService) Delete(project string, operation string) *GlobalAccountsOperationsDeleteCall {
c := &GlobalAccountsOperationsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.operation = operation
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GlobalAccountsOperationsDeleteCall) Fields(s ...googleapi.Field) *GlobalAccountsOperationsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GlobalAccountsOperationsDeleteCall) Context(ctx context.Context) *GlobalAccountsOperationsDeleteCall {
c.ctx_ = ctx
return c
}
func (c *GlobalAccountsOperationsDeleteCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/operations/{operation}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"operation": c.operation,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.globalAccountsOperations.delete" call.
func (c *GlobalAccountsOperationsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes the specified operation resource.",
// "httpMethod": "DELETE",
// "id": "clouduseraccounts.globalAccountsOperations.delete",
// "parameterOrder": [
// "project",
// "operation"
// ],
// "parameters": {
// "operation": {
// "description": "Name of the Operations resource to delete.",
// "location": "path",
// "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/operations/{operation}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.globalAccountsOperations.get":
type GlobalAccountsOperationsGetCall struct {
s *Service
project string
operation string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// Get: Retrieves the specified operation resource.
func (r *GlobalAccountsOperationsService) Get(project string, operation string) *GlobalAccountsOperationsGetCall {
c := &GlobalAccountsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.operation = operation
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GlobalAccountsOperationsGetCall) Fields(s ...googleapi.Field) *GlobalAccountsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *GlobalAccountsOperationsGetCall) IfNoneMatch(entityTag string) *GlobalAccountsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GlobalAccountsOperationsGetCall) Context(ctx context.Context) *GlobalAccountsOperationsGetCall {
c.ctx_ = ctx
return c
}
func (c *GlobalAccountsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/operations/{operation}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"operation": c.operation,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.globalAccountsOperations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GlobalAccountsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the specified operation resource.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.globalAccountsOperations.get",
// "parameterOrder": [
// "project",
// "operation"
// ],
// "parameters": {
// "operation": {
// "description": "Name of the Operations resource to return.",
// "location": "path",
// "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/operations/{operation}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.globalAccountsOperations.list":
type GlobalAccountsOperationsListCall struct {
s *Service
project string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// List: Retrieves the list of operation resources contained within the
// specified project.
func (r *GlobalAccountsOperationsService) List(project string) *GlobalAccountsOperationsListCall {
c := &GlobalAccountsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
return c
}
// Filter sets the optional parameter "filter": Sets a filter expression
// for filtering listed resources, in the form filter={expression}. Your
// {expression} must be in the format: FIELD_NAME COMPARISON_STRING
// LITERAL_STRING.
//
// The FIELD_NAME is the name of the field you want to compare. Only
// atomic field types are supported (string, number, boolean). The
// COMPARISON_STRING must be either eq (equals) or ne (not equals). The
// LITERAL_STRING is the string value to filter to. The literal value
// must be valid for the type of field (string, number, boolean). For
// string fields, the literal value is interpreted as a regular
// expression using RE2 syntax. The literal value must match the entire
// field.
//
// For example, filter=name ne example-instance.
func (c *GlobalAccountsOperationsListCall) Filter(filter string) *GlobalAccountsOperationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum count of
// results to be returned.
func (c *GlobalAccountsOperationsListCall) MaxResults(maxResults int64) *GlobalAccountsOperationsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OrderBy sets the optional parameter "orderBy": Sorts list results by
// a certain order. By default, results are returned in alphanumerical
// order based on the resource name.
//
// You can also sort results in descending order based on the creation
// timestamp using orderBy="creationTimestamp desc". This sorts results
// based on the creationTimestamp field in reverse chronological order
// (newest result first). Use this to sort resources like operations so
// that the newest operation is returned first.
//
// Currently, only sorting by name or creationTimestamp desc is
// supported.
func (c *GlobalAccountsOperationsListCall) OrderBy(orderBy string) *GlobalAccountsOperationsListCall {
c.urlParams_.Set("orderBy", orderBy)
return c
}
// PageToken sets the optional parameter "pageToken": Specifies a page
// token to use. Use this parameter if you want to list the next page of
// results. Set pageToken to the nextPageToken returned by a previous
// list request.
func (c *GlobalAccountsOperationsListCall) PageToken(pageToken string) *GlobalAccountsOperationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GlobalAccountsOperationsListCall) Fields(s ...googleapi.Field) *GlobalAccountsOperationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *GlobalAccountsOperationsListCall) IfNoneMatch(entityTag string) *GlobalAccountsOperationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GlobalAccountsOperationsListCall) Context(ctx context.Context) *GlobalAccountsOperationsListCall {
c.ctx_ = ctx
return c
}
func (c *GlobalAccountsOperationsListCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/operations")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.globalAccountsOperations.list" call.
// Exactly one of *OperationList or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *OperationList.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *GlobalAccountsOperationsListCall) Do(opts ...googleapi.CallOption) (*OperationList, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &OperationList{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the list of operation resources contained within the specified project.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.globalAccountsOperations.list",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "filter": {
// "description": "Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING.\n\nThe FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.\n\nFor example, filter=name ne example-instance.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "500",
// "description": "Maximum count of results to be returned.",
// "format": "uint32",
// "location": "query",
// "maximum": "500",
// "minimum": "0",
// "type": "integer"
// },
// "orderBy": {
// "description": "Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.\n\nYou can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.\n\nCurrently, only sorting by name or creationTimestamp desc is supported.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/operations",
// "response": {
// "$ref": "OperationList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.groups.addMember":
type GroupsAddMemberCall struct {
s *Service
project string
groupName string
groupsaddmemberrequest *GroupsAddMemberRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// AddMember: Adds users to the specified group.
func (r *GroupsService) AddMember(project string, groupName string, groupsaddmemberrequest *GroupsAddMemberRequest) *GroupsAddMemberCall {
c := &GroupsAddMemberCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.groupName = groupName
c.groupsaddmemberrequest = groupsaddmemberrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsAddMemberCall) Fields(s ...googleapi.Field) *GroupsAddMemberCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsAddMemberCall) Context(ctx context.Context) *GroupsAddMemberCall {
c.ctx_ = ctx
return c
}
func (c *GroupsAddMemberCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.groupsaddmemberrequest)
if err != nil {
return nil, err
}
ctype := "application/json"
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups/{groupName}/addMember")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"groupName": c.groupName,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.addMember" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GroupsAddMemberCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds users to the specified group.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.groups.addMember",
// "parameterOrder": [
// "project",
// "groupName"
// ],
// "parameters": {
// "groupName": {
// "description": "Name of the group for this request.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups/{groupName}/addMember",
// "request": {
// "$ref": "GroupsAddMemberRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.groups.delete":
type GroupsDeleteCall struct {
s *Service
project string
groupName string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// Delete: Deletes the specified Group resource.
func (r *GroupsService) Delete(project string, groupName string) *GroupsDeleteCall {
c := &GroupsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.groupName = groupName
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsDeleteCall) Fields(s ...googleapi.Field) *GroupsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsDeleteCall) Context(ctx context.Context) *GroupsDeleteCall {
c.ctx_ = ctx
return c
}
func (c *GroupsDeleteCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups/{groupName}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"groupName": c.groupName,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GroupsDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified Group resource.",
// "httpMethod": "DELETE",
// "id": "clouduseraccounts.groups.delete",
// "parameterOrder": [
// "project",
// "groupName"
// ],
// "parameters": {
// "groupName": {
// "description": "Name of the Group resource to delete.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups/{groupName}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.groups.get":
type GroupsGetCall struct {
s *Service
project string
groupName string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// Get: Returns the specified Group resource.
func (r *GroupsService) Get(project string, groupName string) *GroupsGetCall {
c := &GroupsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.groupName = groupName
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsGetCall) Fields(s ...googleapi.Field) *GroupsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *GroupsGetCall) IfNoneMatch(entityTag string) *GroupsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsGetCall) Context(ctx context.Context) *GroupsGetCall {
c.ctx_ = ctx
return c
}
func (c *GroupsGetCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups/{groupName}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"groupName": c.groupName,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.get" call.
// Exactly one of *Group or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Group.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *GroupsGetCall) Do(opts ...googleapi.CallOption) (*Group, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Group{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the specified Group resource.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.groups.get",
// "parameterOrder": [
// "project",
// "groupName"
// ],
// "parameters": {
// "groupName": {
// "description": "Name of the Group resource to return.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups/{groupName}",
// "response": {
// "$ref": "Group"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.groups.insert":
type GroupsInsertCall struct {
s *Service
project string
group *Group
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// Insert: Creates a Group resource in the specified project using the
// data included in the request.
func (r *GroupsService) Insert(project string, group *Group) *GroupsInsertCall {
c := &GroupsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.group = group
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsInsertCall) Fields(s ...googleapi.Field) *GroupsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsInsertCall) Context(ctx context.Context) *GroupsInsertCall {
c.ctx_ = ctx
return c
}
func (c *GroupsInsertCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.group)
if err != nil {
return nil, err
}
ctype := "application/json"
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.insert" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GroupsInsertCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a Group resource in the specified project using the data included in the request.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.groups.insert",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups",
// "request": {
// "$ref": "Group"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.groups.list":
type GroupsListCall struct {
s *Service
project string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// List: Retrieves the list of groups contained within the specified
// project.
func (r *GroupsService) List(project string) *GroupsListCall {
c := &GroupsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
return c
}
// Filter sets the optional parameter "filter": Sets a filter expression
// for filtering listed resources, in the form filter={expression}. Your
// {expression} must be in the format: FIELD_NAME COMPARISON_STRING
// LITERAL_STRING.
//
// The FIELD_NAME is the name of the field you want to compare. Only
// atomic field types are supported (string, number, boolean). The
// COMPARISON_STRING must be either eq (equals) or ne (not equals). The
// LITERAL_STRING is the string value to filter to. The literal value
// must be valid for the type of field (string, number, boolean). For
// string fields, the literal value is interpreted as a regular
// expression using RE2 syntax. The literal value must match the entire
// field.
//
// For example, filter=name ne example-instance.
func (c *GroupsListCall) Filter(filter string) *GroupsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum count of
// results to be returned.
func (c *GroupsListCall) MaxResults(maxResults int64) *GroupsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OrderBy sets the optional parameter "orderBy": Sorts list results by
// a certain order. By default, results are returned in alphanumerical
// order based on the resource name.
//
// You can also sort results in descending order based on the creation
// timestamp using orderBy="creationTimestamp desc". This sorts results
// based on the creationTimestamp field in reverse chronological order
// (newest result first). Use this to sort resources like operations so
// that the newest operation is returned first.
//
// Currently, only sorting by name or creationTimestamp desc is
// supported.
func (c *GroupsListCall) OrderBy(orderBy string) *GroupsListCall {
c.urlParams_.Set("orderBy", orderBy)
return c
}
// PageToken sets the optional parameter "pageToken": Specifies a page
// token to use. Use this parameter if you want to list the next page of
// results. Set pageToken to the nextPageToken returned by a previous
// list request.
func (c *GroupsListCall) PageToken(pageToken string) *GroupsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsListCall) Fields(s ...googleapi.Field) *GroupsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *GroupsListCall) IfNoneMatch(entityTag string) *GroupsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsListCall) Context(ctx context.Context) *GroupsListCall {
c.ctx_ = ctx
return c
}
func (c *GroupsListCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.list" call.
// Exactly one of *GroupList or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *GroupList.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GroupsListCall) Do(opts ...googleapi.CallOption) (*GroupList, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GroupList{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the list of groups contained within the specified project.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.groups.list",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "filter": {
// "description": "Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING.\n\nThe FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.\n\nFor example, filter=name ne example-instance.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "500",
// "description": "Maximum count of results to be returned.",
// "format": "uint32",
// "location": "query",
// "maximum": "500",
// "minimum": "0",
// "type": "integer"
// },
// "orderBy": {
// "description": "Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.\n\nYou can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.\n\nCurrently, only sorting by name or creationTimestamp desc is supported.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups",
// "response": {
// "$ref": "GroupList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.groups.removeMember":
type GroupsRemoveMemberCall struct {
s *Service
project string
groupName string
groupsremovememberrequest *GroupsRemoveMemberRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// RemoveMember: Removes users from the specified group.
func (r *GroupsService) RemoveMember(project string, groupName string, groupsremovememberrequest *GroupsRemoveMemberRequest) *GroupsRemoveMemberCall {
c := &GroupsRemoveMemberCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.groupName = groupName
c.groupsremovememberrequest = groupsremovememberrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *GroupsRemoveMemberCall) Fields(s ...googleapi.Field) *GroupsRemoveMemberCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *GroupsRemoveMemberCall) Context(ctx context.Context) *GroupsRemoveMemberCall {
c.ctx_ = ctx
return c
}
func (c *GroupsRemoveMemberCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.groupsremovememberrequest)
if err != nil {
return nil, err
}
ctype := "application/json"
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/groups/{groupName}/removeMember")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"groupName": c.groupName,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.groups.removeMember" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *GroupsRemoveMemberCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Removes users from the specified group.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.groups.removeMember",
// "parameterOrder": [
// "project",
// "groupName"
// ],
// "parameters": {
// "groupName": {
// "description": "Name of the group for this request.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/groups/{groupName}/removeMember",
// "request": {
// "$ref": "GroupsRemoveMemberRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.linux.getAuthorizedKeysView":
type LinuxGetAuthorizedKeysViewCall struct {
s *Service
project string
zone string
user string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// GetAuthorizedKeysView: Returns a list of authorized public keys for a
// specific user account.
func (r *LinuxService) GetAuthorizedKeysView(project string, zone string, user string, instance string) *LinuxGetAuthorizedKeysViewCall {
c := &LinuxGetAuthorizedKeysViewCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.zone = zone
c.user = user
c.urlParams_.Set("instance", instance)
return c
}
// Login sets the optional parameter "login": Whether the view was
// requested as part of a user-initiated login.
func (c *LinuxGetAuthorizedKeysViewCall) Login(login bool) *LinuxGetAuthorizedKeysViewCall {
c.urlParams_.Set("login", fmt.Sprint(login))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LinuxGetAuthorizedKeysViewCall) Fields(s ...googleapi.Field) *LinuxGetAuthorizedKeysViewCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LinuxGetAuthorizedKeysViewCall) Context(ctx context.Context) *LinuxGetAuthorizedKeysViewCall {
c.ctx_ = ctx
return c
}
func (c *LinuxGetAuthorizedKeysViewCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/zones/{zone}/authorizedKeysView/{user}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"zone": c.zone,
"user": c.user,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.linux.getAuthorizedKeysView" call.
// Exactly one of *LinuxGetAuthorizedKeysViewResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *LinuxGetAuthorizedKeysViewResponse.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *LinuxGetAuthorizedKeysViewCall) Do(opts ...googleapi.CallOption) (*LinuxGetAuthorizedKeysViewResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LinuxGetAuthorizedKeysViewResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns a list of authorized public keys for a specific user account.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.linux.getAuthorizedKeysView",
// "parameterOrder": [
// "project",
// "zone",
// "user",
// "instance"
// ],
// "parameters": {
// "instance": {
// "description": "The fully-qualified URL of the virtual machine requesting the view.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "login": {
// "description": "Whether the view was requested as part of a user-initiated login.",
// "location": "query",
// "type": "boolean"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "user": {
// "description": "The user account for which you want to get a list of authorized public keys.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// },
// "zone": {
// "description": "Name of the zone for this request.",
// "location": "path",
// "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/zones/{zone}/authorizedKeysView/{user}",
// "response": {
// "$ref": "LinuxGetAuthorizedKeysViewResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.linux.getLinuxAccountViews":
type LinuxGetLinuxAccountViewsCall struct {
s *Service
project string
zone string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// GetLinuxAccountViews: Retrieves a list of user accounts for an
// instance within a specific project.
func (r *LinuxService) GetLinuxAccountViews(project string, zone string, instance string) *LinuxGetLinuxAccountViewsCall {
c := &LinuxGetLinuxAccountViewsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.zone = zone
c.urlParams_.Set("instance", instance)
return c
}
// Filter sets the optional parameter "filter": Sets a filter expression
// for filtering listed resources, in the form filter={expression}. Your
// {expression} must be in the format: FIELD_NAME COMPARISON_STRING
// LITERAL_STRING.
//
// The FIELD_NAME is the name of the field you want to compare. Only
// atomic field types are supported (string, number, boolean). The
// COMPARISON_STRING must be either eq (equals) or ne (not equals). The
// LITERAL_STRING is the string value to filter to. The literal value
// must be valid for the type of field (string, number, boolean). For
// string fields, the literal value is interpreted as a regular
// expression using RE2 syntax. The literal value must match the entire
// field.
//
// For example, filter=name ne example-instance.
func (c *LinuxGetLinuxAccountViewsCall) Filter(filter string) *LinuxGetLinuxAccountViewsCall {
c.urlParams_.Set("filter", filter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum count of
// results to be returned.
func (c *LinuxGetLinuxAccountViewsCall) MaxResults(maxResults int64) *LinuxGetLinuxAccountViewsCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OrderBy sets the optional parameter "orderBy": Sorts list results by
// a certain order. By default, results are returned in alphanumerical
// order based on the resource name.
//
// You can also sort results in descending order based on the creation
// timestamp using orderBy="creationTimestamp desc". This sorts results
// based on the creationTimestamp field in reverse chronological order
// (newest result first). Use this to sort resources like operations so
// that the newest operation is returned first.
//
// Currently, only sorting by name or creationTimestamp desc is
// supported.
func (c *LinuxGetLinuxAccountViewsCall) OrderBy(orderBy string) *LinuxGetLinuxAccountViewsCall {
c.urlParams_.Set("orderBy", orderBy)
return c
}
// PageToken sets the optional parameter "pageToken": Specifies a page
// token to use. Use this parameter if you want to list the next page of
// results. Set pageToken to the nextPageToken returned by a previous
// list request.
func (c *LinuxGetLinuxAccountViewsCall) PageToken(pageToken string) *LinuxGetLinuxAccountViewsCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LinuxGetLinuxAccountViewsCall) Fields(s ...googleapi.Field) *LinuxGetLinuxAccountViewsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LinuxGetLinuxAccountViewsCall) Context(ctx context.Context) *LinuxGetLinuxAccountViewsCall {
c.ctx_ = ctx
return c
}
func (c *LinuxGetLinuxAccountViewsCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/zones/{zone}/linuxAccountViews")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"zone": c.zone,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.linux.getLinuxAccountViews" call.
// Exactly one of *LinuxGetLinuxAccountViewsResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *LinuxGetLinuxAccountViewsResponse.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *LinuxGetLinuxAccountViewsCall) Do(opts ...googleapi.CallOption) (*LinuxGetLinuxAccountViewsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &LinuxGetLinuxAccountViewsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of user accounts for an instance within a specific project.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.linux.getLinuxAccountViews",
// "parameterOrder": [
// "project",
// "zone",
// "instance"
// ],
// "parameters": {
// "filter": {
// "description": "Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING.\n\nThe FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.\n\nFor example, filter=name ne example-instance.",
// "location": "query",
// "type": "string"
// },
// "instance": {
// "description": "The fully-qualified URL of the virtual machine requesting the views.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "maxResults": {
// "default": "500",
// "description": "Maximum count of results to be returned.",
// "format": "uint32",
// "location": "query",
// "maximum": "500",
// "minimum": "0",
// "type": "integer"
// },
// "orderBy": {
// "description": "Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.\n\nYou can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.\n\nCurrently, only sorting by name or creationTimestamp desc is supported.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "zone": {
// "description": "Name of the zone for this request.",
// "location": "path",
// "pattern": "[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/zones/{zone}/linuxAccountViews",
// "response": {
// "$ref": "LinuxGetLinuxAccountViewsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.users.addPublicKey":
type UsersAddPublicKeyCall struct {
s *Service
project string
user string
publickey *PublicKey
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// AddPublicKey: Adds a public key to the specified User resource with
// the data included in the request.
func (r *UsersService) AddPublicKey(project string, user string, publickey *PublicKey) *UsersAddPublicKeyCall {
c := &UsersAddPublicKeyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.user = user
c.publickey = publickey
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersAddPublicKeyCall) Fields(s ...googleapi.Field) *UsersAddPublicKeyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersAddPublicKeyCall) Context(ctx context.Context) *UsersAddPublicKeyCall {
c.ctx_ = ctx
return c
}
func (c *UsersAddPublicKeyCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.publickey)
if err != nil {
return nil, err
}
ctype := "application/json"
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users/{user}/addPublicKey")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"user": c.user,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.addPublicKey" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *UsersAddPublicKeyCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a public key to the specified User resource with the data included in the request.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.users.addPublicKey",
// "parameterOrder": [
// "project",
// "user"
// ],
// "parameters": {
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "user": {
// "description": "Name of the user for this request.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users/{user}/addPublicKey",
// "request": {
// "$ref": "PublicKey"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.users.delete":
type UsersDeleteCall struct {
s *Service
project string
user string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// Delete: Deletes the specified User resource.
func (r *UsersService) Delete(project string, user string) *UsersDeleteCall {
c := &UsersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.user = user
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersDeleteCall) Fields(s ...googleapi.Field) *UsersDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersDeleteCall) Context(ctx context.Context) *UsersDeleteCall {
c.ctx_ = ctx
return c
}
func (c *UsersDeleteCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users/{user}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"user": c.user,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *UsersDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified User resource.",
// "httpMethod": "DELETE",
// "id": "clouduseraccounts.users.delete",
// "parameterOrder": [
// "project",
// "user"
// ],
// "parameters": {
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "user": {
// "description": "Name of the user resource to delete.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users/{user}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.users.get":
type UsersGetCall struct {
s *Service
project string
user string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// Get: Returns the specified User resource.
func (r *UsersService) Get(project string, user string) *UsersGetCall {
c := &UsersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.user = user
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersGetCall) Fields(s ...googleapi.Field) *UsersGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *UsersGetCall) IfNoneMatch(entityTag string) *UsersGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersGetCall) Context(ctx context.Context) *UsersGetCall {
c.ctx_ = ctx
return c
}
func (c *UsersGetCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users/{user}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"user": c.user,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.get" call.
// Exactly one of *User or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *User.ServerResponse.Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *UsersGetCall) Do(opts ...googleapi.CallOption) (*User, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &User{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the specified User resource.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.users.get",
// "parameterOrder": [
// "project",
// "user"
// ],
// "parameters": {
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "user": {
// "description": "Name of the user resource to return.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users/{user}",
// "response": {
// "$ref": "User"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.users.insert":
type UsersInsertCall struct {
s *Service
project string
user *User
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// Insert: Creates a User resource in the specified project using the
// data included in the request.
func (r *UsersService) Insert(project string, user *User) *UsersInsertCall {
c := &UsersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.user = user
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersInsertCall) Fields(s ...googleapi.Field) *UsersInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersInsertCall) Context(ctx context.Context) *UsersInsertCall {
c.ctx_ = ctx
return c
}
func (c *UsersInsertCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.user)
if err != nil {
return nil, err
}
ctype := "application/json"
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
})
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.insert" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *UsersInsertCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a User resource in the specified project using the data included in the request.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.users.insert",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users",
// "request": {
// "$ref": "User"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
// method id "clouduseraccounts.users.list":
type UsersListCall struct {
s *Service
project string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
}
// List: Retrieves a list of users contained within the specified
// project.
func (r *UsersService) List(project string) *UsersListCall {
c := &UsersListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
return c
}
// Filter sets the optional parameter "filter": Sets a filter expression
// for filtering listed resources, in the form filter={expression}. Your
// {expression} must be in the format: FIELD_NAME COMPARISON_STRING
// LITERAL_STRING.
//
// The FIELD_NAME is the name of the field you want to compare. Only
// atomic field types are supported (string, number, boolean). The
// COMPARISON_STRING must be either eq (equals) or ne (not equals). The
// LITERAL_STRING is the string value to filter to. The literal value
// must be valid for the type of field (string, number, boolean). For
// string fields, the literal value is interpreted as a regular
// expression using RE2 syntax. The literal value must match the entire
// field.
//
// For example, filter=name ne example-instance.
func (c *UsersListCall) Filter(filter string) *UsersListCall {
c.urlParams_.Set("filter", filter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum count of
// results to be returned.
func (c *UsersListCall) MaxResults(maxResults int64) *UsersListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// OrderBy sets the optional parameter "orderBy": Sorts list results by
// a certain order. By default, results are returned in alphanumerical
// order based on the resource name.
//
// You can also sort results in descending order based on the creation
// timestamp using orderBy="creationTimestamp desc". This sorts results
// based on the creationTimestamp field in reverse chronological order
// (newest result first). Use this to sort resources like operations so
// that the newest operation is returned first.
//
// Currently, only sorting by name or creationTimestamp desc is
// supported.
func (c *UsersListCall) OrderBy(orderBy string) *UsersListCall {
c.urlParams_.Set("orderBy", orderBy)
return c
}
// PageToken sets the optional parameter "pageToken": Specifies a page
// token to use. Use this parameter if you want to list the next page of
// results. Set pageToken to the nextPageToken returned by a previous
// list request.
func (c *UsersListCall) PageToken(pageToken string) *UsersListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersListCall) Fields(s ...googleapi.Field) *UsersListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *UsersListCall) IfNoneMatch(entityTag string) *UsersListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersListCall) Context(ctx context.Context) *UsersListCall {
c.ctx_ = ctx
return c
}
func (c *UsersListCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
req.Header.Set("If-None-Match", c.ifNoneMatch_)
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.list" call.
// Exactly one of *UserList or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *UserList.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *UsersListCall) Do(opts ...googleapi.CallOption) (*UserList, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &UserList{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of users contained within the specified project.",
// "httpMethod": "GET",
// "id": "clouduseraccounts.users.list",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "filter": {
// "description": "Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING.\n\nThe FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.\n\nFor example, filter=name ne example-instance.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "500",
// "description": "Maximum count of results to be returned.",
// "format": "uint32",
// "location": "query",
// "maximum": "500",
// "minimum": "0",
// "type": "integer"
// },
// "orderBy": {
// "description": "Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.\n\nYou can also sort results in descending order based on the creation timestamp using orderBy=\"creationTimestamp desc\". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.\n\nCurrently, only sorting by name or creationTimestamp desc is supported.",
// "location": "query",
// "type": "string"
// },
// "pageToken": {
// "description": "Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users",
// "response": {
// "$ref": "UserList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/cloud.useraccounts",
// "https://www.googleapis.com/auth/cloud.useraccounts.readonly"
// ]
// }
}
// method id "clouduseraccounts.users.removePublicKey":
type UsersRemovePublicKeyCall struct {
s *Service
project string
user string
urlParams_ gensupport.URLParams
ctx_ context.Context
}
// RemovePublicKey: Removes the specified public key from the user.
func (r *UsersService) RemovePublicKey(project string, user string, fingerprint string) *UsersRemovePublicKeyCall {
c := &UsersRemovePublicKeyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.project = project
c.user = user
c.urlParams_.Set("fingerprint", fingerprint)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *UsersRemovePublicKeyCall) Fields(s ...googleapi.Field) *UsersRemovePublicKeyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *UsersRemovePublicKeyCall) Context(ctx context.Context) *UsersRemovePublicKeyCall {
c.ctx_ = ctx
return c
}
func (c *UsersRemovePublicKeyCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "{project}/global/users/{user}/removePublicKey")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.Expand(req.URL, map[string]string{
"project": c.project,
"user": c.user,
})
req.Header.Set("User-Agent", c.s.userAgent())
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "clouduseraccounts.users.removePublicKey" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *UsersRemovePublicKeyCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Removes the specified public key from the user.",
// "httpMethod": "POST",
// "id": "clouduseraccounts.users.removePublicKey",
// "parameterOrder": [
// "project",
// "user",
// "fingerprint"
// ],
// "parameters": {
// "fingerprint": {
// "description": "The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key.",
// "location": "query",
// "pattern": "[a-f0-9]{32}",
// "required": true,
// "type": "string"
// },
// "project": {
// "description": "Project ID for this request.",
// "location": "path",
// "pattern": "(?:(?:[-a-z0-9]{1,63}\\.)*(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?):)?(?:[0-9]{1,19}|(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?))",
// "required": true,
// "type": "string"
// },
// "user": {
// "description": "Name of the user for this request.",
// "location": "path",
// "pattern": "[a-z][-a-z0-9_]{0,31}",
// "required": true,
// "type": "string"
// }
// },
// "path": "{project}/global/users/{user}/removePublicKey",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud.useraccounts"
// ]
// }
}
| {
"content_hash": "8e03a2871bcf0edd3396f950a8d9254a",
"timestamp": "",
"source": "github",
"line_count": 3340,
"max_line_length": 725,
"avg_line_length": 35.47844311377246,
"alnum_prop": 0.6841887626795389,
"repo_name": "glerchundi/etcd2-bootstrapper",
"id": "f87b2acad39af3c5d5f74d62fb527dc7d211288e",
"size": "118828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/google.golang.org/api/clouduseraccounts/vm_beta/clouduseraccounts-gen.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "12947"
},
{
"name": "Makefile",
"bytes": "985"
}
],
"symlink_target": ""
} |
var _ = require('lodash'),
path = require('path'),
Q = require('q'),
fs = require('q-io/fs');
/*
1 - load templates from directory
2 - compile and cache templates
3 - process templates
4 - output files
*/
module.exports = function( options ) {
var debugFlag = false;
function log(msg) {
if(debugFlag) console.log(msg);
}
//---------------------------------------------
// check options
/*
var options = {
source: '',
destination: '',
values: {},
debug: false,
updateFileName: function or string
};
*/
if( !options ) throw new Error('options not defined');
if( options.debug ) debugFlag = true;
if( !options.source ) throw new Error('options.source not defined');
var source = options.source;
if( !options.destination ) throw new Error('options.destination not defined');
var destination = options.destination;
if( !options.values ) throw new Error('options.values not defined');
var values = options.values;
//---------------------------------------------
var _updateFileName = null;
if( _.isFunction( options.updateFileName ) ) {
_updateFileName = options.updateFileName;
} else if( _.isString( options.updateFileName ) ) {
_updateFileName = function( ignored ) {
return options.updateFileName;
};
} else {
_updateFileName = function( filename ) { return filename; };
}
//---------------------------------------------
log('\nrunning generate engine \noptions: \n');
log( options );
log('\n------------------------------------\n');
//---------------------------------------------
var TemplateProcessError = (function() {
function TemplateProcessError(message, error) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.toString = function() {
var out = this.name + ': \n ' + this.message;
if(error) out += '\nTemplate Error :\n ' + error.stack;
return out;
};
}
var ClassDef = TemplateProcessError;
ClassDef.prototype = new Error();
ClassDef.prototype.constructor = TemplateProcessError;
return ClassDef;
})();
//---------------------------------------------
function processDirectory() {
var metadata = {};
var templateCache = {};
function filterOnlyFiles(path, stat) {
// ignore dot files like .DS_Store
var filename = path.split('/').pop();
return stat.isFile() && !filename.match(/^\./);
}
return fs.listTree(source, filterOnlyFiles) // list files
.then(function(files) {
var templateName, output;
return Q.all(files.sort().map(function(filePath) {
return fs.read(filePath).then(function(content) { // read template file
log('read: ' + filePath);
templateName = filePath.replace(source + '/', '');
output = {
path: filePath,
name: path.basename(filePath),
templateName: templateName,
directory: path.dirname( filePath ).replace(source, ''),
content: content
};
metadata[templateName] = output;
try{
templateCache[templateName] = _.template(content);
} catch(err) {
throw new TemplateProcessError(filePath, err);
}
return output;
});
}));
})
.then(function(files) { // process templates and write files
log('\n------------------------------------\n');
return Q.all(files.map(function(file) {
var fileUrl, content;
// define file destination
fileUrl = path.join(
destination, // output directory
values.name, // processed templates directory output
file.directory, // exist some sub directory ?
_updateFileName( file.name ) // output file name
);
log( fileUrl );
// process template
content = templateCache[file.templateName](values);
log( content );
log('\n------------------------------------\n');
// create directories tree
return fs.makeTree(path.dirname(fileUrl)).then(function() {
log('write file: ' + fileUrl);
return fs.write(fileUrl, content); // write file to disk
});
}));
});
}
//---------------------------------------------
function processFile() {
return fs.read(source).then(function(content) { // read template file
log('read: ' + source);
var tplCache = null;
try{
tplCache = _.template(content);
} catch(err) {
throw new TemplateProcessError(source, err);
}
return {
name: path.basename(source),
templateCache: tplCache
};
})
.then(function(file) {
log('\n------------------------------------\n');
var fileUrl, content;
// define file destination
fileUrl = path.join(
destination, // output directory
_updateFileName( file.name ) // output file name
);
log( fileUrl );
// process template
content = file.templateCache(values);
log( content );
log('\n------------------------------------\n');
// create directories tree
return fs.makeTree(path.dirname(fileUrl)).then(function() {
log('write file: ' + fileUrl);
return fs.write(fileUrl, content); // write file to disk
});
});
}
//---------------------------------------------
// templates processment flow
return fs.exists( source ).then(function( flag ) {
if( flag ) {
// check if options.source is file or directory
return fs.stat( source ).then(function( stat ) {
if( stat.isDirectory() ) {
return processDirectory(); // directory templates processment flow
} else if( stat.isFile() ) {
return processFile(); // file template processment flow
} else {
throw new Error( 'Invalid : \n ' + source );
}
});
} else {
throw new Error( 'Not found : \n ' + source );
}
});
};
| {
"content_hash": "593646caeb7095e1e1afa46744b32838",
"timestamp": "",
"source": "github",
"line_count": 267,
"max_line_length": 81,
"avg_line_length": 23.45692883895131,
"alnum_prop": 0.5192399808398531,
"repo_name": "the-front/angularjs-ee-boilerplate",
"id": "4dfdc26f0e3136e2527b48399dbc3b78c7af85ba",
"size": "6263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/lib/generate/engine.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "29293"
},
{
"name": "HTML",
"bytes": "29574"
},
{
"name": "JavaScript",
"bytes": "154803"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
/**
* @ngdoc overview
* @ngname horizon.dashboard.identity.users
*
* @description
* Provides all of the services and widgets required
* to support and display users related content.
*/
angular
.module('horizon.dashboard.identity.users', [
'ngRoute',
'horizon.dashboard.identity.users.details',
'horizon.dashboard.identity.users.actions'
])
.constant('horizon.dashboard.identity.users.resourceType', 'OS::Keystone::User')
.constant('horizon.dashboard.identity.users.validationRules', validationRules())
.run(run)
.config(config);
run.$inject = [
'horizon.framework.conf.resource-type-registry.service',
'horizon.dashboard.identity.users.basePath',
'horizon.dashboard.identity.users.resourceType',
'horizon.dashboard.identity.users.service'
];
function run(registry, basePath, userResourceType, usersService) {
registry.getResourceType(userResourceType)
.setNames('User', 'Users', ngettext('User', 'Users', 1))
.setSummaryTemplateUrl(basePath + 'details/drawer.html')
.setDefaultIndexUrl('/identity/users/')
.setProperties(userProperties())
.setListFunction(usersService.getUsersPromise)
.setNeedsFilterFirstFunction(usersService.getFilterFirstSettingPromise)
.tableColumns
.append({
id: 'name',
priority: 1,
sortDefault: true,
urlFunction: usersService.getDetailsPath
})
.append({
id: 'email',
priority: 2,
filters: ['noValue'],
template: '<a ng-href="mailto:{$ item.email $}">{$ item.email $}</a>'
})
.append({
id: 'id',
priority: 1
})
.append({
id: 'enabled',
priority: 2,
filters: ['yesno']
});
registry.getResourceType(userResourceType).filterFacets
.append({
label: gettext('Name'),
name: 'name',
singleton: true,
isServer: true
})
.append({
label: gettext('Email'),
name: 'email',
singleton: true
})
.append({
label: gettext('ID'),
name: 'id',
singleton: true,
isServer: true
})
.append({
label: gettext('Enabled'),
name: 'enabled',
singleton: true,
isServer: true,
options: [
{label: gettext('Yes'), key: 'true'},
{label: gettext('No'), key: 'false'}
]
});
/**
* @name userProperties
* @description resource properties for user module
*/
function userProperties() {
return {
name: gettext('Name'),
email: {label: gettext('Email'), filters: ['noValue']},
id: gettext('ID'),
enabled: {label: gettext('Enabled'), filters: ['yesno']},
domain_id: {label: gettext('Domain ID'), filters: ['noValue']},
domain_name: {label: gettext('Domain Name'), filters: ['noValue']},
description: {label: gettext('Description'), filters: ['noValue']},
default_project_id: {label: gettext('Primary Project ID'), filters: ['noValue']},
project_name: {label: gettext('Primary Project Name'), filters: ['noValue']}
};
}
}
/**
* @ngdoc constant
* @name horizon.dashboard.identity.users.events.validationRules
* @description constants for use in validation fields
*/
function validationRules() {
return {
integer: /^[0-9]+$/,
validatePassword: /.*/,
fieldMaxLength: 255
};
}
config.$inject = [
'$provide',
'$windowProvider',
'$routeProvider'
];
/**
* @name config
* @param {Object} $provide
* @param {Object} $windowProvider
* @param {Object} $routeProvider
* @description Routes used by this module.
* @returns {undefined} Returns nothing
*/
function config($provide, $windowProvider, $routeProvider) {
var path = $windowProvider.$get().STATIC_URL + 'dashboard/identity/users/';
$provide.constant('horizon.dashboard.identity.users.basePath', path);
$routeProvider.when('/identity/users', {
templateUrl: path + 'panel.html'
});
}
})();
| {
"content_hash": "a78e2de1bb5408aff81631ac710f15f4",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 89,
"avg_line_length": 28.58219178082192,
"alnum_prop": 0.5954948478312965,
"repo_name": "openstack/horizon",
"id": "61d552abc4a37d59aea149cc3cc978258c5d1703",
"size": "4791",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "openstack_dashboard/dashboards/identity/static/dashboard/identity/users/users.module.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "583449"
},
{
"name": "JavaScript",
"bytes": "2585531"
},
{
"name": "Python",
"bytes": "5370605"
},
{
"name": "SCSS",
"bytes": "133237"
},
{
"name": "Shell",
"bytes": "6526"
}
],
"symlink_target": ""
} |
define([
'requirejs',
'def:requirejs',
'document',
'./EventObject',
'def:./EventObject',
'def:./sandboxUtilsInner',
], (
requirejs,
defRequire,
document,
EventObject,
defEventObject,
defInner
) => {
'use strict';
// Usage: sandboxUtils.make([dependencies], myFunction);
// myFunction executes inside the sandbox
// Returns a worker-like object which permits communication
// (addEventListener & sendMessage), and destruction (terminate)
const STATE_LOADING = 0;
const STATE_READY = 1;
const STATE_KILLED = 2;
const B64 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
function makeNonce() {
const buffer = new Uint8Array(16);
crypto.getRandomValues(buffer);
let r = '';
for(let i = 0; i < buffer.length; ++ i) {
r += B64[buffer[i] % 64];
}
return r;
}
function buildInvocation(dependencies, fn) {
if(fn && dependencies.length > 0) {
return '() => requirejs(' + JSON.stringify(dependencies) + ', ' + fn.toString() + ')';
} else if(fn) {
return fn.toString();
} else {
return '() => requirejs(' + JSON.stringify(dependencies) + ')';
}
}
class IFrame extends EventObject {
constructor(postMessageFn, terminateFn) {
super();
this.postMessageFn = postMessageFn;
this.terminateFn = terminateFn;
}
postMessage(message) {
this.postMessageFn(message);
}
terminate() {
this.terminateFn();
}
}
function makeContent(dependencies, fn, {allowAllScripts}) {
// Thanks, https://stackoverflow.com/a/23522755/1180785
const safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
// WORKAROUNDS:
// * Chrome doesn't allow relaxing script-src inside an iframe, so we
// have to use blob: to load all scripts from outside (we can also
// use this to eval competitor code where needed)
// * Safari considers blob: to be a non-https resource, so blocks it,
// but it does allow relaxing script-src. So we allow content from
// our detected domain and also allow unsafe-eval for competitor code
const protocol = self.rootProtocol || window.location.protocol;
const href = self.rootHref || window.location.href;
const needUnsafeEval = safari;
let remoteDomain = 'blob:';
let blockRequire = false;
if(safari && protocol !== 'file:') {
const p = href.indexOf('/', href.indexOf('//') + 2);
remoteDomain = (p !== -1) ? href.substr(0, p) : href;
blockRequire = true;
}
// WORKAROUND (Safari): web workers are totally unusable in non-origin
// environments since they block blob URLs and all non-self URLs. So
// for Safari we have to sacrafice some more security thanks to their
// insistence on security.
const needsSameOrigin = (safari && protocol === 'https:');
const src = (
'self.rootProtocol = ' + JSON.stringify(protocol) + ';\n' +
'self.rootHref = ' + JSON.stringify(href) + ';\n' +
'self.restrictedRequire = ' + JSON.stringify(!blockRequire) + ';\n' +
'const requireFactory = ' + defRequire.factory() + ';\n' +
'requireFactory();\n' +
defEventObject.code() + '\n' +
defInner.code() + '\n' +
'requirejs([' + JSON.stringify(defInner.src) + '])' +
'.then(' + buildInvocation(dependencies, fn) + ');\n'
);
const nonce = makeNonce();
const html = (
'<html>\n' +
'<head>\n' +
'<meta charset="utf-8">\n' +
'<meta http-equiv="content-security-policy" content="' +
'script-src \'' + (allowAllScripts ? 'unsafe-inline' : ('nonce-' + nonce)) + '\' ' +
remoteDomain +
(needUnsafeEval ? ' \'unsafe-eval\'' : '') + ';' +
'style-src \'none\';' +
'">\n' +
'<script nonce="' + nonce + '">' + src + '</script>\n' +
'</head>\n' +
'<body>\n' +
'</body>\n' +
'</html>\n'
);
return {
html,
blockRequire,
origin: (needsSameOrigin ? remoteDomain : 'null'),
sandboxing: (
'allow-scripts' +
(needsSameOrigin ? ' allow-same-origin' : '')
),
};
}
function make(dependencies, fn, {allowAllScripts = false} = {}) {
if(typeof dependencies === 'function') {
fn = dependencies;
dependencies = [];
}
if(typeof dependencies === 'string') {
dependencies = [dependencies];
}
const details = makeContent(dependencies, fn, {allowAllScripts});
let blockRequire = details.blockRequire;
const iframe = document.createElement('iframe');
let state = STATE_LOADING;
const queueIn = [];
const postMessage = (message) => {
if(state === STATE_READY) {
iframe.contentWindow.postMessage(message, '*');
} else {
queueIn.push(message);
}
};
function handleScriptRequest(event) {
const path = event.data.requireScriptPath;
if(!path) {
blockRequire = true;
return;
}
if(blockRequire) {
throw new Error('Blocked late sandbox requirejs() call: ' + path);
}
requirejs(['def:' + path], (def) => {
postMessage({
requireScriptPath: path,
requireScriptCode: def.code(),
});
});
}
let o = null;
function messageListener(event) {
if(
event.origin !== details.origin ||
event.source !== iframe.contentWindow
) {
return;
}
if(event.data && event.data.requireScriptPath !== undefined) {
return handleScriptRequest(event);
}
o.trigger('message', [event]);
}
const terminate = () => {
state = STATE_KILLED;
if(iframe && iframe.parentNode) {
iframe.parentNode.removeChild(iframe);
window.removeEventListener('message', messageListener);
}
};
o = new IFrame(postMessage, terminate);
iframe.setAttribute('sandbox', details.sandboxing);
iframe.style.display = 'none';
iframe.setAttribute('src', URL.createObjectURL(new Blob(
[details.html],
{type: 'text/html'}
)));
iframe.addEventListener('error', (event) => {
o.trigger('error', [event]);
});
iframe.addEventListener('load', () => {
if(state === STATE_KILLED) {
return;
}
state = STATE_READY;
postMessage({sandboxConnected: true});
queueIn.forEach(postMessage);
queueIn.length = 0;
}, {once: true});
window.addEventListener('message', messageListener, {
_noSandboxIntercept: true,
});
document.body.appendChild(iframe);
return o;
}
return {
make,
};
});
| {
"content_hash": "025d2b8d6c4548fec75d0c55e2c446c0",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 89,
"avg_line_length": 26.43776824034335,
"alnum_prop": 0.6342532467532468,
"repo_name": "davidje13/koth-webplayer",
"id": "b341dc66f45c2afc3a44e8a756b8c3f51ac9c1c5",
"size": "6160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/sandboxUtils.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23768"
},
{
"name": "HTML",
"bytes": "28529"
},
{
"name": "JavaScript",
"bytes": "444064"
},
{
"name": "Shell",
"bytes": "631"
}
],
"symlink_target": ""
} |
package org.commonjava.indy.model.core.dto;
import org.commonjava.indy.model.core.StoreKey;
import org.commonjava.indy.model.core.StoreType;
import org.commonjava.indy.model.core.io.IndyObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by jdcasey on 4/25/16.
*/
public class NotFoundCacheDTOTest
{
@Test
public void jsonRoundTrip()
throws IOException
{
String firstSectionOnePath = "/path/to/first/file.pom";
String secondSectionOnePath = "/path/to/another/path.pom";
NotFoundCacheSectionDTO sectionOne = new NotFoundCacheSectionDTO( new StoreKey( StoreType.remote, "test" ),
Arrays.asList( firstSectionOnePath, secondSectionOnePath ) );
String firstSectionTwoPath = "/path/to/third/file.pom";
String secondSectionTwoPath = "/path/to/fourth/path.pom";
NotFoundCacheSectionDTO sectionTwo = new NotFoundCacheSectionDTO( new StoreKey( StoreType.remote, "test2" ),
Arrays.asList( firstSectionTwoPath, secondSectionTwoPath ) );
NotFoundCacheDTO in = new NotFoundCacheDTO();
in.addSection( sectionOne );
in.addSection( sectionTwo );
IndyObjectMapper mapper = new IndyObjectMapper( true );
String json = mapper.writeValueAsString( in );
NotFoundCacheDTO out = mapper.readValue( json, NotFoundCacheDTO.class );
assertThat( out, notNullValue() );
Set<NotFoundCacheSectionDTO> sections = out.getSections();
assertThat( sections, notNullValue() );
assertThat( sections.size(), equalTo( 2 ) );
assertThat( sections.contains( sectionOne ), equalTo( true ) );
assertThat( sections.contains( sectionTwo ), equalTo( true ) );
sections.forEach( (section)->{
StoreKey testKey;
Set<String> testPaths;
if ( section.equals( sectionOne ) )
{
testKey = sectionOne.getKey();
testPaths = sectionOne.getPaths();
}
else
{
testKey = sectionTwo.getKey();
testPaths = sectionTwo.getPaths();
}
assertThat( section.getKey(), equalTo( testKey ) );
Set<String> paths = section.getPaths();
assertThat( paths, notNullValue() );
assertThat( paths.size(), equalTo( testPaths.size() ) );
testPaths.forEach( (path)->{
assertThat( path + " NOT found in results for key: " + section.getKey(), paths.contains( path ),
equalTo( true ) );
} );
} );
}
}
| {
"content_hash": "29a6cb289bab2e840b4ff9f71cf181d4",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 135,
"avg_line_length": 36.58024691358025,
"alnum_prop": 0.6068174147823152,
"repo_name": "Commonjava/indy",
"id": "980cba7843d8751c35b95402ac7dce8628a00039",
"size": "3610",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "models/core-java/src/test/java/org/commonjava/indy/model/core/dto/NotFoundCacheDTOTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6390"
},
{
"name": "Dockerfile",
"bytes": "3740"
},
{
"name": "Groovy",
"bytes": "45401"
},
{
"name": "HTML",
"bytes": "73128"
},
{
"name": "Java",
"bytes": "5905423"
},
{
"name": "JavaScript",
"bytes": "75193"
},
{
"name": "Python",
"bytes": "78715"
},
{
"name": "Ruby",
"bytes": "13080"
},
{
"name": "Shell",
"bytes": "32345"
}
],
"symlink_target": ""
} |
//
// Packager.c
// PSPL
//
// Created by Jack Andersen on 4/28/13.
//
//
#define PSPL_INTERNAL
#include <PSPLExtension.h>
#include <PSPLInternal.h>
#include <PSPL/PSPLHash.h>
#include <errno.h>
#include <dirent.h>
#include "Packager.h"
#include "ObjectIndexer.h"
#pragma mark Packager Implementation
/* Package indexer initialiser */
void pspl_packager_init(pspl_packager_context_t* ctx,
unsigned int max_extension_count,
unsigned int max_platform_count,
unsigned int psplc_count) {
ctx->ext_count = 0;
ctx->ext_array = calloc(max_extension_count, sizeof(pspl_extension_t*));
ctx->plat_count = 0;
ctx->plat_array = calloc(max_platform_count, sizeof(pspl_platform_t*));
ctx->indexer_count = 0;
ctx->indexer_cap = psplc_count;
ctx->indexer_array = calloc(psplc_count, sizeof(pspl_indexer_context_t*));
ctx->stubs_count = 0;
ctx->stubs_cap = 50;
ctx->stubs_array = calloc(50, sizeof(pspl_indexer_entry_t*));
}
/* Augment with index */
void pspl_packager_indexer_augment(pspl_packager_context_t* ctx,
pspl_indexer_context_t* indexer) {
int i,j;
uint8_t needs_add;
if (ctx->indexer_count >= ctx->indexer_cap)
pspl_error(-1, "Internal error",
"PSPL Packager would have augmented too many PSPLCs; expected %u",
ctx->indexer_cap);
// Ensure PSPLC isn't already staged for adding
for (i=0 ; i<ctx->indexer_count ; ++i) {
pspl_indexer_context_t* present_idxer = ctx->indexer_array[i];
if (!pspl_hash_cmp(&present_idxer->psplc_hash, &indexer->psplc_hash))
pspl_error(-1, "Duplicate-name PSPLCs added to package",
"PSPLC '%s' and '%s' have the same name hash; "
"this is disallowed by PSPL",
present_idxer->definer, indexer->definer);
}
// Unify extension array
for (i=0 ; i<indexer->ext_count ; ++i) {
needs_add = 1;
const pspl_extension_t* index_ext = indexer->ext_array[i];
for (j=0 ; j<ctx->ext_count ; ++j) {
const pspl_extension_t* pack_ext = ctx->ext_array[j];
if (index_ext == pack_ext) {
needs_add = 0;
break;
}
}
if (needs_add)
ctx->ext_array[ctx->ext_count++] = index_ext;
}
// Unify platform array
for (i=0 ; i<indexer->plat_count ; ++i) {
needs_add = 1;
const pspl_platform_t* index_plat = indexer->plat_array[i];
for (j=0 ; j<ctx->plat_count ; ++j) {
const pspl_platform_t* pack_plat = ctx->plat_array[j];
if (index_plat == pack_plat) {
needs_add = 0;
break;
}
}
if (needs_add)
ctx->plat_array[ctx->plat_count++] = index_plat;
}
// Unify file stubs
for (i=0 ; i<indexer->stubs_count ; ++i) {
needs_add = 1;
pspl_indexer_entry_t* index_stub = indexer->stubs_array[i];
for (j=0 ; j<ctx->stubs_count ; ++j) {
const pspl_indexer_entry_t* pack_stub = ctx->stubs_array[j];
if (!pspl_hash_cmp(&index_stub->object_hash, &pack_stub->object_hash)) {
needs_add = 0;
break;
}
}
if (needs_add) {
if (ctx->stubs_count >= ctx->stubs_cap) {
ctx->stubs_cap *= 2;
ctx->stubs_array = realloc(ctx->stubs_array, ctx->stubs_cap * sizeof(pspl_indexer_entry_t*));
}
ctx->stubs_array[ctx->stubs_count++] = index_stub;
}
}
// Add indexer
ctx->indexer_array[ctx->indexer_count++] = indexer;
}
/* Prepare staged file for packaging */
static void prepare_staged_file(pspl_indexer_entry_t* ent) {
// Concatenate together path
char* path = ent->file_path;
path[0] = '\0';
strlcat(path, ent->stub_source_path, MAXPATHLEN);
if (ent->stub_source_path_ext) {
strlcat(path, ":", MAXPATHLEN);
strlcat(path, ent->stub_source_path_ext, MAXPATHLEN);
}
// Hash path
pspl_hash_ctx_t hash_ctx;
pspl_hash_init(&hash_ctx);
pspl_hash_write(&hash_ctx, path, strlen(path));
pspl_hash* path_hash;
pspl_hash_result(&hash_ctx, path_hash);
char path_hash_str[PSPL_HASH_STRING_LEN];
pspl_hash_fmt(path_hash_str, path_hash);
// Object hash
char object_hash_str[PSPL_HASH_STRING_LEN];
pspl_hash_fmt(object_hash_str, &ent->object_hash);
// Use dirent to scan PSPLFiles for bitwise-matching file
DIR* staging_dir = opendir(driver_state.staging_path);
if (!staging_dir)
pspl_error(-1, "Unable to open Staging Directory", "`%s` inaccessible", driver_state.staging_path);
struct dirent* dent = NULL;
while ((dent = readdir(staging_dir))) {
if (memcmp(dent->d_name, path_hash_str, 40))
continue;
const char* file_obj_hash = strrchr(dent->d_name, '_') + 1;
if (memcmp(file_obj_hash, object_hash_str, 40))
continue;
const char* file_plat_bits_str = strchr(dent->d_name, '_') + 1;
long file_plat_bits = strtol(file_plat_bits_str, NULL, 16);
if (file_plat_bits & ent->build_platform_availability_bits)
break;
}
if (!dent)
pspl_error(-1, "Staged file unavailable",
"there should be a file with path hash '%s' and data hash '%s'",
path_hash_str, object_hash_str);
// Now copy staged path
path[0] = '\0';
strlcpy(path, driver_state.staging_path, MAXPATHLEN);
strlcat(path, dent->d_name, MAXPATHLEN);
// Open file, make sure it still exists
FILE* file = fopen(path, "r");
if (!file)
pspl_error(-1, "Staged file unavailable",
"there should be an accessible file at `%s`; derived from `%s`; errno %d (%s)",
path, ent->stub_source_path, errno, strerror(errno));
// Record length
fseek(file, 0, SEEK_END);
ent->object_len = ftell(file);
fclose(file);
}
/* Write out to PSPLP file */
void pspl_packager_write_psplp(pspl_packager_context_t* ctx,
uint8_t psplp_endianness,
FILE* psplp_file_out) {
int i,j,k;
// Determine endianness
for (i=0 ; i<ctx->plat_count ; ++i)
psplp_endianness |= ctx->plat_array[i]->byte_order;
psplp_endianness &= PSPL_BI_ENDIAN;
if (!psplp_endianness) {
# if __LITTLE_ENDIAN__
psplp_endianness = PSPL_LITTLE_ENDIAN;
# elif __BIG_ENDIAN__
psplp_endianness = PSPL_BIG_ENDIAN;
# endif
}
// Table offset accumulations
uint32_t acc = sizeof(pspl_header_t);
acc += (psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_off_header_bi_t) : sizeof(pspl_off_header_t);
acc += (psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_psplp_header_bi_t) : sizeof(pspl_psplp_header_t);
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_psplp_psplc_index_bi_t) : sizeof(pspl_psplp_psplc_index_t) + sizeof(pspl_hash)) * ctx->indexer_count;
for (i=0 ; i<ctx->indexer_count ; ++i) {
pspl_indexer_context_t* indexer = ctx->indexer_array[i];
//printf("Will Write Beginning: %zu\n", acc);
indexer->extension_obj_base_off = acc;
//acc += sizeof(pspl_hash);
acc += (psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_psplc_header_bi_t) : sizeof(pspl_psplc_header_t);
//printf("Will Write p1: %zu\n", acc);
//printf("Will AHH %u\n",indexer->ext_count);
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_array_extension_bi_t) : sizeof(pspl_object_array_extension_t)) * indexer->ext_count;
//printf("Will Write p2: %zu\n", acc);
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_array_extension_bi_t) : sizeof(pspl_object_array_extension_t)) * indexer->plat_count;
indexer->extension_obj_array_off = acc - indexer->extension_obj_base_off; // PACKAGER SPECIFIC!!! - BASE-RELATIVE OFFSETS!!!
//printf("Will Write p3: %zu\n", acc);
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_hash_record_bi_t) : sizeof(pspl_object_hash_record_t) + sizeof(pspl_hash)) * indexer->h_objects_count;
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_int_record_bi_t) : sizeof(pspl_object_int_record_t)) * indexer->i_objects_count;
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_hash_record_bi_t) : sizeof(pspl_object_hash_record_t) + sizeof(pspl_hash)) * indexer->ph_objects_count;
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_object_int_record_bi_t) : sizeof(pspl_object_int_record_t)) * indexer->pi_objects_count;
indexer->extension_obj_array_padding = ROUND_UP_32(acc) - acc;
acc += indexer->extension_obj_array_padding;
//printf("Will Write: %u\n", acc);
indexer->extension_obj_data_off = acc;
// Per extension object blobs
for (k=0 ; k<indexer->ext_count ; ++k) {
const pspl_extension_t* cur_ext = indexer->ext_array[k];
for (j=0 ; j<indexer->h_objects_count ; ++j) {
pspl_indexer_entry_t* ent = indexer->h_objects_array[j];
if (ent->owner_ext == cur_ext) {
ent->object_off = acc;
if (psplp_endianness == PSPL_LITTLE_ENDIAN)
ent->object_big_data = NULL;
else if (psplp_endianness == PSPL_BIG_ENDIAN)
ent->object_little_data = NULL;
ent->object_padding = ROUND_UP_32(ent->object_len) - ent->object_len;
if (ent->object_little_data && ent->object_big_data &&
ent->object_little_data != ent->object_big_data)
acc += (ent->object_len+ent->object_padding)*2;
else
acc += ent->object_len+ent->object_padding;
}
}
for (j=0 ; j<indexer->i_objects_count ; ++j) {
pspl_indexer_entry_t* ent = indexer->i_objects_array[j];
if (ent->owner_ext == cur_ext) {
ent->object_off = acc;
if (psplp_endianness == PSPL_LITTLE_ENDIAN)
ent->object_big_data = NULL;
else if (psplp_endianness == PSPL_BIG_ENDIAN)
ent->object_little_data = NULL;
ent->object_padding = ROUND_UP_32(ent->object_len) - ent->object_len;
if (ent->object_little_data && ent->object_big_data &&
ent->object_little_data != ent->object_big_data)
acc += (ent->object_len+ent->object_padding)*2;
else
acc += ent->object_len+ent->object_padding;
}
}
}
// Per platform object blobs
for (k=0 ; k<indexer->plat_count ; ++k) {
const pspl_platform_t* cur_plat = indexer->plat_array[k];
for (j=0 ; j<indexer->ph_objects_count ; ++j) {
pspl_indexer_entry_t* ent = indexer->ph_objects_array[j];
if (ent->owner_plat == cur_plat) {
ent->object_off = acc;
if (psplp_endianness == PSPL_LITTLE_ENDIAN)
ent->object_big_data = NULL;
else if (psplp_endianness == PSPL_BIG_ENDIAN)
ent->object_little_data = NULL;
ent->object_padding = ROUND_UP_32(ent->object_len) - ent->object_len;
if (ent->object_little_data && ent->object_big_data &&
ent->object_little_data != ent->object_big_data)
acc += (ent->object_len+ent->object_padding)*2;
else
acc += ent->object_len+ent->object_padding;
}
}
for (j=0 ; j<indexer->pi_objects_count ; ++j) {
pspl_indexer_entry_t* ent = indexer->pi_objects_array[j];
if (ent->owner_plat == cur_plat) {
ent->object_off = acc;
if (psplp_endianness == PSPL_LITTLE_ENDIAN)
ent->object_big_data = NULL;
else if (psplp_endianness == PSPL_BIG_ENDIAN)
ent->object_little_data = NULL;
ent->object_padding = ROUND_UP_32(ent->object_len) - ent->object_len;
if (ent->object_little_data && ent->object_big_data &&
ent->object_little_data != ent->object_big_data)
acc += (ent->object_len+ent->object_padding)*2;
else
acc += ent->object_len+ent->object_padding;
}
}
}
indexer->extension_obj_blobs_len = acc - indexer->extension_obj_data_off; // PACKAGER SPECIFIC!!!
//printf("Will Write End: %u\n", acc);
}
uint32_t file_stub_array_off = acc;
acc += ((psplp_endianness==PSPL_BI_ENDIAN) ? sizeof(pspl_file_stub_bi_t) : sizeof(pspl_file_stub_t) + sizeof(pspl_hash)) * ctx->stubs_count;
uint32_t stub_data_table_pre_padding = acc;
acc = ROUND_UP_32(acc);
stub_data_table_pre_padding = acc - stub_data_table_pre_padding;
uint32_t extension_name_table_off = acc;
for (i=0 ; i<ctx->stubs_count ; ++i) {
pspl_indexer_entry_t* file_ent = ctx->stubs_array[i];
file_ent->file_off = extension_name_table_off;
prepare_staged_file(file_ent);
extension_name_table_off += file_ent->object_len;
uint32_t padding_diff = extension_name_table_off;
extension_name_table_off = ROUND_UP_32(extension_name_table_off);
file_ent->file_padding = extension_name_table_off - padding_diff;
}
uint32_t platform_name_table_off = extension_name_table_off;
for (i=0 ; i<ctx->ext_count ; ++i)
platform_name_table_off += strlen(ctx->ext_array[i]->extension_name) + 1;
acc = platform_name_table_off;
for (i=0 ; i<ctx->plat_count ; ++i)
acc += strlen(ctx->plat_array[i]->platform_name) + 1;
// Determine padding length at end
uint32_t pad_end = ROUND_UP_32(acc);
pad_end -= acc;
// Populate main header
pspl_header_t pspl_header = {
.magic = PSPL_MAGIC_DEF,
.package_flag = PSPL_PSPLP,
.version = PSPL_VERSION,
.endian_flags = psplp_endianness,
};
// Populate offset header
pspl_off_header_bi_t pspl_off_header;
SET_BI_U32(pspl_off_header, extension_name_table_c, ctx->ext_count);
SET_BI_U32(pspl_off_header, extension_name_table_off, extension_name_table_off);
SET_BI_U32(pspl_off_header, platform_name_table_c, ctx->plat_count);
SET_BI_U32(pspl_off_header, platform_name_table_off, platform_name_table_off);
SET_BI_U32(pspl_off_header, file_table_c, ctx->stubs_count);
SET_BI_U32(pspl_off_header, file_table_off, file_stub_array_off);
// Write main header
fwrite(&pspl_header, 1, sizeof(pspl_header_t), psplp_file_out);
// Write offset header
switch (psplp_endianness) {
case PSPL_LITTLE_ENDIAN:
fwrite(&pspl_off_header.little, 1, sizeof(pspl_off_header_t), psplp_file_out);
break;
case PSPL_BIG_ENDIAN:
fwrite(&pspl_off_header.big, 1, sizeof(pspl_off_header_t), psplp_file_out);
break;
case PSPL_BI_ENDIAN:
fwrite(&pspl_off_header, 1, sizeof(pspl_off_header_bi_t), psplp_file_out);
break;
default:
break;
}
// Write PSPLP header
pspl_psplp_header_bi_t psplp_head;
SET_BI_U32(psplp_head, psplc_count, ctx->indexer_count);
switch (psplp_endianness) {
case PSPL_LITTLE_ENDIAN:
fwrite(&psplp_head.little, 1, sizeof(pspl_psplp_header_t), psplp_file_out);
break;
case PSPL_BIG_ENDIAN:
fwrite(&psplp_head.big, 1, sizeof(pspl_psplp_header_t), psplp_file_out);
break;
case PSPL_BI_ENDIAN:
fwrite(&psplp_head, 1, sizeof(pspl_psplp_header_bi_t), psplp_file_out);
break;
default:
break;
}
// Write PSPLC hash and base offsets for indexers
for (i=0 ; i<ctx->indexer_count ; ++i) {
pspl_indexer_context_t* indexer = ctx->indexer_array[i];
fwrite(&indexer->psplc_hash, 1, sizeof(pspl_hash), psplp_file_out);
pspl_psplp_psplc_index_bi_t psplc_record;
SET_BI_U32(psplc_record, psplc_base, indexer->extension_obj_base_off);
SET_BI_U32(psplc_record, psplc_tables_len,
indexer->extension_obj_data_off - indexer->extension_obj_base_off);
SET_BI_U32(psplc_record, psplc_blobs_len, indexer->extension_obj_blobs_len);
switch (psplp_endianness) {
case PSPL_LITTLE_ENDIAN:
fwrite(&psplc_record.little, 1, sizeof(pspl_psplp_psplc_index_t), psplp_file_out);
break;
case PSPL_BIG_ENDIAN:
fwrite(&psplc_record.big, 1, sizeof(pspl_psplp_psplc_index_t), psplp_file_out);
break;
case PSPL_BI_ENDIAN:
fwrite(&psplc_record, 1, sizeof(pspl_psplp_psplc_index_bi_t), psplp_file_out);
break;
default:
break;
}
}
// Perform bare file write
for (i=0 ; i<ctx->indexer_count ; ++i) {
pspl_indexer_context_t* indexer = ctx->indexer_array[i];
pspl_indexer_write_psplc_bare(indexer, psplp_endianness, (pspl_indexer_globals_t*)ctx, psplp_file_out);
}
// Populate and write all file-stub objects
for (i=0 ; i<ctx->stubs_count ; ++i) {
const pspl_indexer_entry_t* ent = ctx->stubs_array[i];
pspl_file_stub_bi_t stub_record;
SET_BI_U32(stub_record, platform_availability_bits,
union_plat_bits((pspl_indexer_globals_t*)ctx, ent->parent, ent->platform_availability_bits));
SET_BI_U32(stub_record, file_off, ent->file_off);
SET_BI_U32(stub_record, file_len, (uint32_t)ent->object_len);
// Write data hash
fwrite(&ent->object_hash, 1, sizeof(pspl_hash), psplp_file_out);
// Write structure
switch (psplp_endianness) {
case PSPL_LITTLE_ENDIAN:
fwrite(&stub_record.little, 1, sizeof(pspl_file_stub_t), psplp_file_out);
break;
case PSPL_BIG_ENDIAN:
fwrite(&stub_record.big, 1, sizeof(pspl_file_stub_t), psplp_file_out);
break;
case PSPL_BI_ENDIAN:
fwrite(&stub_record, 1, sizeof(pspl_file_stub_bi_t), psplp_file_out);
break;
default:
break;
}
}
// Data blob pre-padding
for (i=0 ; i<stub_data_table_pre_padding ; ++i)
fwrite("", 1, 1, psplp_file_out);
// Write all file data blobs
for (i=0 ; i<ctx->stubs_count ; ++i) {
const pspl_indexer_entry_t* ent = ctx->stubs_array[i];
// Copy in file data
uint8_t buf[8196];
size_t rem_len = ent->object_len;
size_t read_len;
FILE* file = fopen(ent->file_path, "r");
if (!file)
pspl_error(-1, "File suddenly unavailable",
"`%s` is unable to be re-opened; errno %d (%s)",
ent->file_path, errno, strerror(errno));
do {
read_len = fread(buf, 1, (rem_len>8196)?8196:rem_len, file);
if (!read_len)
pspl_error(-1, "Unexpected end of staged file",
"`%s` ended with %zu bytes to go",
ent->file_path, rem_len);
fwrite(buf, 1, read_len, psplp_file_out);
rem_len -= read_len;
} while (rem_len > 0);
fclose(file);
// Post padding
for (j=0 ; j<ent->file_padding ; ++j)
fwrite("", 1, 1, psplp_file_out);
}
// Write all Extension name string blobs
for (i=0 ; i<ctx->ext_count ; ++i) {
const pspl_extension_t* ext = ctx->ext_array[i];
fwrite(ext->extension_name, 1, strlen(ext->extension_name)+1, psplp_file_out);
}
// Write all Platform name string blobs
for (i=0 ; i<ctx->plat_count ; ++i) {
const pspl_platform_t* plat = ctx->plat_array[i];
fwrite(plat->platform_name, 1, strlen(plat->platform_name)+1, psplp_file_out);
}
// Pad with 0xFF
char ff = 0xff;
for (i=0 ; i<pad_end ; ++i)
fwrite(&ff, 1, 1, psplp_file_out);
}
| {
"content_hash": "dcc4d5c0ef17b470e8d2544350e149d5",
"timestamp": "",
"source": "github",
"line_count": 520,
"max_line_length": 175,
"avg_line_length": 40.8,
"alnum_prop": 0.5434106334841629,
"repo_name": "jackoalan/PSPL",
"id": "bf4522e543a064445adb8655236dd39e298b4f80",
"size": "21216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Toolchain/Packager.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2833"
},
{
"name": "C",
"bytes": "852140"
},
{
"name": "C++",
"bytes": "24664"
},
{
"name": "Objective-C",
"bytes": "2864"
},
{
"name": "Python",
"bytes": "91654"
},
{
"name": "Shell",
"bytes": "344"
}
],
"symlink_target": ""
} |
:host{
background-color: lightgrey;
min-height: 30px;
}
.social-image {
width: 25px;
height: 25px;
margin-left: 10px;
vertical-align: middle;
}
.copyright{
vertical-align: middle;
} | {
"content_hash": "2200840fb2544d6646288434506d0ee0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 16.076923076923077,
"alnum_prop": 0.631578947368421,
"repo_name": "hotsaucemedia/hsm-store",
"id": "71b56ccbfc579b173afa8b106f5e3784c52183b4",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sample/client/src/fw/footer/footer.component.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "957"
}
],
"symlink_target": ""
} |
package seedu.today.logic.parser;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ocpsoft.prettytime.nlp.PrettyTimeParser;
import org.ocpsoft.prettytime.nlp.parse.DateGroup;
//@@author A0144422R
public class SeperableParser {
protected static final int NUMBER_OF_ARGUMENTS_IN_STARTING_TIME_AND_DEADLINE = 2;
protected String args;
protected String[] getTags() {
Pattern pattern = Pattern.compile(CliSyntax.TAGS);
Matcher matcher = pattern.matcher(args);
ArrayList<String> tags = new ArrayList<String>();
while (matcher.find()) {
assert matcher.group().length() > 0;
tags.add(matcher.group().trim().substring(1));
}
args = matcher.replaceAll("");
return (tags.toArray(new String[0]));
}
protected String getArgument(String key) {
String reverseString = new StringBuilder(args).reverse().toString();
String reverseKey = new StringBuilder(key).reverse().toString();
Pattern pattern = Pattern.compile(CliSyntax.END_OF_A_WORD + reverseKey + CliSyntax.END_OF_A_WORD);
Matcher matcher = pattern.matcher(reverseString);
if (matcher.find()) {
String arg = args.substring(reverseString.length() - matcher.start());
args = args.substring(0, reverseString.length() - matcher.end());
return arg.trim();
} else {
return null;
}
}
protected List<String> getMoreThanOneArguments(String regex, String[] captureGroups) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(args);
if (matcher.matches()) {
List<String> arguments = new ArrayList<String>();
for (String captureGroup : captureGroups) {
arguments.add(matcher.group(captureGroup).trim());
}
args = matcher.group("rest").trim();
return arguments;
} else {
return null;
}
}
protected List<Date> getStartingTimeAndDeadline() {
String tmpArgs = args;
String correctDateTime = "";
List<String> datesString = getMoreThanOneArguments(CliSyntax.STARTINGTIME_AND_DEADLINE_REVERSE_REGEX,
CliSyntax.CAPTURE_GROUPS_OF_EVENT);
if (datesString == null) {
args = tmpArgs;
return null;
}
assert datesString.size() == NUMBER_OF_ARGUMENTS_IN_STARTING_TIME_AND_DEADLINE;
List<Date> dates = new ArrayList<Date>();
for (int i = 0; i < NUMBER_OF_ARGUMENTS_IN_STARTING_TIME_AND_DEADLINE; i++) {
List<DateGroup> group = new PrettyTimeParser().parseSyntax(ParserUtil.correctDateFormat(datesString.get(i))
+ (i == 1 ? CliSyntax.DEFAULT_STARTING_TIME : CliSyntax.DEFAULT_DEADLINE));
if (group == null || group.size() > NUMBER_OF_ARGUMENTS_IN_STARTING_TIME_AND_DEADLINE
|| (!group.get(0).getText().equals(datesString.get(i)) && (!group.get(0).getText()
.equals(ParserUtil.correctDateFormat(datesString.get(i))
+ (i == CliSyntax.INDEX_OF_STARTINGTIME ?
CliSyntax.DEFAULT_STARTING_TIME : CliSyntax.DEFAULT_DEADLINE))
&& !group.get(0).getText().equals(ParserUtil.correctDateFormat(datesString.get(i)))))) {
args = tmpArgs;
return null;
} else {
dates.addAll(group.get(0).getDates());
correctDateTime = ((i == CliSyntax.INDEX_OF_STARTINGTIME ? "from " : "to ")
+ group.get(0).getText() + " ") + correctDateTime;
}
}
if (dates.get(CliSyntax.INDEX_OF_STARTINGTIME).after(dates.get(CliSyntax.INDEX_OF_DEADLINE))) {
args = tmpArgs;
return null;
}
dates = new PrettyTimeParser().parse(correctDateTime);
return dates;
}
protected Date getDeadline() {
String tmpArgs = args;
String deadlineString = getArgument(CliSyntax.DEADLINE_ONLY);
if (deadlineString == null) {
args = tmpArgs;
return null;
}
List<DateGroup> group = new PrettyTimeParser()
.parseSyntax(ParserUtil.correctDateFormat(deadlineString) + CliSyntax.DEFAULT_DEADLINE);
if (group == null || group.get(0).getPosition() != 0 || group.size() > 2
|| group.get(0).getDates().size() > 1) {
args = tmpArgs;
return null;
} else {
return group.get(0).getDates().get(0);
}
}
}
| {
"content_hash": "722f03f139d591c9bdb840e903d3ec96",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 119,
"avg_line_length": 41.46086956521739,
"alnum_prop": 0.587248322147651,
"repo_name": "CS2103JAN2017-T09-B1/main",
"id": "4376233ee954b10013197a4a6691681a64b0e434",
"size": "4768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/seedu/today/logic/parser/SeperableParser.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22691"
},
{
"name": "HTML",
"bytes": "32420"
},
{
"name": "Java",
"bytes": "463472"
},
{
"name": "Shell",
"bytes": "1525"
}
],
"symlink_target": ""
} |
BOOST_FIXTURE_TEST_SUITE(wallet_crypto, BasicTestingSetup)
bool OldSetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod, unsigned char* chKey, unsigned char* chIV)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
memory_cleanse(chKey, sizeof(chKey));
memory_cleanse(chIV, sizeof(chIV));
return false;
}
return true;
}
bool OldEncrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext, const unsigned char chKey[32], const unsigned char chIV[16])
{
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool OldDecrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext, const unsigned char chKey[32], const unsigned char chIV[16])
{
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0;
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0;
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
class TestCrypter
{
public:
static void TestPassphraseSingle(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
unsigned char chIV[WALLET_CRYPTO_IV_SIZE];
CCrypter crypt;
crypt.SetKeyFromPassphrase(passphrase, vchSalt, rounds, 0);
OldSetKeyFromPassphrase(passphrase, vchSalt, rounds, 0, chKey, chIV);
BOOST_CHECK_MESSAGE(memcmp(chKey, crypt.chKey, sizeof(chKey)) == 0, \
HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(crypt.chKey, crypt.chKey + (sizeof crypt.chKey)));
BOOST_CHECK_MESSAGE(memcmp(chIV, crypt.chIV, sizeof(chIV)) == 0, \
HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(crypt.chIV, crypt.chIV + (sizeof crypt.chIV)));
if(!correctKey.empty())
BOOST_CHECK_MESSAGE(memcmp(chKey, &correctKey[0], sizeof(chKey)) == 0, \
HexStr(chKey, chKey+sizeof(chKey)) + std::string(" != ") + HexStr(correctKey.begin(), correctKey.end()));
if(!correctIV.empty())
BOOST_CHECK_MESSAGE(memcmp(chIV, &correctIV[0], sizeof(chIV)) == 0,
HexStr(chIV, chIV+sizeof(chIV)) + std::string(" != ") + HexStr(correctIV.begin(), correctIV.end()));
}
static void TestPassphrase(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
TestPassphraseSingle(vchSalt, passphrase, rounds, correctKey, correctIV);
for(SecureString::const_iterator i(passphrase.begin()); i != passphrase.end(); ++i)
TestPassphraseSingle(vchSalt, SecureString(i, passphrase.end()), rounds);
}
static void TestDecrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchCiphertext, \
const std::vector<unsigned char>& vchPlaintext = std::vector<unsigned char>())
{
CKeyingMaterial vchDecrypted1;
CKeyingMaterial vchDecrypted2;
int result1, result2;
result1 = crypt.Decrypt(vchCiphertext, vchDecrypted1);
result2 = OldDecrypt(vchCiphertext, vchDecrypted2, crypt.chKey, crypt.chIV);
BOOST_CHECK(result1 == result2);
// These two should be equal. However, OpenSSL 1.0.1j introduced a change
// that would zero all padding except for the last byte for failed decrypts.
// This behavior was reverted for 1.0.1k.
if (vchDecrypted1 != vchDecrypted2 && vchDecrypted1.size() >= AES_BLOCK_SIZE && SSLeay() == 0x100010afL)
{
for(CKeyingMaterial::iterator it = vchDecrypted1.end() - AES_BLOCK_SIZE; it != vchDecrypted1.end() - 1; it++)
*it = 0;
}
BOOST_CHECK_MESSAGE(vchDecrypted1 == vchDecrypted2, HexStr(vchDecrypted1.begin(), vchDecrypted1.end()) + " != " + HexStr(vchDecrypted2.begin(), vchDecrypted2.end()));
if (vchPlaintext.size())
BOOST_CHECK(CKeyingMaterial(vchPlaintext.begin(), vchPlaintext.end()) == vchDecrypted2);
}
static void TestEncryptSingle(const CCrypter& crypt, const CKeyingMaterial& vchPlaintext,
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
std::vector<unsigned char> vchCiphertext1;
std::vector<unsigned char> vchCiphertext2;
int result1 = crypt.Encrypt(vchPlaintext, vchCiphertext1);
int result2 = OldEncrypt(vchPlaintext, vchCiphertext2, crypt.chKey, crypt.chIV);
BOOST_CHECK(result1 == result2);
BOOST_CHECK(vchCiphertext1 == vchCiphertext2);
if (!vchCiphertextCorrect.empty())
BOOST_CHECK(vchCiphertext2 == vchCiphertextCorrect);
const std::vector<unsigned char> vchPlaintext2(vchPlaintext.begin(), vchPlaintext.end());
if(vchCiphertext1 == vchCiphertext2)
TestDecrypt(crypt, vchCiphertext1, vchPlaintext2);
}
static void TestEncrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchPlaintextIn, \
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
TestEncryptSingle(crypt, CKeyingMaterial(vchPlaintextIn.begin(), vchPlaintextIn.end()), vchCiphertextCorrect);
for(std::vector<unsigned char>::const_iterator i(vchPlaintextIn.begin()); i != vchPlaintextIn.end(); ++i)
TestEncryptSingle(crypt, CKeyingMaterial(i, vchPlaintextIn.end()));
}
};
BOOST_AUTO_TEST_CASE(passphrase) {
// These are expensive.
TestCrypter::TestPassphrase(ParseHex("0000deadbeef0000"), "test", 25000, \
ParseHex("fc7aba077ad5f4c3a0988d8daa4810d0d4a0e3bcb53af662998898f33df0556a"), \
ParseHex("cf2f2691526dd1aa220896fb8bf7c369"));
std::string hash(GetRandHash().ToString());
std::vector<unsigned char> vchSalt(8);
GetRandBytes(&vchSalt[0], vchSalt.size());
uint32_t rounds = insecure_rand();
if (rounds > 30000)
rounds = 30000;
TestCrypter::TestPassphrase(vchSalt, SecureString(hash.begin(), hash.end()), rounds);
}
BOOST_AUTO_TEST_CASE(encrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
TestCrypter::TestEncrypt(crypt, ParseHex("22bcade09ac03ff6386914359cfe885cfeb5f77ff0d670f102f619687453b29d"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestEncrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_CASE(decrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
// Some corner cases the came up while testing
TestCrypter::TestDecrypt(crypt,ParseHex("795643ce39d736088367822cdc50535ec6f103715e3e48f4f3b1a60a08ef59ca"));
TestCrypter::TestDecrypt(crypt,ParseHex("de096f4a8f9bd97db012aa9d90d74de8cdea779c3ee8bc7633d8b5d6da703486"));
TestCrypter::TestDecrypt(crypt,ParseHex("32d0a8974e3afd9c6c3ebf4d66aa4e6419f8c173de25947f98cf8b7ace49449c"));
TestCrypter::TestDecrypt(crypt,ParseHex("e7c055cca2faa78cb9ac22c9357a90b4778ded9b2cc220a14cea49f931e596ea"));
TestCrypter::TestDecrypt(crypt,ParseHex("b88efddd668a6801d19516d6830da4ae9811988ccbaf40df8fbb72f3f4d335fd"));
TestCrypter::TestDecrypt(crypt,ParseHex("8cae76aa6a43694e961ebcb28c8ca8f8540b84153d72865e8561ddd93fa7bfa9"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestDecrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_SUITE_END()
| {
"content_hash": "b0a3f033c07b46ae422e459c587cb12c",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 211,
"avg_line_length": 43.96279069767442,
"alnum_prop": 0.6873677528565383,
"repo_name": "BTCDDev/bitcoin",
"id": "c5f55ef5f0dac3559dfc60f4383b8baeab569a00",
"size": "9868",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/wallet/test/crypto_tests.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28456"
},
{
"name": "C",
"bytes": "702976"
},
{
"name": "C++",
"bytes": "4601814"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "3792"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "32388"
},
{
"name": "M4",
"bytes": "183023"
},
{
"name": "Makefile",
"bytes": "103215"
},
{
"name": "Objective-C",
"bytes": "3771"
},
{
"name": "Objective-C++",
"bytes": "7240"
},
{
"name": "Protocol Buffer",
"bytes": "2308"
},
{
"name": "Python",
"bytes": "956547"
},
{
"name": "QMake",
"bytes": "2020"
},
{
"name": "Shell",
"bytes": "37607"
}
],
"symlink_target": ""
} |
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class jv {
private static int numNodes = -1;
private static final int[][] nodes;
private static final byte[] visited;
static {
nodes = readPlaces();
visited = new byte[numNodes];
}
public static void main(final String[] args) {
// warm up a bit
for (int i = 0; i < 10; i++) {
getLongestPath(0, nodes[0], visited);
}
final long start = System.nanoTime();
final int len = getLongestPath(0, nodes[0], visited);
final long duration = (System.nanoTime() - start) / 1000000; // ns -> ms
System.out.printf("%d LANGUAGE Java %d\n", len, duration);
}
/**
* int[node][cost|dest|...]
*/
private static int[][] readPlaces() {
try (Scanner in = new Scanner(new File("agraph"))) {
numNodes = in.nextInt();
int[][] nodes = new int[numNodes][];
for (int i = 0; i < numNodes; i++) {
nodes[i] = new int[0];
}
while (in.hasNextInt()) {
int node = in.nextInt();
int neighbour = in.nextInt();
int cost = in.nextInt();
int index = nodes[node].length;
int[] replacement = Arrays.copyOf(nodes[node], index + 2);
replacement[index] = cost;
replacement[index + 1] = neighbour;
nodes[node] = replacement;
}
// reduce any fragmentation
int[][] newNodes = new int[numNodes][];
for (int i = 0; i < numNodes; i++) {
newNodes[i] = Arrays.copyOf(nodes[i], nodes[i].length);
}
return newNodes;
} catch (Exception e) {
return null;
}
}
private static int getLongestPath(final int nodeID, final int[] row, final byte[] visited) {
visited[nodeID] = 1;
int max = 0;
for (int i = 1; i < row.length; i += 2) {
final int dest = row[i];
if (visited[dest] == 0) {
max = Math.max(row[i - 1] + getLongestPath(dest, nodes[dest], visited), max);
}
}
visited[nodeID] = 0;
return max;
}
}
| {
"content_hash": "950bcc1b741dbbd125d16de38e250f87",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 93,
"avg_line_length": 26.125,
"alnum_prop": 0.6055289739500266,
"repo_name": "logicchains/LPATHBench",
"id": "f5a630c52fbe92860e1935ad45c799732afad6b2",
"size": "1881",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jv.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "20991"
},
{
"name": "C#",
"bytes": "2054"
},
{
"name": "C++",
"bytes": "6254"
},
{
"name": "Clojure",
"bytes": "2137"
},
{
"name": "Common Lisp",
"bytes": "2422"
},
{
"name": "Crystal",
"bytes": "999"
},
{
"name": "D",
"bytes": "1909"
},
{
"name": "Dart",
"bytes": "1454"
},
{
"name": "F#",
"bytes": "1550"
},
{
"name": "Factor",
"bytes": "1672"
},
{
"name": "Fortran",
"bytes": "5282"
},
{
"name": "Go",
"bytes": "4379"
},
{
"name": "Haskell",
"bytes": "1880"
},
{
"name": "Java",
"bytes": "3804"
},
{
"name": "JavaScript",
"bytes": "3615"
},
{
"name": "Julia",
"bytes": "1110"
},
{
"name": "Lua",
"bytes": "3262"
},
{
"name": "Makefile",
"bytes": "2173"
},
{
"name": "Nim",
"bytes": "1047"
},
{
"name": "OCaml",
"bytes": "1676"
},
{
"name": "PHP",
"bytes": "1089"
},
{
"name": "Perl",
"bytes": "912"
},
{
"name": "Python",
"bytes": "2933"
},
{
"name": "Racket",
"bytes": "1983"
},
{
"name": "Ruby",
"bytes": "703"
},
{
"name": "Rust",
"bytes": "7266"
},
{
"name": "Scala",
"bytes": "1884"
},
{
"name": "Shell",
"bytes": "2663"
},
{
"name": "Swift",
"bytes": "2008"
}
],
"symlink_target": ""
} |
{% extends "withoutnav_template.html" %}
{% from "components/table.html" import list_table, field, text_field, link_field, right_aligned_field_heading, hidden_field_heading %}
{% from "components/page-footer.html" import page_footer %}
{% block per_page_title %}
Provider versions
{% endblock %}
{% block maincolumn_content %}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-large">{{ provider_versions[0].display_name }}</h1>
{% call(item, row_number) list_table(
provider_versions,
caption='',
caption_visible=False,
empty_message='No history for this provider',
field_headings=['Version', 'Last Updated', 'Updated By', 'Priority', 'Active'],
field_headings_visible=True
) %}
{{ text_field(item.version) }}
{% if item.updated_at %}
{{ text_field(item.updated_at|format_datetime_short) }}
{% else %}
{{ text_field('None') }}
{% endif %}
{% if item.created_by %}
{{ text_field(item.created_by.name) }}
{% else %}
{{ text_field('None') }}
{% endif %}
{{ text_field(item.priority) }}
{{ text_field(item.active) }}
{% endcall %}
{{ page_footer(
back_link=url_for('main.view_providers'),
back_link_text="Back to providers"
) }}
</div>
</div>
{% endblock %}
| {
"content_hash": "aa83a71ca8998369a5652ffb2e7fe2a4",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 134,
"avg_line_length": 27.153846153846153,
"alnum_prop": 0.5651558073654391,
"repo_name": "gov-cjwaszczuk/notifications-admin",
"id": "d934e7ff0bd6c434cc512e6719321eac1746c608",
"size": "1412",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/views/providers/provider.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "62775"
},
{
"name": "HTML",
"bytes": "300104"
},
{
"name": "JavaScript",
"bytes": "33859"
},
{
"name": "Makefile",
"bytes": "9209"
},
{
"name": "Python",
"bytes": "1013002"
},
{
"name": "Shell",
"bytes": "5460"
}
],
"symlink_target": ""
} |
package me.savikin.kris.common.blocks;
import me.savikin.kris.common.blocks.te.TileEntityAirPump;
import me.savikin.kris.common.helper.BlockCreationHelper;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
/**
* Created by Mark on 26/06/2016.
*/
public class BlocksInit
{
public static Block air_pump;
public static void init()
{
air_pump = new BlockAirPump();
BlockCreationHelper.createBlock(air_pump, "air_pump");
GameRegistry.registerTileEntity(TileEntityAirPump.class, "te_air_pump");
((PSBlock)air_pump).registerItemModel(Item.getItemFromBlock(air_pump));
}
}
| {
"content_hash": "36154de7602eab6cda8d65153db8b626",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 80,
"avg_line_length": 28.958333333333332,
"alnum_prop": 0.7352517985611511,
"repo_name": "andrejsavikin/Kris",
"id": "f12a49f987e9f40de157dee67c603a48b365d21c",
"size": "695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/me/savikin/kris/common/blocks/BlocksInit.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8899"
}
],
"symlink_target": ""
} |
package info.istamendil.bookcatalogue.extensions.pebble;
import com.mitchellbosecke.pebble.extension.Function;
import com.mitchellbosecke.pebble.template.EvaluationContext;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContext;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
//ToDo: Add more functionality like adding host, schema.
/**
* Function for generating urls with context etc.
* Differ from Symfony Twig function due specific Java ideas.
*/
@Component
public class FullUriFunction implements Function {
@Autowired
private ServletContext servletContext;
@Override
public List<String> getArgumentNames() {
return Arrays.asList("uri");
}
@Override
public Object execute(Map<String, Object> args, PebbleTemplate pebbleTemplate, EvaluationContext evaluationContext, int i) {
String input = (String)args.get("uri");
StringBuilder fullUri = new StringBuilder(input);
fullUri.insert(0, servletContext.getContextPath());
return fullUri.toString();
}
}
| {
"content_hash": "bff1634841b38201eaf4413e0cb168ad",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 128,
"avg_line_length": 31.81578947368421,
"alnum_prop": 0.7626137303556658,
"repo_name": "ist-programming/spring-bookcatalogue",
"id": "ab92d5eb4a85b08294c8457b57877da4d49bae91",
"size": "1209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/info/istamendil/bookcatalogue/extensions/pebble/FullUriFunction.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1296"
},
{
"name": "HTML",
"bytes": "2212"
},
{
"name": "Java",
"bytes": "104395"
},
{
"name": "TSQL",
"bytes": "5610"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Messaging.Queue.Provider.Samples.Console")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Messaging.Queue.Provider.Samples.Console")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9547a267-f7a0-41bd-84b5-ae08cbed549f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "9b04d52d63619118e9d0aaf41696a62c",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 40.361111111111114,
"alnum_prop": 0.7494838265657261,
"repo_name": "brunobrandes/messaging-queue-provider",
"id": "36f734afd619ce3e8816226d98bc0b31742c31e1",
"size": "1456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Console/Messaging.Queue.Provider.Samples.Console/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "33448"
}
],
"symlink_target": ""
} |
package com.stp.stayzilla.constants;
/**
* Created by Santhosh on 01-02-2015.
*/
public interface AppConstants {
public static String RESPONSE_KEY = "response_key";
}
| {
"content_hash": "4fde03bee83948b25ffe60f911890682",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 55,
"avg_line_length": 17.6,
"alnum_prop": 0.7102272727272727,
"repo_name": "SanthoshDhandapani/StayZillaHackathon",
"id": "6dae0166b66fc884f5c6d9e3dcce5b67630320cd",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/stp/stayzilla/constants/AppConstants.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "93217"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- Documenting T:NAnt.DotNet.Tasks.LicenseTask-->
<head>
<meta http-equiv="Content-Language" content="en-ca" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../style.css" />
<title><license> Task</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="2" class="NavBar">
<tr>
<td class="NavBar-Cell">
<a href="http://nant.sourceforge.net">
<b>NAnt</b>
</a>
<img alt="->" src="../images/arrow.gif" />
<a href="../index.html">Help</a>
<img alt="->" src="../images/arrow.gif" />
<a href="../tasks/index.html">Task Reference</a>
<img alt="->" src="../images/arrow.gif" /> <license></td>
<td class="NavBar-Cell" align="right">
v0.92</td>
</tr>
</table>
<h1><license></h1>
<p> Generates a <code>.licence</code> file from a <code>.licx</code> file. </p>
<p> If no output file is specified, the default filename is the name of the target file with the extension <code>.licenses</code> appended. </p>
<h3>Parameters</h3>
<div class="table">
<table>
<tr>
<th>Attribute</th>
<th style="text-align: center;">Type</th>
<th>Description</th>
<th style="text-align: center;">Required</th>
</tr>
<tr>
<td valign="top" class="required">input</td>
<td style="text-align: center;">file</td>
<td> Input file to process. </td>
<td style="text-align: center;">True</td>
</tr>
<tr>
<td valign="top">licensetarget</td>
<td style="text-align: center;">string</td>
<td>
<i>Deprecated.</i> Specifies the executable for which the .licenses file is generated. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">output</td>
<td style="text-align: center;">file</td>
<td> Name of the license file to output. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">target</td>
<td style="text-align: center;">string</td>
<td> Specifies the executable for which the .licenses file is generated. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">failonerror</td>
<td style="text-align: center;">bool</td>
<td> Determines if task failure stops the build, or is just reported. The default is <b>true</b>. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">if</td>
<td style="text-align: center;">bool</td>
<td> If <b>true</b> then the task will be executed; otherwise, skipped. The default is <b>true</b>. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">timeout</td>
<td style="text-align: center;">int</td>
<td> The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">unless</td>
<td style="text-align: center;">bool</td>
<td> Opposite of <code>if</code>. If <b>false</b> then the task will be executed; otherwise, skipped. The default is <b>false</b>. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">verbose</td>
<td style="text-align: center;">bool</td>
<td> Determines whether the task should report detailed build log messages. The default is <b>false</b>. </td>
<td style="text-align: center;">False</td>
</tr>
</table>
</div>
<h3>Framework-configurable parameters</h3>
<div class="table">
<table>
<tr>
<th>Attribute</th>
<th style="text-align: center;">Type</th>
<th>Description</th>
<th style="text-align: center;">Required</th>
</tr>
<tr>
<td valign="top">exename</td>
<td style="text-align: center;">string</td>
<td> The name of the executable that should be used to launch the external program. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">hascommandlinecompiler</td>
<td style="text-align: center;">bool</td>
<td> Indicates whether the current target framework has a command line tool for compiling licenses files. The default is <b>true</b>. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">managed</td>
<td style="text-align: center;">
<a href="../enums/NAnt.Core.Types.ManagedExecution.html">ManagedExecution</a>
</td>
<td> Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">supportsassemblyreferences</td>
<td style="text-align: center;">bool</td>
<td> Indicates whether assembly references are supported by the current target framework. The default is <b>false</b>. </td>
<td style="text-align: center;">False</td>
</tr>
<tr>
<td valign="top">useruntimeengine</td>
<td style="text-align: center;">bool</td>
<td>
<i>Deprecated.</i> Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is <b>false</b>. </td>
<td style="text-align: center;">False</td>
</tr>
</table>
</div>
<h3>Nested Elements:</h3>
<!--Element-->
<h4>
<a id="assemblies">
</a>
<<a href="../types/assemblyfileset.html">assemblies</a>>
</h4>
<div class="nested-element"> Names of the references to scan for the licensed component. <p /></div>
<h4>
<a id="assemblies">
</a>
</<a href="../types/assemblyfileset.html">assemblies</a>>
</h4>
<h3>Examples</h3>
<ul class="examples">
<li>
<p> Generate the file <code>component.exe.licenses</code> file from <code>component.licx</code>. </p>
<pre class="code">
<license input="component.licx" licensetarget="component.exe" />
</pre>
</li>
</ul>
<h3>Requirements</h3>
<div style="margin-left: 20px;">
<b>Assembly:</b> NAnt.DotNetTasks (0.92.4543.0)
</div>
</body>
</html> | {
"content_hash": "1c271d7519f54134288cd7cda103e0de",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 194,
"avg_line_length": 43,
"alnum_prop": 0.5523956290277389,
"repo_name": "thomast74/spring-net-data-mongodb",
"id": "39cc412456d80e6a3e216ddd1988950786ac73b9",
"size": "7140",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tools/nant/doc/help/tasks/license.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "147635"
},
{
"name": "Shell",
"bytes": "4948"
},
{
"name": "XML",
"bytes": "2904336"
}
],
"symlink_target": ""
} |
package org.springframework.security.access.intercept.aspectj.aspect;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.annotation.SecuredAnnotationSecurityMetadataSource;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.ExpressionBasedAnnotationAttributeFactory;
import org.springframework.security.access.expression.method.ExpressionBasedPostInvocationAdvice;
import org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice;
import org.springframework.security.access.intercept.AfterInvocationProviderManager;
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PostInvocationAdviceProvider;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter;
import org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author Luke Taylor
* @since 3.0.3
*/
public class AnnotationSecurityAspectTests {
private AffirmativeBased adm;
private @Mock AuthenticationManager authman;
private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "",
"ROLE_A");
// private TestingAuthenticationToken bob = new TestingAuthenticationToken("bob", "",
// "ROLE_B");
private AspectJMethodSecurityInterceptor interceptor;
private SecuredImpl secured = new SecuredImpl();
private SecuredImplSubclass securedSub = new SecuredImplSubclass();
private PrePostSecured prePostSecured = new PrePostSecured();
@Before
public final void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
interceptor = new AspectJMethodSecurityInterceptor();
AccessDecisionVoter[] voters = new AccessDecisionVoter[] {
new RoleVoter(),
new PreInvocationAuthorizationAdviceVoter(
new ExpressionBasedPreInvocationAdvice()) };
adm = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>> asList(voters));
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
interceptor
.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource());
AnnotationSecurityAspect secAspect = AnnotationSecurityAspect.aspectOf();
secAspect.setSecurityInterceptor(interceptor);
}
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void securedInterfaceMethodAllowsAllAccess() throws Exception {
secured.securedMethod();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void securedClassMethodDeniesUnauthenticatedAccess() throws Exception {
secured.securedClassMethod();
}
@Test
public void securedClassMethodAllowsAccessToRoleA() throws Exception {
SecurityContextHolder.getContext().setAuthentication(anne);
secured.securedClassMethod();
}
@Test(expected = AccessDeniedException.class)
public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(anne);
try {
secured.publicCallsPrivate();
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
securedSub.publicCallsPrivate();
}
@Test(expected = AccessDeniedException.class)
public void protectedMethodIsIntercepted() throws Exception {
SecurityContextHolder.getContext().setAuthentication(anne);
secured.protectedMethod();
}
@Test
public void overriddenProtectedMethodIsNotIntercepted() throws Exception {
// AspectJ doesn't inherit annotations
securedSub.protectedMethod();
}
// SEC-1262
@Test(expected = AccessDeniedException.class)
public void denyAllPreAuthorizeDeniesAccess() throws Exception {
configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(anne);
prePostSecured.denyAllMethod();
}
@Test
public void postFilterIsApplied() throws Exception {
configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(anne);
List<String> objects = prePostSecured.postFilterMethod();
assertThat(objects).hasSize(2);
assertThat(objects.contains("apple")).isTrue();
assertThat(objects.contains("aubergine")).isTrue();
}
private void configureForElAnnotations() {
DefaultMethodSecurityExpressionHandler eh = new DefaultMethodSecurityExpressionHandler();
interceptor
.setSecurityMetadataSource(new PrePostAnnotationSecurityMetadataSource(
new ExpressionBasedAnnotationAttributeFactory(eh)));
interceptor.setAccessDecisionManager(adm);
AfterInvocationProviderManager aim = new AfterInvocationProviderManager();
aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(
new ExpressionBasedPostInvocationAdvice(eh))));
interceptor.setAfterInvocationManager(aim);
}
}
interface SecuredInterface {
@Secured("ROLE_X")
void securedMethod();
}
class SecuredImpl implements SecuredInterface {
// Not really secured because AspectJ doesn't inherit annotations from interfaces
public void securedMethod() {
}
@Secured("ROLE_A")
public void securedClassMethod() {
}
@Secured("ROLE_X")
private void privateMethod() {
}
@Secured("ROLE_X")
protected void protectedMethod() {
}
@Secured("ROLE_X")
public void publicCallsPrivate() {
privateMethod();
}
}
class SecuredImplSubclass extends SecuredImpl {
protected void protectedMethod() {
}
public void publicCallsPrivate() {
super.publicCallsPrivate();
}
}
class PrePostSecured {
@PreAuthorize("denyAll")
public void denyAllMethod() {
}
@PostFilter("filterObject.startsWith('a')")
public List<String> postFilterMethod() {
ArrayList<String> objects = new ArrayList<>();
objects.addAll(Arrays.asList(new String[] { "apple", "banana", "aubergine",
"orange" }));
return objects;
}
}
| {
"content_hash": "0166f522802326826e6d9b99a42a504b",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 103,
"avg_line_length": 34.185,
"alnum_prop": 0.809419335966067,
"repo_name": "wkorando/spring-security",
"id": "2098699f526758685904e5b69cb4296d3e3fb68e",
"size": "7457",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "2756"
},
{
"name": "FreeMarker",
"bytes": "2058"
},
{
"name": "Groovy",
"bytes": "671543"
},
{
"name": "HTML",
"bytes": "468"
},
{
"name": "Java",
"bytes": "5162503"
},
{
"name": "PLSQL",
"bytes": "3177"
},
{
"name": "Python",
"bytes": "129"
},
{
"name": "Shell",
"bytes": "234"
},
{
"name": "XSLT",
"bytes": "2344"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "218b2241df4a8ef0cc2e10d2cec2ec23",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "19fcb60125876a199d013a537f1606350c8b9b36",
"size": "175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Aspleniaceae/Diellia/Diellia laui/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright 2016 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.
import '//resources/cr_elements/cr_dialog/cr_dialog.m.js';
import '//resources/cr_elements/cr_button/cr_button.m.js';
import '//resources/cr_elements/cr_radio_button/cr_radio_button.m.js';
import '//resources/cr_elements/cr_radio_group/cr_radio_group.m.js';
import '//resources/polymer/v3_0/iron-selector/iron-selector.js';
import '../../settings_shared_css.js';
import {assert, assertNotReached} from '//resources/js/assert.m.js';
import {loadTimeData} from '//resources/js/load_time_data.m.js';
import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {AboutPageBrowserProxy, AboutPageBrowserProxyImpl, AboutPageUpdateInfo, BrowserChannel, browserChannelToI18nId, ChannelInfo, isTargetChannelMoreStable, RegulatoryInfo, TPMFirmwareUpdateStatusChangedEvent, UpdateStatus, UpdateStatusChangedEvent, VersionInfo} from './about_page_browser_proxy.js';
/**
*/
const WarningMessage = {
NONE: -1,
ENTERPRISE_MANAGED: 0,
POWERWASH: 1,
UNSTABLE: 2,
};
/**
* @fileoverview 'settings-channel-switcher-dialog' is a component allowing the
* user to switch between release channels (dev, beta, stable). A
* |target-channel-changed| event is fired if the user does select a different
* release channel to notify parents of this dialog.
*/
Polymer({
_template: html`{__html_template__}`,
is: 'settings-channel-switcher-dialog',
properties: {
/** @private */
browserChannelEnum_: {
type: Object,
value: BrowserChannel,
},
/** @private {!BrowserChannel} */
currentChannel_: String,
/** @private {!BrowserChannel} */
targetChannel_: String,
/**
* Controls which of the two action buttons is visible.
* @private {?{changeChannel: boolean, changeChannelAndPowerwash: boolean}}
*/
shouldShowButtons_: {
type: Object,
value: null,
},
},
/** @private {?AboutPageBrowserProxy} */
browserProxy_: null,
/** @override */
ready() {
this.browserProxy_ = AboutPageBrowserProxyImpl.getInstance();
this.browserProxy_.getChannelInfo().then(info => {
this.currentChannel_ = info.currentChannel;
this.targetChannel_ = info.targetChannel;
// Pre-populate radio group with target channel.
const radioGroup = this.$$('cr-radio-group');
radioGroup.selected = this.targetChannel_;
radioGroup.focus();
});
},
/** @override */
attached() {
this.$.dialog.showModal();
},
/** @private */
onCancelTap_() {
this.$.dialog.close();
},
/** @private */
onChangeChannelTap_() {
const selectedChannel = this.$$('cr-radio-group').selected;
this.browserProxy_.setChannel(selectedChannel, false);
this.$.dialog.close();
this.fire('target-channel-changed', selectedChannel);
},
/** @private */
onChangeChannelAndPowerwashTap_() {
const selectedChannel = this.$$('cr-radio-group').selected;
this.browserProxy_.setChannel(selectedChannel, true);
this.$.dialog.close();
this.fire('target-channel-changed', selectedChannel);
},
/**
* @param {boolean} changeChannel Whether the changeChannel button should be
* visible.
* @param {boolean} changeChannelAndPowerwash Whether the
* changeChannelAndPowerwash button should be visible.
* @private
*/
updateButtons_(changeChannel, changeChannelAndPowerwash) {
if (changeChannel || changeChannelAndPowerwash) {
// Ensure that at most one button is visible at any given time.
assert(changeChannel !== changeChannelAndPowerwash);
}
this.shouldShowButtons_ = {
changeChannel: changeChannel,
changeChannelAndPowerwash: changeChannelAndPowerwash,
};
},
/** @private */
onChannelSelectionChanged_() {
const selectedChannel = this.$$('cr-radio-group').selected;
// Selected channel is the same as the target channel so only show 'cancel'.
if (selectedChannel === this.targetChannel_) {
this.shouldShowButtons_ = null;
this.$.warningSelector.select(WarningMessage.NONE);
return;
}
// Selected channel is the same as the current channel, allow the user to
// change without warnings.
if (selectedChannel === this.currentChannel_) {
this.updateButtons_(true, false);
this.$.warningSelector.select(WarningMessage.NONE);
return;
}
if (isTargetChannelMoreStable(this.currentChannel_, selectedChannel)) {
// More stable channel selected. For non managed devices, notify the user
// about powerwash.
if (loadTimeData.getBoolean('aboutEnterpriseManaged')) {
this.$.warningSelector.select(WarningMessage.ENTERPRISE_MANAGED);
this.updateButtons_(true, false);
} else {
this.$.warningSelector.select(WarningMessage.POWERWASH);
this.updateButtons_(false, true);
}
} else {
if (selectedChannel === BrowserChannel.DEV) {
// Dev channel selected, warn the user.
this.$.warningSelector.select(WarningMessage.UNSTABLE);
} else {
this.$.warningSelector.select(WarningMessage.NONE);
}
this.updateButtons_(true, false);
}
},
/**
* @param {string} format
* @param {string} replacement
* @return {string}
* @private
*/
substituteString_(format, replacement) {
return loadTimeData.substituteString(format, replacement);
},
});
| {
"content_hash": "e9109f6004979a67b2fab2d83eaf2e88",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 302,
"avg_line_length": 32.62573099415204,
"alnum_prop": 0.682021867718229,
"repo_name": "scheib/chromium",
"id": "2bcc09b7558b87424442f2863d96bfdc8ea3fcd0",
"size": "5579",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "chrome/browser/resources/settings/chromeos/os_about_page/channel_switcher_dialog.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
local Snowflake = require('../Snowflake')
local Role = require('./Role')
local Emoji = require('./Emoji')
local Member = require('./Member')
local Webhook = require('./Webhook')
local GuildTextChannel = require('./channels/GuildTextChannel')
local GuildVoiceChannel = require('./channels/GuildVoiceChannel')
local Invite = require('../Invite')
local Cache = require('../../utils/Cache')
local hash = table.hash
local format = string.format
local floor, clamp = math.floor, math.clamp
local wrap, yield = coroutine.wrap, coroutine.yield
local Guild, property, method, cache = class('Guild', Snowflake)
Guild.__description = "Represents a Discord guild (also known as a server)."
function Guild:__init(data, parent)
Snowflake.__init(self, data, parent)
self._roles = Cache({}, Role, 'id', self)
self._emojis = Cache({}, Emoji, 'id', self)
self._members = Cache({}, Member, 'id', self)
self._text_channels = Cache({}, GuildTextChannel, 'id', self)
self._voice_channels = Cache({}, GuildVoiceChannel, 'id', self)
if data.unavailable then
self._unavailable = true
else
self:_makeAvailable(data)
end
end
function Guild:__tostring()
return format('%s: %s', self.__name, self._name)
end
function Guild:_makeAvailable(data)
self:_update(data)
self._roles:merge(data.roles)
self._emojis:merge(data.emojis)
self._members:merge(data.members)
hash(data.voice_states, 'user_id')
self._voice_states = data.voice_states
if data.presences then
self:_loadMemberPresences(data.presences)
end
if data.channels then
for _, channel_data in ipairs(data.channels) do
local type = channel_data.type
if type == 'text' then
self._text_channels:new(channel_data)
elseif type == 'voice' then
self._voice_channels:new(channel_data)
end
end
end
if self._large and self._parent._options.fetchMembers then
self:_requestMembers()
end
self._vip = next(data.features) and true or false
-- TODO: parse features
end
function Guild:_requestMembers()
local socket = self._parent._sockets[self.shardId]
if socket._loading then
socket._loading.chunks[self._id] = true
end
socket:requestGuildMembers(self._id)
end
function Guild:_loadMemberPresences(data)
for _, presence in ipairs(data) do
local member = self._members:get(presence.user.id)
member:_createPresence(presence)
end
end
function Guild:_updateMemberPresence(data)
local member = self._members:get(data.user.id)
if member then
member:_updatePresence(data)
else
member = self._members:new(data)
member:_createPresence(data)
end
return member
end
local function setName(self, name)
local success, data = self._parent._api:modifyGuild(self._id, {name = name})
if success then self._name = data.name end
return success
end
local function setRegion(self, region)
local success, data = self._parent._api:modifyGuild(self._id, {region = region})
if success then self._region = data.region end
return success
end
local function setIcon(self, icon)
local success, data = self._parent._api:modifyGuild(self._id, {icon = icon})
if success then self._icon = data.icon end
return success
end
local function setOwner(self, member)
local success, data = self._parent._api:modifyGuild(self._id, {owner_id = member._id})
if success then self._owner_id = data.owner_id end
return success
end
local function setAfkTimeout(self, timeout)
local success, data = self._parent._api:modifyGuild(self._id, {afk_timeout = timeout})
if success then self._afk_timeout = data.afk_timeout end
return success
end
local function setAfkChannel(self, channel)
local success, data = self._parent._api:modifyGuild(self._id, {afk_channel_id = channel and channel._id or self._id})
if success then self._afk_channel_id = data._afk_channel_id end
return success
end
local function getIconUrl(self)
if not self._icon then return nil end
return format('https://cdn.discordapp.com/icons/%s/%s.png', self._id, self._icon)
end
local function getShardId(self)
return floor(self._id / 2^22) % self._parent._shard_count
end
local function getMe(self)
return self._members:get(self._parent._user._id)
end
local function getOwner(self)
return self._members:get(self._owner_id)
end
local function getAfkChannel(self)
return self._voice_channels:get(self._afk_channel_id)
end
local function getDefaultRole(self)
return self._roles:get(self._id)
end
local function getDefaultChannel(self)
return self._text_channels:get(self._id)
end
local function listVoiceRegions(self)
local success, data = self._parent._api:getGuildVoiceRegions(self._id)
return success and data or nil
end
local function leave(self)
return (self._parent._api:leaveGuild(self._id))
end
local function delete(self)
return (self._parent._api:deleteGuild(self._id))
end
local function getBannedUsers(self)
local success, data = self._parent._api:getGuildBans(self._id)
if not success then return function() end end
local users = self._parent._users
local i = 1
return function()
local v = data[i]
if v then
i = i + 1
return users:get(v.user.id) or users:new(v.user)
end
end
end
local function getInvites(self)
local success, data = self._parent._api:getGuildInvites(self._id)
local parent = self._parent
if not success then return function() end end
local i = 1
return function()
local v = data[i]
if v then
i = i + 1
return Invite(v, parent)
end
end
end
local function getWebhooks(self)
local success, data = self._parent._api:getGuildWebhooks(self._id)
local parent = self._parent
if not success then return function() end end
local i = 1
return function()
local v = data[i]
if v then
i = i + 1
return Webhook(v, parent)
end
end
end
local function banUser(self, user, days)
local query = days and {['delete-message-days'] = clamp(days, 0, 7)} or nil
return (self._parent._api:createGuildBan(self._id, user._id, nil, query))
end
local function unbanUser(self, user)
return (self._parent._api:removeGuildBan(self._id, user._id))
end
local function kickUser(self, user)
return (self._parent._api:removeGuildMember(self._id, user._id))
end
local function getPruneCount(self, days)
local query = days and {days = clamp(days, 1, 30)} or nil
local success, data = self._parent._api:getGuildPruneCount(self._id, query)
return success and data.pruned or nil
end
local function pruneMembers(self, days)
local query = days and {days = clamp(days, 1, 30)} or nil
local success, data = self._parent._api:getGuildPruneCount(self._id, query)
return success and data.pruned or nil
end
local function createTextChannel(self, name)
local success, data = self._parent._api:createGuildChannel(self._id, {name = name, type = 'text'})
return success and self._text_channels:new(data) or nil
end
local function createVoiceChannel(self, name)
local success, data = self._parent._api:createGuildChannel(self._id, {name = name, type = 'voice'})
return success and self._voice_channels:new(data) or nil
end
local function createRole(self, name)
local success, data = self._parent._api:createGuildRole(self._id, {name = name})
return success and self._roles:new(data) or nil
end
-- channels --
local function getChannelCount(self)
return self._text_channels._count + self._voice_channels._count
end
local function getChannels(self, key, value)
return wrap(function()
for channel in self._text_channels:getAll(key, value) do
yield(channel)
end
for channel in self._voice_channels:getAll(key, value) do
yield(channel)
end
end)
end
local function getChannel(self, key, value)
return self._text_channels:get(key, value) or self._voice_channels:get(key, value)
end
local function findChannel(self, predicate)
return self._text_channels:find(predicate) or self._voice_channels:find(predicate)
end
local function findChannels(self, predicate)
return wrap(function()
for channel in self._text_channels:findAll(predicate) do
yield(channel)
end
for channel in self._voice_channels:findAll(predicate) do
yield(channel)
end
end)
end
-- text channels --
local function getTextChannelCount(self)
return self._text_channels._count
end
local function getTextChannels(self, key, value)
return self._text_channels:getAll(key, value)
end
local function getTextChannel(self, key, value)
return self._text_channels:get(key, value)
end
local function findTextChannel(self, predicate)
return self._text_channels:find(predicate)
end
local function findTextChannels(self, predicate)
return self._text_channels:findAll(predicate)
end
-- voice channels --
local function getVoiceChannelCount(self)
return self._voice_channels._count
end
local function getVoiceChannels(self, key, value)
return self._voice_channels:getAll(key, value)
end
local function getVoiceChannel(self, key, value)
return self._voice_channels:get(key, value)
end
local function findVoiceChannel(self, predicate)
return self._voice_channels:find(predicate)
end
local function findVoiceChannels(self, predicate)
return self._voice_channels:findAll(predicate)
end
-- roles --
local function getRoleCount(self)
return self._roles._count
end
local function getRoles(self, key, value)
return self._roles:getAll(key, value)
end
local function getRole(self, key, value)
return self._roles:get(key, value)
end
local function findRole(self, predicate)
return self._roles:find(predicate)
end
local function findRoles(self, predicate)
return self._roles:findAll(predicate)
end
-- emojis --
local function getEmojiCount(self)
return self._emojis._count
end
local function getEmojis(self, key, value)
return self._emojis:getAll(key, value)
end
local function getEmoji(self, key, value)
return self._emojis:get(key, value)
end
local function findEmoji(self, predicate)
return self._emojis:find(predicate)
end
local function findEmojis(self, predicate)
return self._emojis:findAll(predicate)
end
-- members --
local function getMemberCount(self)
return self._members._count
end
local function getMembers(self, key, value)
return self._members:getAll(key, value)
end
local function getMember(self, key, value)
local member = self._members:get(key, value)
if member or value then return member end
local success, data = self._parent._api:getGuildMember(self._id, key)
return success and self._members:new(data) or nil
end
local function findMember(self, predicate)
return self._members:find(predicate)
end
local function findMembers(self, predicate)
return self._members:findAll(predicate)
end
-- messages --
local function getMessageCount(self)
local n = 0
for channel in self._text_channels:iter() do
n = n + channel._messages._count
end
return n
end
local function getMessages(self, key, value)
return wrap(function()
for channel in self._text_channels:iter() do
for message in channel._messages:getAll(key, value) do
yield(message)
end
end
end)
end
local function getMessage(self, key, value)
for channel in self._text_channels:iter() do
local message = channel._messages:get(key, value)
if message then return message end
end
return nil
end
local function findMessage(self, predicate)
for channel in self._text_channels:iter() do
local message = channel._messages:find(predicate)
if message then return message end
end
return nil
end
local function findMessages(self, predicate)
return wrap(function()
for channel in self._text_channels:iter() do
for message in channel._messages:findAll(predicate) do
yield(message)
end
end
end)
end
property('vip', '_vip', nil, 'boolean', "Whether the guild is featured by Discord")
property('name', '_name', setName, 'string', "Name of the guild")
property('icon', '_icon', setIcon, 'string?', "Hash representing the guild's icon")
property('iconUrl', getIconUrl, nil, 'string?', "URL that points to the guild's icon")
property('large', '_large', nil, 'boolean', "Whether the guild has a lot of members")
property('splash', '_splash', nil, 'string?', "Hash representing the guild's custom splash")
property('region', '_region', setRegion, 'string', "String representing the guild's voice region")
property('mfaLevel', '_mfa_level', nil, 'number', "Guild required MFA level")
property('joinedAt', '_joined_at', nil, 'string', "Date and time at which the client joined the guild")
property('afkTimeout', '_afk_timeout', setAfkTimeout, 'number', "AFK timeout in seconds")
property('unavailable', '_unavailable', nil, 'boolean', "Whether the guild data is unavailable")
property('totalMemberCount', '_member_count', nil, 'number', "How many members exist in the guild (can be different from cached memberCount)")
property('verificationLevel', '_verification_level', nil, 'number', "Guild verification level")
property('notificationsSetting', '_default_message_notifications', nil, 'number', "Default message notifications setting for members")
property('shardId', getShardId, nil, 'number', "The ID of the shard on which this guild's events will be transmitted")
property('me', getMe, nil, 'Member', "The client's member object for this guild")
property('owner', getOwner, setOwner, 'Member', "The member that owns the server")
property('afkChannel', getAfkChannel, setAfkChannel, 'GuildVoiceChannel', "Voice channel to where members are moved when they are AFK")
property('defaultRole', getDefaultRole, nil, 'Role', "The guild's '@everyone' role")
property('defaultChannel', getDefaultChannel, nil, 'GuildTextChannel', "The guild's default text channel")
property('bannedUsers', getBannedUsers, nil, 'function', "Iterator for the banned users in the guild")
property('invites', getInvites, nil, 'function', "Iterator for the guild's invites (not cached)")
property('webhooks', getWebhooks, nil, 'function', "Iterator for the guild's webhooks (not cached)")
property('connection', '_connection', nil, 'VoiceConnection?', "The handle for this guild's voice connection, if one exists")
method('leave', leave, nil, "Leaves the guild.", 'HTTP')
method('delete', delete, nil, "Deletes the guild.", 'HTTP')
method('listVoiceRegions', listVoiceRegions, nil, "Returns a table of guild voice regions.", 'HTTP')
method('banUser', banUser, 'user[, days]', "Bans a user from the guild and optionally deletes their messages from 1-7 days.", 'HTTP')
method('unbanUser', unbanUser, 'user', "Unbans a user from the guild.", 'HTTP')
method('kickUser', kickUser, 'user', "Kicks a user from the guild", 'HTTP')
method('getPruneCount', getPruneCount, '[days]', "Returns how many members would be removed if 1-30 day prune were performed (default: 1 day).", 'HTTP')
method('pruneMembers', pruneMembers, '[days]', "Removes members who have not been seen in 1-30 days (default: 1 day). Returns the number of pruned members.", 'HTTP')
method('createTextChannel', createTextChannel, 'name', "Creates a new text channel in the guild.", 'HTTP')
method('createVoiceChannel', createVoiceChannel, 'name', "Creates a new voice channel in the guild.", 'HTTP')
method('createRole', createRole, 'name', "Creates a new role in the guild.", 'HTTP')
cache('Channel', getChannelCount, getChannel, getChannels, findChannel, findChannels)
cache('TextChannel', getTextChannelCount, getTextChannel, getTextChannels, findTextChannel, findTextChannels)
cache('VoiceChannel', getVoiceChannelCount, getVoiceChannel, getVoiceChannels, findVoiceChannel, findVoiceChannels)
cache('Role', getRoleCount, getRole, getRoles, findRole, findRoles)
cache('Emoji', getEmojiCount, getEmoji, getEmojis, findEmoji, findEmojis)
cache('Member', getMemberCount, getMember, getMembers, findMember, findMembers)
cache('Message', getMessageCount, getMessage, getMessages, findMessage, findMessages)
return Guild
| {
"content_hash": "d3d8288f560932d059a1446554daf167",
"timestamp": "",
"source": "github",
"line_count": 499,
"max_line_length": 165,
"avg_line_length": 31.26452905811623,
"alnum_prop": 0.7430292929940389,
"repo_name": "Chronomly6/SmoreBot",
"id": "1d1bc8c1e19cf526ed0ed8ac0272f47a6a5af3af",
"size": "15601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "discordia/discordia/containers/snowflakes/Guild.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "69"
},
{
"name": "Lua",
"bytes": "256198"
}
],
"symlink_target": ""
} |
/**
* Initializes the list of Equal Nest <?php echo $pluralRefTableName ?> PKs.
*
* This will query the database for Equal Nest <?php echo $pluralRefTableName ?> relations to this <?php echo $objectClassname ?> object.
* It will set the list to an empty array if the object is newly created.
*
* @param PropelPDO $con
*/
protected function initList<?php echo $pluralRefTableName ?>PKs(PropelPDO $con = null)
{
if ($con === null) {
$con = Propel::getConnection(<?php echo $peerClassname ?>::DATABASE_NAME, Propel::CONNECTION_READ);
}
if (null === $this-><?php echo $varListRelatedPKs ?>) {
if ($this->isNew()) {
$this-><?php echo $varListRelatedPKs ?> = array();
} else {
$sql = "
SELECT DISTINCT <?php echo $tablePk . "\n" ?>
FROM <?php echo $tableName . "\n" ?>
INNER JOIN <?php echo $middleTableName ?> ON
<?php echo $tablePk ?> = <?php echo $refColumn1 . "\n" ?>
OR
<?php echo $tablePk ?> = <?php echo $refColumn2 . "\n" ?>
WHERE
<?php echo $tablePk ?> IN (
SELECT <?php echo $refColumn1 . "\n" ?>
FROM <?php echo $middleTableName . "\n" ?>
WHERE <?php echo $refColumn2 ?> = ?
)
OR
<?php echo $tablePk ?> IN (
SELECT <?php echo $refColumn2 . "\n" ?>
FROM <?php echo $middleTableName . "\n" ?>
WHERE <?php echo $refColumn1 ?> = ?
)";
$stmt = $con->prepare($sql);
$stmt->bindValue(1, $this->getPrimaryKey(), PDO::PARAM_INT);
$stmt->bindValue(2, $this->getPrimaryKey(), PDO::PARAM_INT);
$stmt->execute();
$this-><?php echo $varListRelatedPKs ?> = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
}
}
| {
"content_hash": "d2089d228a5071396e8d8e72b0af52df",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 137,
"avg_line_length": 34.520833333333336,
"alnum_prop": 0.5853952926976463,
"repo_name": "mjahn/EqualNestBehavior",
"id": "b7fb462269f7459dc770ca09f702bcedc33f5cca",
"size": "1657",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/templates/parent/addInitListRelatedPKs.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "98232"
}
],
"symlink_target": ""
} |
/* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* <p/>
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.rzo.yajsw.os;
import java.io.FileDescriptor;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class AbstractProcess.
*/
public abstract class AbstractProcess implements Process
{
/** The _cmd. */
protected String _cmd;
protected String[] _arrCmd;
/** The _working dir. */
protected String _workingDir;
/** The _priority. */
protected int _priority = PRIORITY_UNDEFINED;
/** The _visible. */
protected boolean _visible = true;
/** The _pid. */
volatile protected int _pid = -1;
/** The _exit code. */
volatile protected int _exitCode = -1;
/** The _title. */
protected String _title = "";
/** The _cpu affinity. */
protected int _cpuAffinity = AFFINITY_UNDEFINED;
/** The _pipe streams. */
protected boolean _pipeStreams = false;
/** The _redirect error stream. */
protected boolean _redirectErrorStream = false;
/** The _input stream. */
protected InputStream _inputStream;
/** The _output stream. */
protected OutputStream _outputStream;
/** The _error stream. */
protected InputStream _errorStream;
/** The in_fd. */
protected final FileDescriptor in_fd = new FileDescriptor();
/** The out_fd. */
protected final FileDescriptor out_fd = new FileDescriptor();
/** The err_fd. */
protected final FileDescriptor err_fd = new FileDescriptor();
/** The _tee name. */
protected String _teeName;
/** The _tmp path. */
protected String _tmpPath;
protected String _user;
protected String _password;
protected Logger _logger;
protected List<String[]> _environment = new ArrayList<String[]>();
protected boolean _debug = false;
protected boolean _minimized = false;
protected boolean _logonActiveSession = false;
protected String _desktop = null;
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getCommand()
*/
public String getCommand()
{
return _cmd;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setCommand(java.lang.String)
*/
public void setCommand(String cmd)
{
_cmd = cmd;
}
/**
* Sets the command.
*
* @param cmds
* the new command
*/
public void setCommand(String[] cmds)
{
_arrCmd = cmds;
_cmd = null;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getEnv()
*/
public List<String[]> getEnvironment()
{
return _environment;
}
public Map<String, String> getEnvironmentAsMap()
{
Map result = new HashMap();
for (String[] entry : _environment)
result.put(entry[0], entry[1]);
return result;
}
/**
* Sets the env.
*
* @param env
* the new env
*/
public void setEnvironment(List<String[]> environment)
{
if (environment == null)
environment = new ArrayList<String[]>();
_environment = environment;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getExitCode()
*/
public int getExitCode()
{
return _exitCode;
}
/**
* Sets the exit code.
*
* @param exitCode
* the new exit code
*/
protected void setExitCode(int exitCode)
{
_exitCode = exitCode;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getPid()
*/
public int getPid()
{
return _pid;
}
/**
* Sets the pid.
*
* @param pid
* the new pid
*/
public void setPid(int pid)
{
_pid = pid;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getPriority()
*/
public int getPriority()
{
return _priority;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setPriority(int)
*/
public void setPriority(int priority)
{
_priority = priority;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#isVisible()
*/
public boolean isVisible()
{
return _visible;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setVisible(boolean)
*/
public void setVisible(boolean visible)
{
_visible = visible;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getWorkingDir()
*/
public String getWorkingDir()
{
return _workingDir;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setWorkingDir(java.lang.String)
*/
public void setWorkingDir(String workingDir)
{
_workingDir = workingDir;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle()
{
return _title;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setTitle(java.lang.String)
*/
public void setTitle(String title)
{
_title = title;
}
/**
* Gets the cpu affinity.
*
* @return the cpu affinity
*/
public int getCpuAffinity()
{
return _cpuAffinity;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setCpuAffinity(int)
*/
public void setCpuAffinity(int cpuAffinity)
{
_cpuAffinity = cpuAffinity;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#setPipeStreams(boolean, boolean)
*/
public void setPipeStreams(boolean pipeStreams, boolean redirectErrorStream)
{
_pipeStreams = pipeStreams;
_redirectErrorStream = redirectErrorStream;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getInputStream()
*/
public InputStream getInputStream()
{
return _inputStream;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getErrorStream()
*/
public InputStream getErrorStream()
{
return _errorStream;
}
/*
* (non-Javadoc)
*
* @see org.rzo.yajsw.os.Process#getOutputStream()
*/
public OutputStream getOutputStream()
{
return _outputStream;
}
/**
* Gets the tee name.
*
* @return the tee name
*/
String getTeeName()
{
return _teeName;
}
/**
* Sets the tee name.
*
* @param teeName
* the new tee name
*/
public void setTeeName(String teeName)
{
_teeName = teeName;
}
/**
* Sets the tmp path.
*
* @param tmpPath
* the new tmp path
*/
public void setTmpPath(String tmpPath)
{
_tmpPath = tmpPath;
}
public String getUser()
{
return _user;
}
public void setUser(String user)
{
_user = user;
}
public String getPassword()
{
return _password;
}
public void setPassword(String password)
{
_password = password;
}
public void setLogger(Logger logger)
{
_logger = logger;
}
protected void log(String msg)
{
if (_logger != null)
_logger.info(msg);
else
System.out.println(msg);
}
protected void throwing(String cls, String method, Throwable ex)
{
if (_logger != null)
_logger.throwing(cls, method, ex);
else
ex.printStackTrace();
}
public void setDebug(boolean debug)
{
_debug = debug;
}
public boolean isMinimized()
{
return _minimized;
}
public void setMinimized(boolean minimized)
{
_minimized = minimized;
}
public boolean isLogonActiveSession()
{
return _logonActiveSession;
}
public void setLogonActiveSession(boolean logonActiveSession)
{
_logonActiveSession = logonActiveSession;
}
public void setDesktop(String desktop)
{
_desktop = desktop;
}
public boolean isDebug()
{
return _debug;
}
}
| {
"content_hash": "a76a4c4cfc5cf7f2d178b4f827537c44",
"timestamp": "",
"source": "github",
"line_count": 450,
"max_line_length": 77,
"avg_line_length": 18.29111111111111,
"alnum_prop": 0.6016279917385494,
"repo_name": "ColFusion/PentahoKettle",
"id": "fe4e651454be779096c511e21ccbabf1dd077a9c",
"size": "8231",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "CarteService/default/src/main/java/org/rzo/yajsw/os/AbstractProcess.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "21071"
},
{
"name": "Batchfile",
"bytes": "21366"
},
{
"name": "C",
"bytes": "7006"
},
{
"name": "CSS",
"bytes": "1952277"
},
{
"name": "Groff",
"bytes": "684"
},
{
"name": "Groovy",
"bytes": "33843"
},
{
"name": "HTML",
"bytes": "197173221"
},
{
"name": "Java",
"bytes": "3685348"
},
{
"name": "JavaScript",
"bytes": "31972698"
},
{
"name": "PHP",
"bytes": "224688"
},
{
"name": "Perl",
"bytes": "6881"
},
{
"name": "PigLatin",
"bytes": "7496"
},
{
"name": "Python",
"bytes": "109487"
},
{
"name": "Shell",
"bytes": "43881"
},
{
"name": "Smarty",
"bytes": "2952"
},
{
"name": "XQuery",
"bytes": "798"
},
{
"name": "XSLT",
"bytes": "562453"
}
],
"symlink_target": ""
} |
> Provides additional truncation functions in PHP.
[](https://github.com/Dreamseer/php-shorten/actions/workflows/test.yml)
[](https://coveralls.io/github/Dreamseer/php-shorten?branch=main)



[](https://github.com/Dreamseer/php-shorten/blob/main/LICENSE.md)
## Installation
I recommend using [Composer](https://getcomposer.org/) for installing and using Shorten:
```bash
composer require marcgoertz/shorten
```
Of course you can also just require it in your scripts directly.
## Usage
```php
<?php
use Marcgoertz\Shorten\Shorten;
$shorten = new Shorten();
print $shorten->truncateMarkup('<a href="https://example.com/">Go to example site</a>', 10);
?>
```
Output:
```html
<a href="https://example.com/">Go to exam</a>…
```
## Functions
```php
truncateMarkup(
string $markup,
int $length = 400,
string $appendix = '…',
bool $appendixInside = false,
bool $wordsafe = false
): string
```
* String `$markup`: Text containing markup
* Integer `$length`: Maximum length of truncated text (default: `400`)
* String `$appendix`: Text added after truncated text (default: `'…'`)
* Boolean `$appendixInside`: Add appendix to last content in tags, increases `$length` by 1 (default: `false`)
* Boolean `$wordsafe`: Wordsafe truncation (default: `false`)
* String `$delimiter`: Delimiter for wordsafe truncation (default: `' '`)
## License
MIT © [Marc Görtz](https://marcgoertz.de/)
| {
"content_hash": "77b1cc3f3f5d9eda1d8feab4704a45d9",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 162,
"avg_line_length": 32.389830508474574,
"alnum_prop": 0.7247514390371533,
"repo_name": "Dreamseer/php-shorten",
"id": "05c73711c75ceef4493a88ddfad9173ea2c3dba4",
"size": "1930",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "9421"
}
],
"symlink_target": ""
} |
'use strict'
const ghpages = require('gh-pages');
const path = require('path');
ghpages.publish(path.join(__dirname, '../..', 'dist'), {
branch: 'master',
message: 'Deploy current dev branch to GitHub Pages'
}, console.info('Deploying to `master` branch went OK.')); | {
"content_hash": "9eb5c08add97ad40086d3ec64d1e5d99",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 58,
"avg_line_length": 30.22222222222222,
"alnum_prop": 0.6691176470588235,
"repo_name": "xablauger-studios/blau-site",
"id": "05c27e33505e1455b0b8c4f627943dc06182345f",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "tasks/deploy/gh-pages.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5431"
},
{
"name": "HTML",
"bytes": "11952"
},
{
"name": "JavaScript",
"bytes": "6160"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ModuleInfo
/// </summary>
[Serializable]
public class ModuleInfo
{
private Int32 _moduleid;
private string _name;
private string _packagetype;
private string _friendlyName;
private string _description;
private string _version;
private string _businesscontrollerclass;
private string _foldername;
private string _modulename;
private string _compatibleversions;
private string _ManifestFile = string.Empty;
private string _tempFolderPath = string.Empty;
private string _installedFolderPath = string.Empty;
private string _owner = string.Empty;
private string _organization = string.Empty;
private string _url = string.Empty;
private string _email = string.Empty;
private string _releaseNotes = string.Empty;
private string _license = string.Empty;
public int ModuleDefID { get; set; }
public bool IsPortable { get; set; }
public bool IsSearchable { get; set; }
public bool IsUpgradable { get; set; }
public string PackageName { get; set; }
public string PackageDescription { get; set; }
public int PortalID { get; set; }
public string Username { get; set; }
public int ModuleDefPermissionID { get; set; }
public int PortalModulePermissionID { get; set; }
public List<ModuleInfo> ChildModules { get; set; }
private bool _isPremium;
private int _supportedFeatures;
private string _dependencies = string.Empty;
private string _permissions = string.Empty;
public string dependencies
{
get { return _dependencies; }
set { _dependencies = value; }
}
public string permissions
{
get { return _permissions; }
set { _permissions = value; }
}
public int supportedFeatures
{
get { return _supportedFeatures; }
set { _supportedFeatures = value; }
}
public bool isPremium
{
get { return _isPremium; }
set { _isPremium = value; }
}
public string ManifestFile
{
get { return _ManifestFile; }
set { _ManifestFile = value; }
}
public string TempFolderPath
{
get { return _tempFolderPath; }
set { _tempFolderPath = value; }
}
public string InstalledFolderPath
{
get { return _installedFolderPath; }
set { _installedFolderPath = value; }
}
public Int32 ModuleID
{
get { return _moduleid; }
set { _moduleid = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string FriendlyName
{
get { return _friendlyName; }
set { _friendlyName = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public string Version
{
get { return _version; }
set { _version = value; }
}
public string BusinessControllerClass
{
get { return _businesscontrollerclass; }
set { _businesscontrollerclass = value; }
}
public string FolderName
{
get { return _foldername; }
set { _foldername = value; }
}
public string ModuleName
{
get { return _modulename; }
set { _modulename = value; }
}
public string CompatibleVersions
{
get { return _compatibleversions; }
set { _compatibleversions = value; }
}
public string PackageType
{
get { return _packagetype; }
set { _packagetype = value; }
}
public string Owner
{
get { return _owner; }
set { _owner = value; }
}
public string Organization
{
get { return _organization; }
set { _organization = value; }
}
public string URL
{
get { return _url; }
set { _url = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string ReleaseNotes
{
get { return _releaseNotes; }
set { _releaseNotes = value; }
}
public string License
{
get { return _license; }
set { _license = value; }
}
public ModuleInfo()
{
ChildModules = new List<ModuleInfo>();
//
// TODO: Add constructor logic here
//
}
}
| {
"content_hash": "621b354b50ec819e1391c769fb52122f",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 55,
"avg_line_length": 24.135135135135137,
"alnum_prop": 0.5905935050391937,
"repo_name": "SageFrame/SageFrame",
"id": "7cf66420b5071b5aeb689d9d8f6ac47dd8d45da1",
"size": "5571",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SageFrame.Core/Services/Installer/ModuleInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "1554707"
},
{
"name": "ApacheConf",
"bytes": "768"
},
{
"name": "C#",
"bytes": "4514389"
},
{
"name": "CSS",
"bytes": "805481"
},
{
"name": "ColdFusion",
"bytes": "7712"
},
{
"name": "HTML",
"bytes": "466859"
},
{
"name": "JavaScript",
"bytes": "4646118"
},
{
"name": "PHP",
"bytes": "5655"
},
{
"name": "Perl",
"bytes": "4746"
}
],
"symlink_target": ""
} |
@interface LJNewAddressViewController ()
//保存按钮
@property (nonatomic,strong) UIButton *saveBtn;
@property (nonatomic,strong) UITextField *nameField;
@property (nonatomic,strong) UITextField *phoneField;
@property (nonatomic,strong) UITextField *postNum;
@property (nonatomic,strong) UITextField *detailField;
@property (nonatomic,strong) UITableViewCell *provinceCell;
@end
@implementation LJNewAddressViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = YES;
self.tableView.lj_y = 13;
self.tableView.lj_height = spaceEdgeH(300);
self.tableView.delegate =self;
self.tableView.dataSource = self;
self.tableView.bounces = NO; //去掉弹性效果
[self.view addSubview:self.tableView];
[self addSaveBtn];
//重写返回键
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
[backBtn sizeToFit];
[backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}
- (void)loadData {
NSArray *data = @[@"李四",@"15518703027",@"上海市宝山区罗泾镇",@"123456",@"陈川新村180",];
self.nameField.text = data[0];
self.phoneField.text = data[1];
self.provinceCell.detailTextLabel.text = data[2];
self.postNum.text = data[3];
self.detailField.text = data[4];
}
#pragma mark --代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return spaceEdgeH(44);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* cellId = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
}
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 160, 0, 150, spaceEdgeH(35))];
textField.lj_centerY = cell.lj_height / 2;
textField.textAlignment = NSTextAlignmentRight;
textField.textColor = LJFontColor4c;
[textField setFont:LJFontSize16];
textField.tag = indexPath.row + 100;
textField.delegate =self;
[textField addTarget:self action:@selector(edingChange) forControlEvents:UIControlEventEditingChanged];
[cell addSubview:textField];
cell.textLabel.textColor = LJFontColor4c;
[cell.textLabel setFont:LJFontSize16];
cell.detailTextLabel.textColor = LJFontColor88;
[cell.detailTextLabel setFont:[UIFont systemFontOfSize:15]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row == 0) {
cell.textLabel.text = @"收货人姓名";
UITextField *textField = (UITextField*)[cell viewWithTag:indexPath.row + 100];
textField.placeholder = @"收货人姓名";
self.nameField = textField;
}else if (indexPath.row == 1){
cell.textLabel.text = @"手机号码";
UITextField *textField = (UITextField*)[cell viewWithTag:indexPath.row + 100];
textField.keyboardType = UIKeyboardTypePhonePad;
textField.placeholder = @"收货人手机号";
self.phoneField = textField;
}else if (indexPath.row == 2){
cell.textLabel.text = @"省、市、区/县";
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UITextField *textField = (UITextField*)[cell viewWithTag:indexPath.row + 100];
[textField removeFromSuperview];
cell.detailTextLabel.text = @"请选择";
self.provinceCell = cell;
}else if (indexPath.row == 3){
cell.textLabel.text = @"邮政编码";
UITextField *textField = (UITextField*)[cell viewWithTag:indexPath.row + 100];
textField.keyboardType = UIKeyboardTypePhonePad;
textField.placeholder = @"邮政编码";
self.postNum = textField;
}else if (indexPath.row == 4){
cell.textLabel.text = @"详细地址";
UITextField *textField = (UITextField*)[cell viewWithTag:indexPath.row + 100];
textField.placeholder = @"请输入详细地址";
self.detailField = textField;
textField.lj_x = 100;
textField.lj_width = SCREEN_WIDTH - 110;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 2) {
LJAddressSelectedViewController *Vc = [NSClassFromString(@"LJAddressSelectedViewController") new];
__weak LJNewAddressViewController *weakSelf = self;
Vc.addressInfoblock = ^(NSString *address){
weakSelf.provinceCell.detailTextLabel.text = address;
};
[self.navigationController pushViewController:Vc animated:YES];
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (![self.navigationItem.title isEqualToString:@"修改地址"]) return; //如果不是修改地址就不用传值
if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
[self loadData];
}
}
#pragma mark --textField代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.tag == 101) {
if (textField.text.length - range.length + string.length > 11) {
return NO;
}
return [LJVerifyInfo isNumText:[textField.text stringByAppendingString:string]];
}
if (textField.tag == 103) {
if (textField.text.length - range.length + string.length > 6) {
return NO;
}
return [LJVerifyInfo isNumText:[textField.text stringByAppendingString:string]];
}
return YES;
}
#pragma mark --监听保存按钮的状态
- (void)edingChange {
if (self.nameField.text.length > 0 && self.phoneField.text.length > 0 && !([self.provinceCell.detailTextLabel.text isEqualToString:@"请选择"] > 0) &&self.postNum.text.length > 0 &&self.detailField.text.length >0) {
self.saveBtn.backgroundColor = [UIColor redColor];
self.saveBtn.enabled =YES;
}else{
self.saveBtn.backgroundColor = LJFontColor88;
self.saveBtn.enabled =NO;
}
}
#pragma mark --添加保存按钮
- (void)addSaveBtn {
self.saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(28, SCREEN_HEIGHT -86, SCREEN_WIDTH - 56, spaceEdgeH(44))];
self.saveBtn.backgroundColor = LJFontColorc3;
self.saveBtn.enabled = NO;
[self.saveBtn.titleLabel setFont:LJFontSize16];
[self.saveBtn setTitle:@"保存" forState:UIControlStateNormal];
[self.saveBtn.titleLabel setTextColor:[UIColor whiteColor]];
[self.saveBtn setLayerWithCr:5];
[self.saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.saveBtn];
}
//self.saveBtn Click
- (void)saveBtnClick {
LJLogFunc
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark --解决键盘遮挡问题
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if ( textField.tag == 104) {
//滑动效果(动画)
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//将视图的Y坐标向上移动,以使下面腾出地方用于软键盘的显示
self.view.frame = CGRectMake(0.0f, -25.f, self.view.frame.size.width, self.view.frame.size.height);//64-216
[UIView commitAnimations];
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
if ( textField.tag == 104) {
//滑动效果
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
//恢复屏幕
self.view.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);//64-216
[UIView commitAnimations];}
}
- (void) back{
if ([self.nameField.text isEqualToString:@""]&&[self.phoneField.text isEqualToString:@""]&&[self.provinceCell.detailTextLabel.text isEqualToString:@"请选择"]&&[self.postNum.text isEqualToString:@""]&&[self.detailField.text isEqualToString:@""]) {
[self.navigationController popViewControllerAnimated:YES];
}else{
LJTooltip *tip =[[LJTooltip alloc] initWithToolTipStyle:ToolTipStyleAlert2];
[tip Alert2content:@"确定要退出么?"];
__weak LJNewAddressViewController *weakSelf = self;
tip.okClickBlock =^ (NSString *str) {
if ([str isEqualToString:@"确定"]) {
[weakSelf.navigationController popViewControllerAnimated:YES];
}
};
[tip showTooltip];
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
| {
"content_hash": "da59fed5d1fc807b56caa98002607201",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 247,
"avg_line_length": 40.730593607305934,
"alnum_prop": 0.692713004484305,
"repo_name": "duanzhenglong/xianchufang",
"id": "d5c1a236ac08ec8667b0cf69ccab382322fd2c52",
"size": "9581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xianchufang/xianchufang/Class/Me/Controller/LJNewAddressViewController.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "4689"
},
{
"name": "Objective-C",
"bytes": "1842180"
},
{
"name": "Ruby",
"bytes": "760"
},
{
"name": "Shell",
"bytes": "25671"
},
{
"name": "Swift",
"bytes": "16223"
}
],
"symlink_target": ""
} |
@protocol NYYJItemViewDelegate;
@interface NYYJItemView : UIView<UITableViewDataSource, UITableViewDelegate>
@property (assign, nonatomic) id<NYYJItemViewDelegate> delegate;
@property (nonatomic) NSInteger pageNumber;
- (id)initWithFrame:(CGRect)frame delegate:(id<NYYJItemViewDelegate>)delegate;
- (void)willReloadDataWithArray:(NSArray *)itemArray;
- (void)willReloadDataWithNextPageArray:(NSArray *)itemArray;
@end
@protocol NYYJItemViewDelegate <NSObject>
@optional
- (void)didScrolledBottom:(NSInteger)pageNumber;
- (void)didSelectedYJItemCellWithIndexPath:(NSIndexPath *)indexPath;
@end
| {
"content_hash": "11d73e8209d7f0cb1e5171cb94a84d56",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 78,
"avg_line_length": 27.363636363636363,
"alnum_prop": 0.813953488372093,
"repo_name": "naoto0822/ios-sandbox",
"id": "73f8b97f29547902982903532a4dcac21086bb92",
"size": "806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ios-sandbox/Classes/Views/NYYJItemView.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "42785"
}
],
"symlink_target": ""
} |
<?php
namespace Admin\Model;
use Application\Model\Doctrine,
DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as DoctrineAdapter,
Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator,
Settings\Entity\SocialNetwork as SocialNetworkEntity;
class SocialNetwork extends Doctrine {
const TEMP_IMAGES_DIR = 'public/images/tmpuploads/';
const ICONS_DIR = 'public/images/social_networks/icon';
protected $socialNetworkEntity;
protected $cdnHost;
public function __construct($sm) {
$envConfig = $sm->get('Config');
$host = $envConfig['web']['host'];
$this->cdnHost = $host;
$em = $sm->get('doctrine.entitymanager.orm_default');
parent::__construct($em);
}
public function getIconsDirectory() {
return self::ICONS_DIR;
}
public function getTempImagesDirectory() {
return self::TEMP_IMAGES_DIR;
}
public function all() {
return $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->findAll();
}
public function allVisible($limit=0, $page=0) {
if($page > 0) {
$offset = (int) ($page-1)*$limit;
return $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->findBy( array('visible' => true), array('created_at' => 'ASC'), $limit, $offset );
} else {
$offset = (int) ($page-1)*$limit;
return $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->findBy( array('visible' => true), array('created_at' => 'ASC') );
}
}
public function get($id) {
return $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->find($id); #->hydrate(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
public function getByIds($ids) {
return $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->findBy( array('id' => $ids) );
}
public function allSelect() {
$socialNetworks = $this->entityManager->getRepository('Settings\Entity\SocialNetwork')->findAll();
$data = array();
foreach ($socialNetworks as $socialNetwork){
$data[$socialNetwork->id] = $socialNetwork->name;
}
return $data;
}
public function getAdapter($column = 'name', $order = 'asc', $searchParams = array()) {
$repository = $this->entityManager->getRepository('Settings\Entity\SocialNetwork');
$query = $repository->createQueryBuilder('sn');
if ($column != '') {
$query->add('orderBy', "sn.$column $order");
} else {
$query->add('orderBy', "sn.sequence desc");
}
if (isset($searchParams['query']) && $searchParams['query'] != '') {
$searchTerm = $searchParams['query'];
$query->andWhere( $query->expr()->like('sn.title', $query->expr()->literal('%' . $searchTerm . '%')) );
}
if (isset($searchParams['visible']) && $searchParams['visible'] != '') {
$query->andWhere( $query->expr()->eq('sn.visible', $searchParams['visible']) );
}
return new DoctrineAdapter(new ORMPaginator($query));
}
public function getNextSequence() {
$repository = $this->entityManager->getRepository('Settings\Entity\SocialNetwork');
$qb = $repository->createQueryBuilder('sn');
$qb->select( $qb->expr()->max('sn.sequence') );
$dql = $qb->getDql();
$query = $this->entityManager->createQuery($dql);
$nextSequence = $query->getSingleScalarResult() + 1;
return $nextSequence;
}
public function getMaxSequenceByIds($ids) {
$repository = $this->entityManager->getRepository('Settings\Entity\SocialNetwork');
$qb = $repository->createQueryBuilder('sn');
$qb->select( $qb->expr()->max('sn.sequence') );
$qb->where( $qb->expr()->in('sn.id', $ids) );
$dql = $qb->getDql();
$query = $this->entityManager->createQuery($dql);
return $query->getSingleScalarResult();
}
public function create($data) {
$socialNetwork = new SocialNetworkEntity();
foreach ($data as $key => $value) {
$socialNetwork->$key = $value;
}
$socialNetwork->sequence = $this->getNextSequence();
$this->entityManager->persist($socialNetwork);
$this->entityManager->flush();
return $socialNetwork;
}
public function setSocialNetworkEntity($socialNetwork) {
$this->socialNetworkEntity = $socialNetwork;
}
public function getSocialNetworkEntity() {
return $this->socialNetworkEntity;
}
public function getCdnHost() {
return $this->cdnHost;
}
public function getServiceManager() {
return $this->serviceManager;
}
public function getRepresentation() {
$socialNetwork = $this->getSocialNetworkEntity();
$output['id'] = $socialNetwork->id;
$output['title'] = $socialNetwork->title;
$output['url'] = $socialNetwork->url;
if ($socialNetwork->icon) {
$output['icon'] = $this->getCdnHost() . '/images/social_networks/icon/' . $socialNetwork->icon . '?' . time();
} else {
$output['icon'] = '';
}
return $output;
}
public function removeIcon($id) {
$socialNetwork = $this->get($id);
if($socialNetwork instanceof SocialNetworkEntity) {
$iconsDirectory = $this->getIconsDirectory();
$iconImageFile = $socialNetwork->icon;
$iconTargetPath = "$iconsDirectory/$iconImageFile";
if(file_exists($iconTargetPath)) {
unlink($iconTargetPath);
}
$socialNetwork->icon = null;
$this->save($socialNetwork);
}
}
public function uploadIcon() {
$adapter = new \Zend\File\Transfer\Adapter\Http();
$fileInfo = $adapter->getFileInfo();
$fileInfo = $fileInfo['icon'];
$fileExt = $fileInfo['type'];
$sizeInBytes = $fileInfo['size'];
$fileName = $fileInfo['name'];
$arr = explode('/', $fileExt);
$ext = $arr[1];
$fileName = str_replace(' ', '_', $fileName);
$adapter->setDestination(self::TEMP_IMAGES_DIR);
$renameImg = time() . '_social_network_icon.' . $ext;
$adapter->addFilter('Rename', array('target' => self::TEMP_IMAGES_DIR . $renameImg, 'overwrite' => true));
$file = array();
if ($adapter->receive()) {
$file['name'] = $fileName;
$file['storage_name'] = $renameImg;
$file['url'] = str_replace('public', '', self::TEMP_IMAGES_DIR) . $renameImg;
}
return $file;
}
} | {
"content_hash": "5eb2fc27b20627730271231e92d34302",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 165,
"avg_line_length": 33.89010989010989,
"alnum_prop": 0.6386186770428015,
"repo_name": "mafia99/Abbelire",
"id": "c06984216c9e928b28176eda4e604d18915651d2",
"size": "6168",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Admin/src/Admin/Model/SocialNetwork.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.luzhishen.easypackage.facade.biz;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;
import org.springframework.stereotype.Service;
import com.luzhishen.easypackage.facade.entity.User;
@Service
public class UserBiz {
/**
*
* @param userName
* @param password
* @return
*/
@Nullable
public User findUser(String userName, String password) {
// TODO
if (StringUtils.isNotBlank(userName)
&& StringUtils.isNoneBlank(password)
&& StringUtils.equals(userName, password)) {
User user = new User();
user.setId(1);
return user;
}
return null;
}
} | {
"content_hash": "bdad62a8b3a75a9ad8bf648b07fa26ad",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 60,
"avg_line_length": 24.4,
"alnum_prop": 0.6202185792349727,
"repo_name": "wittyLuzhishen/EasyPackage",
"id": "c0636e5e591cbe72e0777fe6d42924a323260c51",
"size": "732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/luzhishen/easypackage/facade/biz/UserBiz.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1060"
},
{
"name": "Java",
"bytes": "67564"
},
{
"name": "JavaScript",
"bytes": "5686"
},
{
"name": "Shell",
"bytes": "222"
}
],
"symlink_target": ""
} |
package com.fruit.dao.management;
import com.fruit.entity.management.Irrigation;
import com.fruit.base.DaoSupport;
/**
*
* @author CSH
*
*/
public interface IrrigationDao extends DaoSupport<Irrigation>{
String DAO_NAME="com.fruit.dao.impl.IrrigationDaoImpl";
}
| {
"content_hash": "0c66440a26354053443d4393bf437854",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 62,
"avg_line_length": 19.5,
"alnum_prop": 0.7509157509157509,
"repo_name": "tanliu/fruit",
"id": "0584e20f974d19055f1b3ef36ef9ad1bf321b677",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fruit-core/src/main/java/com/fruit/dao/management/IrrigationDao.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "392896"
},
{
"name": "HTML",
"bytes": "1981497"
},
{
"name": "Java",
"bytes": "604413"
},
{
"name": "JavaScript",
"bytes": "11560981"
},
{
"name": "PowerShell",
"bytes": "468"
},
{
"name": "Shell",
"bytes": "292"
}
],
"symlink_target": ""
} |
NS_ASSUME_NONNULL_BEGIN
@class DWDPContactsItemsFactory;
@class NSFetchedResultsController;
@interface DWContactsSearchDataSourceObject : NSObject <DWContactsDataSource>
- (instancetype)initWithContactRequestsFRC:(NSFetchedResultsController *)contactRequestsFRC
contactsFRC:(NSFetchedResultsController *)contactsFRC
itemsFactory:(DWDPContactsItemsFactory *)itemsFactory
trimmedQuery:(NSString *)trimmedQuery;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "99cf33628305e6588cb45538bd2d28bd",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 91,
"avg_line_length": 33.666666666666664,
"alnum_prop": 0.7211221122112211,
"repo_name": "QuantumExplorer/breadwallet",
"id": "84a1903aeb96463183b38377134b33f0f4b74c4e",
"size": "1315",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "DashWallet/Sources/UI/DashPay/Contacts/Models/DataSource/DWContactsSearchDataSourceObject.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "495752"
},
{
"name": "C++",
"bytes": "13127"
},
{
"name": "Java",
"bytes": "2100"
},
{
"name": "Objective-C",
"bytes": "1430773"
},
{
"name": "Shell",
"bytes": "586"
}
],
"symlink_target": ""
} |
package kujiin.util.enums;
public enum QuickAddAmbienceType {
REPEAT, SHUFFLE
}
| {
"content_hash": "c592dbc2596a2cc9a8cbbe5b6b3ff023",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 34,
"avg_line_length": 17,
"alnum_prop": 0.7647058823529411,
"repo_name": "calebtrahan/KujiIn_Java",
"id": "52806f12ec81480ddaa696a64c42dfd91fc84e2d",
"size": "85",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/kujiin/util/enums/QuickAddAmbienceType.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6787"
},
{
"name": "HTML",
"bytes": "861"
},
{
"name": "Java",
"bytes": "647552"
}
],
"symlink_target": ""
} |
function getElementByXpath (path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
var rank = getElementByXpath("//*[@id='profile-advanced-right']/div[2]/div[2]/img[2]");
if (rank != null) {
rank = rank.getAttribute("src");
} else {
rank = getElementByXpath("//*[@id='profile-advanced-right']/div[1]/div[2]/img[2]");
if (rank != null) {
rank = rank.getAttribute("src");
}
}
var rslt = [rank];
var reward_cont = getElementByXpath("//*[@id='field_id2']/dd/div[1]/table");
if (reward_cont != null) {
var lst = reward_cont.getElementsByTagName("img");
// console.log( lst );
for (var i=0; i < lst.length; i++) {
rslt.push(lst[i].getAttribute("src"));
}
// console.log( rslt );
}
rslt
| {
"content_hash": "19493f4de846626a83b4a5dd4c97e43f",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 108,
"avg_line_length": 28.607142857142858,
"alnum_prop": 0.616729088639201,
"repo_name": "clan-wot/rewards",
"id": "ae9e36fed41e93c5ac6d81c3e5a523956b9934f8",
"size": "801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/load_user_data.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3161"
},
{
"name": "HTML",
"bytes": "10574"
},
{
"name": "JavaScript",
"bytes": "16269"
},
{
"name": "Makefile",
"bytes": "680"
},
{
"name": "Python",
"bytes": "155134"
}
],
"symlink_target": ""
} |
module Dotify
class Version
# The Checkup class is responsible for
# reaching out to Rubygems.org and retrieving
# the latest gem version.
class Checker
class << self
attr_reader :result, :resp
end
def self.check_latest_release!
@result = (latest == Version.build.level)
end
def self.latest
fetch.map { |v| v['number'] }.max
end
private
def self.fetch
require 'multi_json'
@resp = Net::HTTP.get('rubygems.org', '/api/v1/versions/dotify.json')
MultiJson.load(@resp)
end
end
end
end | {
"content_hash": "c7e41402fb749b74c059bebedae51ac9",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 79,
"avg_line_length": 20.733333333333334,
"alnum_prop": 0.5771704180064309,
"repo_name": "mattdbridges/dotify",
"id": "e0140f79e6496defaab9e206836551dcd425ed3f",
"size": "622",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/dotify/version/checker.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "56510"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "88ebf494c29c51c8097f82ef821bf569",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "8777c7cc4bd42d321cf46c912f1d90ea03457df1",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex sylvatica/ Syn. Carex sylvatica latifolia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "60d19192ff4812bc4e444dae46cd5a9c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "70d6c3b3cdf7d9c662b90b8edad6e2fc3be2a103",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Stipa/Stipa coreana/ Syn. Achnatherum coreanum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef _ncv_pixel_operations_hpp_
#define _ncv_pixel_operations_hpp_
#include <limits.h>
#include <float.h>
#include "NCV.hpp"
template<typename TBase> inline __host__ __device__ TBase _pixMaxVal();
template<> inline __host__ __device__ Ncv8u _pixMaxVal<Ncv8u>() {return UCHAR_MAX;}
template<> inline __host__ __device__ Ncv16u _pixMaxVal<Ncv16u>() {return USHRT_MAX;}
template<> inline __host__ __device__ Ncv32u _pixMaxVal<Ncv32u>() {return UINT_MAX;}
template<> inline __host__ __device__ Ncv8s _pixMaxVal<Ncv8s>() {return SCHAR_MAX;}
template<> inline __host__ __device__ Ncv16s _pixMaxVal<Ncv16s>() {return SHRT_MAX;}
template<> inline __host__ __device__ Ncv32s _pixMaxVal<Ncv32s>() {return INT_MAX;}
template<> inline __host__ __device__ Ncv32f _pixMaxVal<Ncv32f>() {return FLT_MAX;}
template<> inline __host__ __device__ Ncv64f _pixMaxVal<Ncv64f>() {return DBL_MAX;}
template<typename TBase> inline __host__ __device__ TBase _pixMinVal();
template<> inline __host__ __device__ Ncv8u _pixMinVal<Ncv8u>() {return 0;}
template<> inline __host__ __device__ Ncv16u _pixMinVal<Ncv16u>() {return 0;}
template<> inline __host__ __device__ Ncv32u _pixMinVal<Ncv32u>() {return 0;}
template<> inline __host__ __device__ Ncv8s _pixMinVal<Ncv8s>() {return SCHAR_MIN;}
template<> inline __host__ __device__ Ncv16s _pixMinVal<Ncv16s>() {return SHRT_MIN;}
template<> inline __host__ __device__ Ncv32s _pixMinVal<Ncv32s>() {return INT_MIN;}
template<> inline __host__ __device__ Ncv32f _pixMinVal<Ncv32f>() {return FLT_MIN;}
template<> inline __host__ __device__ Ncv64f _pixMinVal<Ncv64f>() {return DBL_MIN;}
template<typename Tvec> struct TConvVec2Base;
template<> struct TConvVec2Base<uchar1> {using TBase = Ncv8u;};
template<> struct TConvVec2Base<uchar3> {using TBase = Ncv8u;};
template<> struct TConvVec2Base<uchar4> {using TBase = Ncv8u;};
template<> struct TConvVec2Base<ushort1> {using TBase = Ncv16u;};
template<> struct TConvVec2Base<ushort3> {using TBase = Ncv16u;};
template<> struct TConvVec2Base<ushort4> {using TBase = Ncv16u;};
template<> struct TConvVec2Base<uint1> {using TBase = Ncv32u;};
template<> struct TConvVec2Base<uint3> {using TBase = Ncv32u;};
template<> struct TConvVec2Base<uint4> {using TBase = Ncv32u;};
template<> struct TConvVec2Base<float1> {using TBase = Ncv32f;};
template<> struct TConvVec2Base<float3> {using TBase = Ncv32f;};
template<> struct TConvVec2Base<float4> {using TBase = Ncv32f;};
template<> struct TConvVec2Base<double1> {using TBase = Ncv64f;};
template<> struct TConvVec2Base<double3> {using TBase = Ncv64f;};
template<> struct TConvVec2Base<double4> {using TBase = Ncv64f;};
#define NC(T) (sizeof(T) / sizeof(TConvVec2Base<T>::TBase))
template<typename TBase, Ncv32u NC> struct TConvBase2Vec;
template<> struct TConvBase2Vec<Ncv8u, 1> {using TVec = uchar1;};
template<> struct TConvBase2Vec<Ncv8u, 3> {using TVec = uchar3;};
template<> struct TConvBase2Vec<Ncv8u, 4> {using TVec = uchar4;};
template<> struct TConvBase2Vec<Ncv16u, 1> {using TVec = ushort1;};
template<> struct TConvBase2Vec<Ncv16u, 3> {using TVec = ushort3;};
template<> struct TConvBase2Vec<Ncv16u, 4> {using TVec = ushort4;};
template<> struct TConvBase2Vec<Ncv32u, 1> {using TVec = uint1;};
template<> struct TConvBase2Vec<Ncv32u, 3> {using TVec = uint3;};
template<> struct TConvBase2Vec<Ncv32u, 4> {using TVec = uint4;};
template<> struct TConvBase2Vec<Ncv32f, 1> {using TVec = float1;};
template<> struct TConvBase2Vec<Ncv32f, 3> {using TVec = float3;};
template<> struct TConvBase2Vec<Ncv32f, 4> {using TVec = float4;};
template<> struct TConvBase2Vec<Ncv64f, 1> {using TVec = double1;};
template<> struct TConvBase2Vec<Ncv64f, 3> {using TVec = double3;};
template<> struct TConvBase2Vec<Ncv64f, 4> {using TVec = double4;};
//TODO: consider using CUDA intrinsics to avoid branching
template<typename Tin> static inline __host__ __device__ void _TDemoteClampZ(Tin &a, Ncv8u &out) {out = (Ncv8u)CLAMP_0_255(a);};
template<typename Tin> static inline __host__ __device__ void _TDemoteClampZ(Tin &a, Ncv16u &out) {out = (Ncv16u)CLAMP(a, 0, USHRT_MAX);}
template<typename Tin> static inline __host__ __device__ void _TDemoteClampZ(Tin &a, Ncv32u &out) {out = (Ncv32u)CLAMP(a, 0, UINT_MAX);}
template<typename Tin> static inline __host__ __device__ void _TDemoteClampZ(Tin &a, Ncv32f &out) {out = (Ncv32f)a;}
//TODO: consider using CUDA intrinsics to avoid branching
template<typename Tin> static inline __host__ __device__ void _TDemoteClampNN(Tin &a, Ncv8u &out) {out = (Ncv8u)CLAMP_0_255(a+0.5f);}
template<typename Tin> static inline __host__ __device__ void _TDemoteClampNN(Tin &a, Ncv16u &out) {out = (Ncv16u)CLAMP(a+0.5f, 0, USHRT_MAX);}
template<typename Tin> static inline __host__ __device__ void _TDemoteClampNN(Tin &a, Ncv32u &out) {out = (Ncv32u)CLAMP(a+0.5f, 0, UINT_MAX);}
template<typename Tin> static inline __host__ __device__ void _TDemoteClampNN(Tin &a, Ncv32f &out) {out = (Ncv32f)a;}
template<typename Tout> inline Tout _pixMakeZero();
template<> inline __host__ __device__ uchar1 _pixMakeZero<uchar1>() {return make_uchar1(0);}
template<> inline __host__ __device__ uchar3 _pixMakeZero<uchar3>() {return make_uchar3(0,0,0);}
template<> inline __host__ __device__ uchar4 _pixMakeZero<uchar4>() {return make_uchar4(0,0,0,0);}
template<> inline __host__ __device__ ushort1 _pixMakeZero<ushort1>() {return make_ushort1(0);}
template<> inline __host__ __device__ ushort3 _pixMakeZero<ushort3>() {return make_ushort3(0,0,0);}
template<> inline __host__ __device__ ushort4 _pixMakeZero<ushort4>() {return make_ushort4(0,0,0,0);}
template<> inline __host__ __device__ uint1 _pixMakeZero<uint1>() {return make_uint1(0);}
template<> inline __host__ __device__ uint3 _pixMakeZero<uint3>() {return make_uint3(0,0,0);}
template<> inline __host__ __device__ uint4 _pixMakeZero<uint4>() {return make_uint4(0,0,0,0);}
template<> inline __host__ __device__ float1 _pixMakeZero<float1>() {return make_float1(0.f);}
template<> inline __host__ __device__ float3 _pixMakeZero<float3>() {return make_float3(0.f,0.f,0.f);}
template<> inline __host__ __device__ float4 _pixMakeZero<float4>() {return make_float4(0.f,0.f,0.f,0.f);}
template<> inline __host__ __device__ double1 _pixMakeZero<double1>() {return make_double1(0.);}
template<> inline __host__ __device__ double3 _pixMakeZero<double3>() {return make_double3(0.,0.,0.);}
template<> inline __host__ __device__ double4 _pixMakeZero<double4>() {return make_double4(0.,0.,0.,0.);}
static inline __host__ __device__ uchar1 _pixMake(Ncv8u x) {return make_uchar1(x);}
static inline __host__ __device__ uchar3 _pixMake(Ncv8u x, Ncv8u y, Ncv8u z) {return make_uchar3(x,y,z);}
static inline __host__ __device__ uchar4 _pixMake(Ncv8u x, Ncv8u y, Ncv8u z, Ncv8u w) {return make_uchar4(x,y,z,w);}
static inline __host__ __device__ ushort1 _pixMake(Ncv16u x) {return make_ushort1(x);}
static inline __host__ __device__ ushort3 _pixMake(Ncv16u x, Ncv16u y, Ncv16u z) {return make_ushort3(x,y,z);}
static inline __host__ __device__ ushort4 _pixMake(Ncv16u x, Ncv16u y, Ncv16u z, Ncv16u w) {return make_ushort4(x,y,z,w);}
static inline __host__ __device__ uint1 _pixMake(Ncv32u x) {return make_uint1(x);}
static inline __host__ __device__ uint3 _pixMake(Ncv32u x, Ncv32u y, Ncv32u z) {return make_uint3(x,y,z);}
static inline __host__ __device__ uint4 _pixMake(Ncv32u x, Ncv32u y, Ncv32u z, Ncv32u w) {return make_uint4(x,y,z,w);}
static inline __host__ __device__ float1 _pixMake(Ncv32f x) {return make_float1(x);}
static inline __host__ __device__ float3 _pixMake(Ncv32f x, Ncv32f y, Ncv32f z) {return make_float3(x,y,z);}
static inline __host__ __device__ float4 _pixMake(Ncv32f x, Ncv32f y, Ncv32f z, Ncv32f w) {return make_float4(x,y,z,w);}
static inline __host__ __device__ double1 _pixMake(Ncv64f x) {return make_double1(x);}
static inline __host__ __device__ double3 _pixMake(Ncv64f x, Ncv64f y, Ncv64f z) {return make_double3(x,y,z);}
static inline __host__ __device__ double4 _pixMake(Ncv64f x, Ncv64f y, Ncv64f z, Ncv64f w) {return make_double4(x,y,z,w);}
template<typename Tin, typename Tout, Ncv32u CN> struct __pixDemoteClampZ_CN {static __host__ __device__ Tout _pixDemoteClampZ_CN(Tin &pix);};
template<typename Tin, typename Tout> struct __pixDemoteClampZ_CN<Tin, Tout, 1> {
static __host__ __device__ Tout _pixDemoteClampZ_CN(Tin &pix)
{
Tout out;
_TDemoteClampZ(pix.x, out.x);
return out;
}};
template<typename Tin, typename Tout> struct __pixDemoteClampZ_CN<Tin, Tout, 3> {
static __host__ __device__ Tout _pixDemoteClampZ_CN(Tin &pix)
{
Tout out;
_TDemoteClampZ(pix.x, out.x);
_TDemoteClampZ(pix.y, out.y);
_TDemoteClampZ(pix.z, out.z);
return out;
}};
template<typename Tin, typename Tout> struct __pixDemoteClampZ_CN<Tin, Tout, 4> {
static __host__ __device__ Tout _pixDemoteClampZ_CN(Tin &pix)
{
Tout out;
_TDemoteClampZ(pix.x, out.x);
_TDemoteClampZ(pix.y, out.y);
_TDemoteClampZ(pix.z, out.z);
_TDemoteClampZ(pix.w, out.w);
return out;
}};
template<typename Tin, typename Tout> static inline __host__ __device__ Tout _pixDemoteClampZ(Tin &pix)
{
return __pixDemoteClampZ_CN<Tin, Tout, NC(Tin)>::_pixDemoteClampZ_CN(pix);
}
template<typename Tin, typename Tout, Ncv32u CN> struct __pixDemoteClampNN_CN {static __host__ __device__ Tout _pixDemoteClampNN_CN(Tin &pix);};
template<typename Tin, typename Tout> struct __pixDemoteClampNN_CN<Tin, Tout, 1> {
static __host__ __device__ Tout _pixDemoteClampNN_CN(Tin &pix)
{
Tout out;
_TDemoteClampNN(pix.x, out.x);
return out;
}};
template<typename Tin, typename Tout> struct __pixDemoteClampNN_CN<Tin, Tout, 3> {
static __host__ __device__ Tout _pixDemoteClampNN_CN(Tin &pix)
{
Tout out;
_TDemoteClampNN(pix.x, out.x);
_TDemoteClampNN(pix.y, out.y);
_TDemoteClampNN(pix.z, out.z);
return out;
}};
template<typename Tin, typename Tout> struct __pixDemoteClampNN_CN<Tin, Tout, 4> {
static __host__ __device__ Tout _pixDemoteClampNN_CN(Tin &pix)
{
Tout out;
_TDemoteClampNN(pix.x, out.x);
_TDemoteClampNN(pix.y, out.y);
_TDemoteClampNN(pix.z, out.z);
_TDemoteClampNN(pix.w, out.w);
return out;
}};
template<typename Tin, typename Tout> static inline __host__ __device__ Tout _pixDemoteClampNN(Tin &pix)
{
return __pixDemoteClampNN_CN<Tin, Tout, NC(Tin)>::_pixDemoteClampNN_CN(pix);
}
template<typename Tin, typename Tout, typename Tw, Ncv32u CN> struct __pixScale_CN {static __host__ __device__ Tout _pixScale_CN(Tin &pix, Tw w);};
template<typename Tin, typename Tout, typename Tw> struct __pixScale_CN<Tin, Tout, Tw, 1> {
static __host__ __device__ Tout _pixScale_CN(Tin &pix, Tw w)
{
Tout out;
using TBout = typename TConvVec2Base<Tout>::TBase;
out.x = (TBout)(pix.x * w);
return out;
}};
template<typename Tin, typename Tout, typename Tw> struct __pixScale_CN<Tin, Tout, Tw, 3> {
static __host__ __device__ Tout _pixScale_CN(Tin &pix, Tw w)
{
Tout out;
using TBout = typename TConvVec2Base<Tout>::TBase;
out.x = (TBout)(pix.x * w);
out.y = (TBout)(pix.y * w);
out.z = (TBout)(pix.z * w);
return out;
}};
template<typename Tin, typename Tout, typename Tw> struct __pixScale_CN<Tin, Tout, Tw, 4> {
static __host__ __device__ Tout _pixScale_CN(Tin &pix, Tw w)
{
Tout out;
using TBout = typename TConvVec2Base<Tout>::TBase;
out.x = (TBout)(pix.x * w);
out.y = (TBout)(pix.y * w);
out.z = (TBout)(pix.z * w);
out.w = (TBout)(pix.w * w);
return out;
}};
template<typename Tin, typename Tout, typename Tw> static __host__ __device__ Tout _pixScale(Tin &pix, Tw w)
{
return __pixScale_CN<Tin, Tout, Tw, NC(Tin)>::_pixScale_CN(pix, w);
}
template<typename Tin, typename Tout, Ncv32u CN> struct __pixAdd_CN {static __host__ __device__ Tout _pixAdd_CN(Tout &pix1, Tin &pix2);};
template<typename Tin, typename Tout> struct __pixAdd_CN<Tin, Tout, 1> {
static __host__ __device__ Tout _pixAdd_CN(Tout &pix1, Tin &pix2)
{
Tout out;
out.x = pix1.x + pix2.x;
return out;
}};
template<typename Tin, typename Tout> struct __pixAdd_CN<Tin, Tout, 3> {
static __host__ __device__ Tout _pixAdd_CN(Tout &pix1, Tin &pix2)
{
Tout out;
out.x = pix1.x + pix2.x;
out.y = pix1.y + pix2.y;
out.z = pix1.z + pix2.z;
return out;
}};
template<typename Tin, typename Tout> struct __pixAdd_CN<Tin, Tout, 4> {
static __host__ __device__ Tout _pixAdd_CN(Tout &pix1, Tin &pix2)
{
Tout out;
out.x = pix1.x + pix2.x;
out.y = pix1.y + pix2.y;
out.z = pix1.z + pix2.z;
out.w = pix1.w + pix2.w;
return out;
}};
template<typename Tin, typename Tout> static __host__ __device__ Tout _pixAdd(Tout &pix1, Tin &pix2)
{
return __pixAdd_CN<Tin, Tout, NC(Tin)>::_pixAdd_CN(pix1, pix2);
}
template<typename Tin, typename Tout, Ncv32u CN> struct __pixDist_CN {static __host__ __device__ Tout _pixDist_CN(Tin &pix1, Tin &pix2);};
template<typename Tin, typename Tout> struct __pixDist_CN<Tin, Tout, 1> {
static __host__ __device__ Tout _pixDist_CN(Tin &pix1, Tin &pix2)
{
return Tout(SQR(pix1.x - pix2.x));
}};
template<typename Tin, typename Tout> struct __pixDist_CN<Tin, Tout, 3> {
static __host__ __device__ Tout _pixDist_CN(Tin &pix1, Tin &pix2)
{
return Tout(SQR(pix1.x - pix2.x) + SQR(pix1.y - pix2.y) + SQR(pix1.z - pix2.z));
}};
template<typename Tin, typename Tout> struct __pixDist_CN<Tin, Tout, 4> {
static __host__ __device__ Tout _pixDist_CN(Tin &pix1, Tin &pix2)
{
return Tout(SQR(pix1.x - pix2.x) + SQR(pix1.y - pix2.y) + SQR(pix1.z - pix2.z) + SQR(pix1.w - pix2.w));
}};
template<typename Tin, typename Tout> static __host__ __device__ Tout _pixDist(Tin &pix1, Tin &pix2)
{
return __pixDist_CN<Tin, Tout, NC(Tin)>::_pixDist_CN(pix1, pix2);
}
template <typename T> struct TAccPixWeighted;
template<> struct TAccPixWeighted<uchar1> {using type = double1;};
template<> struct TAccPixWeighted<uchar3> {using type = double3;};
template<> struct TAccPixWeighted<uchar4> {using type = double4;};
template<> struct TAccPixWeighted<ushort1> {using type = double1;};
template<> struct TAccPixWeighted<ushort3> {using type = double3;};
template<> struct TAccPixWeighted<ushort4> {using type = double4;};
template<> struct TAccPixWeighted<float1> {using type = double1;};
template<> struct TAccPixWeighted<float3> {using type = double3;};
template<> struct TAccPixWeighted<float4> {using type = double4;};
template<typename Tfrom> struct TAccPixDist {};
template<> struct TAccPixDist<uchar1> {using type = Ncv32u;};
template<> struct TAccPixDist<uchar3> {using type = Ncv32u;};
template<> struct TAccPixDist<uchar4> {using type = Ncv32u;};
template<> struct TAccPixDist<ushort1> {using type = Ncv32u;};
template<> struct TAccPixDist<ushort3> {using type = Ncv32u;};
template<> struct TAccPixDist<ushort4> {using type = Ncv32u;};
template<> struct TAccPixDist<float1> {using type = Ncv32f;};
template<> struct TAccPixDist<float3> {using type = Ncv32f;};
template<> struct TAccPixDist<float4> {using type = Ncv32f;};
#endif //_ncv_pixel_operations_hpp_
| {
"content_hash": "f16feb8bee890e9052a92c607f51c08c",
"timestamp": "",
"source": "github",
"line_count": 311,
"max_line_length": 147,
"avg_line_length": 48.59163987138264,
"alnum_prop": 0.6816437268395976,
"repo_name": "drmateo/pcl",
"id": "ae24796f94e9defb280c474a969a84bbdd35d5d9",
"size": "17002",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "gpu/people/src/cuda/nvidia/NCVPixelOperations.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "172874"
},
{
"name": "C++",
"bytes": "19619498"
},
{
"name": "CMake",
"bytes": "440645"
},
{
"name": "Cuda",
"bytes": "923615"
},
{
"name": "GLSL",
"bytes": "2653"
},
{
"name": "Matlab",
"bytes": "3407"
},
{
"name": "Objective-C",
"bytes": "5638"
},
{
"name": "Objective-C++",
"bytes": "7489"
},
{
"name": "Python",
"bytes": "29169"
},
{
"name": "Shell",
"bytes": "9857"
}
],
"symlink_target": ""
} |
title: aof35
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: f35
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "eca44cad8eca21e26b01155b8da7a1b3",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6656716417910448,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "1771d23a58fc16eb8c43a6454d762b95deb9533e",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/aof35.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "87339dcb71271d3e721afae282d4b1c7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "13897be5c564fbd991c15b8f8bbe6c012b3cc621",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Cucurbitales/Begoniaceae/Begonia/Begonia cataractarum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* Siren Decoder Gst Element
*
* @author: Youness Alaoui <kakaroto@kakaroto.homelinux.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* SECTION:element-sirendec
* @title: sirendec
*
* This decodes audio buffers from the Siren 16 codec (a 16khz extension of
* G.722.1) that is meant to be compatible with the Microsoft Windows Live
* Messenger(tm) implementation.
*
* Ref: http://www.polycom.com/company/about_us/technology/siren_g7221/index.html
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstsirendec.h"
#include <string.h>
GST_DEBUG_CATEGORY (sirendec_debug);
#define GST_CAT_DEFAULT (sirendec_debug)
#define FRAME_DURATION (20 * GST_MSECOND)
static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("audio/x-siren, " "dct-length = (int) 320"));
static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("audio/x-raw, format = (string) \"S16LE\", "
"rate = (int) 16000, " "channels = (int) 1"));
static gboolean gst_siren_dec_start (GstAudioDecoder * dec);
static gboolean gst_siren_dec_stop (GstAudioDecoder * dec);
static gboolean gst_siren_dec_set_format (GstAudioDecoder * dec,
GstCaps * caps);
static GstFlowReturn gst_siren_dec_parse (GstAudioDecoder * dec,
GstAdapter * adapter, gint * offset, gint * length);
static GstFlowReturn gst_siren_dec_handle_frame (GstAudioDecoder * dec,
GstBuffer * buffer);
G_DEFINE_TYPE (GstSirenDec, gst_siren_dec, GST_TYPE_AUDIO_DECODER);
static void
gst_siren_dec_class_init (GstSirenDecClass * klass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
GstAudioDecoderClass *base_class = GST_AUDIO_DECODER_CLASS (klass);
GST_DEBUG_CATEGORY_INIT (sirendec_debug, "sirendec", 0, "sirendec");
gst_element_class_add_static_pad_template (element_class, &srctemplate);
gst_element_class_add_static_pad_template (element_class, &sinktemplate);
gst_element_class_set_static_metadata (element_class, "Siren Decoder element",
"Codec/Decoder/Audio ",
"Decode streams encoded with the Siren7 codec into 16bit PCM",
"Youness Alaoui <kakaroto@kakaroto.homelinux.net>");
base_class->start = GST_DEBUG_FUNCPTR (gst_siren_dec_start);
base_class->stop = GST_DEBUG_FUNCPTR (gst_siren_dec_stop);
base_class->set_format = GST_DEBUG_FUNCPTR (gst_siren_dec_set_format);
base_class->parse = GST_DEBUG_FUNCPTR (gst_siren_dec_parse);
base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_siren_dec_handle_frame);
GST_DEBUG ("Class Init done");
}
static void
gst_siren_dec_init (GstSirenDec * dec)
{
gst_audio_decoder_set_needs_format (GST_AUDIO_DECODER (dec), TRUE);
gst_audio_decoder_set_use_default_pad_acceptcaps (GST_AUDIO_DECODER_CAST
(dec), TRUE);
GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_DECODER_SINK_PAD (dec));
}
static gboolean
gst_siren_dec_start (GstAudioDecoder * dec)
{
GstSirenDec *sdec = GST_SIREN_DEC (dec);
GST_DEBUG_OBJECT (dec, "start");
sdec->decoder = Siren7_NewDecoder (16000);
/* no flushing please */
gst_audio_decoder_set_drainable (dec, FALSE);
return TRUE;
}
static gboolean
gst_siren_dec_stop (GstAudioDecoder * dec)
{
GstSirenDec *sdec = GST_SIREN_DEC (dec);
GST_DEBUG_OBJECT (dec, "stop");
Siren7_CloseDecoder (sdec->decoder);
return TRUE;
}
static gboolean
gst_siren_dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
{
GstAudioInfo info;
gst_audio_info_init (&info);
gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16LE, 16000, 1, NULL);
return gst_audio_decoder_set_output_format (bdec, &info);
}
static GstFlowReturn
gst_siren_dec_parse (GstAudioDecoder * dec, GstAdapter * adapter,
gint * offset, gint * length)
{
gint size;
GstFlowReturn ret;
size = gst_adapter_available (adapter);
g_return_val_if_fail (size > 0, GST_FLOW_ERROR);
/* accept any multiple of frames */
if (size > 40) {
ret = GST_FLOW_OK;
*offset = 0;
*length = size - (size % 40);
} else {
ret = GST_FLOW_EOS;
}
return ret;
}
static GstFlowReturn
gst_siren_dec_handle_frame (GstAudioDecoder * bdec, GstBuffer * buf)
{
GstSirenDec *dec;
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *out_buf;
guint8 *in_data, *out_data;
guint i, size, num_frames;
gint out_size;
#ifndef GST_DISABLE_GST_DEBUG
gint in_size;
#endif
gint decode_ret;
GstMapInfo inmap, outmap;
dec = GST_SIREN_DEC (bdec);
size = gst_buffer_get_size (buf);
GST_LOG_OBJECT (dec, "Received buffer of size %u", size);
g_return_val_if_fail (size % 40 == 0, GST_FLOW_ERROR);
g_return_val_if_fail (size > 0, GST_FLOW_ERROR);
/* process 40 input bytes into 640 output bytes */
num_frames = size / 40;
/* this is the input/output size */
#ifndef GST_DISABLE_GST_DEBUG
in_size = num_frames * 40;
#endif
out_size = num_frames * 640;
GST_LOG_OBJECT (dec, "we have %u frames, %u in, %u out", num_frames, in_size,
out_size);
out_buf = gst_audio_decoder_allocate_output_buffer (bdec, out_size);
if (out_buf == NULL)
goto alloc_failed;
/* get the input data for all the frames */
gst_buffer_map (buf, &inmap, GST_MAP_READ);
gst_buffer_map (out_buf, &outmap, GST_MAP_WRITE);
in_data = inmap.data;
out_data = outmap.data;
for (i = 0; i < num_frames; i++) {
GST_LOG_OBJECT (dec, "Decoding frame %u/%u", i, num_frames);
/* decode 40 input bytes to 640 output bytes */
decode_ret = Siren7_DecodeFrame (dec->decoder, in_data, out_data);
if (decode_ret != 0)
goto decode_error;
/* move to next frame */
out_data += 640;
in_data += 40;
}
gst_buffer_unmap (buf, &inmap);
gst_buffer_unmap (out_buf, &outmap);
GST_LOG_OBJECT (dec, "Finished decoding");
/* might really be multiple frames,
* but was treated as one for all purposes here */
ret = gst_audio_decoder_finish_frame (bdec, out_buf, 1);
done:
return ret;
/* ERRORS */
alloc_failed:
{
GST_DEBUG_OBJECT (dec, "failed to pad_alloc buffer: %d (%s)", ret,
gst_flow_get_name (ret));
goto done;
}
decode_error:
{
GST_AUDIO_DECODER_ERROR (bdec, 1, STREAM, DECODE, (NULL),
("Error decoding frame: %d", decode_ret), ret);
if (ret == GST_FLOW_OK)
gst_audio_decoder_finish_frame (bdec, NULL, 1);
gst_buffer_unref (out_buf);
goto done;
}
}
gboolean
gst_siren_dec_plugin_init (GstPlugin * plugin)
{
return gst_element_register (plugin, "sirendec",
GST_RANK_MARGINAL, GST_TYPE_SIREN_DEC);
}
| {
"content_hash": "fed941b6afa9f582a6a97ca17d1497c4",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 81,
"avg_line_length": 28.295719844357976,
"alnum_prop": 0.6845434543454345,
"repo_name": "google/aistreams",
"id": "045bcd6686bc5ec11afbecd3832147df06175ec1",
"size": "7272",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "third_party/gst-plugins-bad/gst/siren/gstsirendec.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "77741"
},
{
"name": "C++",
"bytes": "626396"
},
{
"name": "Python",
"bytes": "41809"
},
{
"name": "Starlark",
"bytes": "56595"
}
],
"symlink_target": ""
} |
package ru.job4j.start;
public class MenuOutException extends RuntimeException {
public MenuOutException(String msg) {
super(msg);
}
}
| {
"content_hash": "ba7f2f4f91e81af49a2618812bb5aa7e",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 56,
"avg_line_length": 21.714285714285715,
"alnum_prop": 0.7105263157894737,
"repo_name": "RadmirShkred/shkredr",
"id": "3bcbce213b1440c1e6c1546feaf19076d7b178f3",
"size": "152",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "chapter_002/src/main/java/ru.job4j/start/MenuOutException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "64755"
}
],
"symlink_target": ""
} |
nextrel=$1
# Get the location of this script. Other scripts that we use must be in the
# same location.
scriptdir=$(dirname $(realpath $0))
# Include function library.
. ${scriptdir}/lib.sh
# Validate the specified new version.
validate_version ${nextrel} || {
echo "Version ${nextrel} is not valid."
echo "See 'validate_version' in ${scriptdir}/lib.sh for guidance."
exit 1
}
# Ensure we're in the root of the Git repository.
cd `git_repo_root`
# Generate raw material for release notes as the list of changes - from Git
# commit messages - since the last release.
last_tag=`git_last_tag`
release_notes=./release-notes-${nextrel}
echo "Felix version ${nextrel}" > ${release_notes}
echo >> ${release_notes}
git cherry -v $last_tag | cut '-d ' -f 3- | sed 's/^/- /' >> ${release_notes}
# Ask user to edit the relase note to their liking.
cat <<EOF
Changes (i.e. Git commit messages) since the last release ($last_tag) have been
written into ${release_notes}. These will become the tag release note.
Please examine that file and edit as appropriate.
Once you have edited the file to your liking, run
make continue-release VERSION=${nextrel}
to create the tag and finish off the release.
EOF
| {
"content_hash": "d0e5c2265fb6195241eff3c2e168d90c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 79,
"avg_line_length": 28.325581395348838,
"alnum_prop": 0.7101806239737274,
"repo_name": "matthewdupre/felix",
"id": "0ed70f7da880fa9ff0184f62376201e09005ef14",
"size": "1322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utils/tag-release.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "921623"
},
{
"name": "Makefile",
"bytes": "15985"
},
{
"name": "Protocol Buffer",
"bytes": "8121"
},
{
"name": "Shell",
"bytes": "32725"
}
],
"symlink_target": ""
} |
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
//angular.module('myApp.services', []).
//value('version', '0.1');
var module = angular.module('myApp.services', []);
module.service('GroupProjService', function () {
// var groupedProjList=[{'id':'4','name':'bernie','age':'15'}];
var groupedProjList=[{}];
//********save projects
this.save=function(project){
groupedProjList.push(project);
};
this.clear=function(){
groupedProjList=[{}];
return groupedProjList;
};
this.list=function(){
return groupedProjList;
};
}); | {
"content_hash": "8fd60e52ce997ff95b6d96e4115fcbd4",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 65,
"avg_line_length": 15.543478260869565,
"alnum_prop": 0.558041958041958,
"repo_name": "githubmave/e-Heroku-ProWork",
"id": "7bc374c01d99a6672467d4cf847ae8cc192d1d82",
"size": "715",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/services.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9619"
},
{
"name": "HTML",
"bytes": "7647"
},
{
"name": "JavaScript",
"bytes": "11149"
}
],
"symlink_target": ""
} |
#include "phd.h"
#if defined (INOVA_PLC)
#include "camera.h"
#include "image_math.h"
#include "cam_INovaPLC.h"
#include "DSCAMAPI.h"
CameraINovaPLC::CameraINovaPLC()
{
Connected = FALSE;
Name=_T("i-Nova PLC-M");
FullSize = wxSize(1280,1024); // Current size of a full frame
m_hasGuideOutput = true; // Do we have an ST4 port?
HasGainControl = true; // Can we adjust gain?
}
wxByte CameraINovaPLC::BitsPerPixel()
{
return 16;
}
bool CameraINovaPLC::Connect(const wxString& camId)
{
DS_CAMERA_STATUS rval = DSCameraInit(R_FULL);
if (rval != STATUS_OK)
return CamConnectFailed(wxString::Format(_("Error on connection: %d"), rval));
DSCameraSetDataWide(true);
DSCameraSetAeState(false); // Turn off auto-exposure
DSCameraGetRowTime(&RowTime); // Figure the row-time in microseconds -- this lets me figure the actual exp time
RawData = new unsigned short[1280*1024];
Connected = true; // Set global flag for being connected
return false;
}
void CameraINovaPLC::InitCapture()
{
// Run after any exp change / at the start of a loop
DS_CAMERA_STATUS rval;
int ExpDur = pFrame->RequestedExposureDuration();
int exp_lines = ExpDur * 1000 / RowTime;
rval = DSCameraSetExposureTime(exp_lines);
wxMilliSleep(100);
if (rval != STATUS_OK)
pFrame->Alert(_("Error setting exposure duration"));
rval = DSCameraSetAnalogGain(GuideCameraGain);
wxMilliSleep(100);
if (rval != STATUS_OK)
pFrame->Alert(_("Error setting gain"));
}
bool CameraINovaPLC::ST4PulseGuideScope(int direction, int duration)
{
unsigned char dircode = 0;
/*Param: Value bit0 - RA+
bit1 - DEC+
bit2 - DEC-
bit3 - RA-*/
switch (direction) {
case WEST:
dircode = 0x01;
break;
case NORTH:
dircode = 0x02;
break;
case SOUTH:
dircode = 0x04;
break;
case EAST:
dircode = 0x08;
break;
default: return true; // bad direction passed in
}
DSCameraSetGuidingPort(dircode);
WorkerThread::MilliSleep(duration);
DSCameraSetGuidingPort(0);
return false;
}
bool CameraINovaPLC::Disconnect()
{
Connected = false;
DSCameraUnInit();
delete [] RawData;
return false;
}
bool CameraINovaPLC::Capture(int duration, usImage& img, int options, const wxRect& subframe)
{
int xsize = FullSize.GetWidth();
int ysize = FullSize.GetHeight();
DS_CAMERA_STATUS rval;
int ntries = 1;
if (img.Init(FullSize)) {
DisconnectWithAlert(CAPT_FAIL_MEMORY);
return true;
}
int ExpDur = pFrame->RequestedExposureDuration();
if (duration != ExpDur) { // reset the exp time - and pause -- we have had a change here from the current value
rval = DSCameraSetExposureTime(ExpDur * 1000 / RowTime);
wxMilliSleep(100);
}
rval = DSCameraGrabFrame((BYTE *) RawData);
while (rval != STATUS_OK) {
ntries++;
rval = DSCameraGrabFrame((BYTE *) RawData);
//pFrame->StatusMsg(wxString::Format("%d %d",ntries,rval));
if (ntries > 30) {
pFrame->Alert("Timeout capturing frames - >30 bad in a row");
return true;
}
}
for (unsigned int i = 0; i <xsize*ysize; i++) {
img.ImageData[i] = (RawData[i]>> 8) | (RawData[i] << 8);
}
if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img);
return false;
}
bool CameraINovaPLC::HasNonGuiCapture(void)
{
return true;
}
bool CameraINovaPLC::ST4HasNonGuiMove(void)
{
return true;
}
#endif // INOVA_PLC
| {
"content_hash": "e1fe5efb70b21a51c43434296f359264",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 116,
"avg_line_length": 27.402877697841728,
"alnum_prop": 0.5993699133630874,
"repo_name": "OpenPHDGuiding/phd2",
"id": "cd29edaf504038403ffbbd95d328c7ac7a8fc391",
"size": "5578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cam_INovaPLC.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "848"
},
{
"name": "C",
"bytes": "953809"
},
{
"name": "C++",
"bytes": "3685973"
},
{
"name": "CMake",
"bytes": "92987"
},
{
"name": "HTML",
"bytes": "2622886"
},
{
"name": "Perl",
"bytes": "3756"
},
{
"name": "Python",
"bytes": "22804"
},
{
"name": "Shell",
"bytes": "33699"
},
{
"name": "VBScript",
"bytes": "2114"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@color/black</item>
<item name="android:windowIsFloating">false</item>
<item name="android:windowNoTitle">true</item>
</style>
<style name="RadioButton">
<item name="android:minHeight">33dp</item>
<item name="android:minWidth">70dp</item>
<item name="android:gravity">center</item>
<item name="android:button">@null</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">5dp</item>
</style>
</resources>
| {
"content_hash": "6d809e2d52e5f21310e067f88b5c1118",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 73,
"avg_line_length": 42.5625,
"alnum_prop": 0.644640234948605,
"repo_name": "andela-Kshittu/Rave",
"id": "85d74c7c87e73d0e47f80af22c01cdf98e7a357a",
"size": "681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "raveModule/src/main/res/values/styles.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "76935"
}
],
"symlink_target": ""
} |
author: slowe
categories: News
comments: true
date: 2007-03-16T22:46:45Z
slug: remotely-exploitable-flaw-in-openbsd-found
tags:
- BSD
- Networking
- Security
- UNIX
title: Remotely Exploitable Flaw in OpenBSD Found
url: /2007/03/16/remotely-exploitable-flaw-in-openbsd-found/
wordpress_id: 429
---
I've got a lot of respect for [OpenBSD](http://www.openbsd.org/), whose maintainers' relentless focus on security has really paid off. Until today, the OpenBSD tagline was "only one remote hole in the default install in almost ten years." Now, due to the discovery of a new [critical vulnerability](http://www.darkreading.com/document.asp?doc_id=119685&f_src=darkreading_section_318), that tagline must change to its current form: "Only two remote holes in the default install, in more than 10 years!"
Fortunately, this new vulnerability is fairly easy to mitigate and is fairly limited in scope to begin with. [This page](http://www.openbsd.org/errata40.html) (look for the security fix dated March 7, 2007) provides some workarounds and a link to the patch that fixes the problem. If you're already using OpenBSD's [pf](http://www.openbsd.org/cgi-bin/man.cgi?query=pf&sektion=4) firewalling functionality, then pf can easily be configured to block the traffic that triggers this vulnerability.
If you manage any OpenBSD-based systems, it would be prudent to configure pf and/or apply the patch to address this vulnerability.
| {
"content_hash": "19642601086400552aba8d9bccedec1d",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 501,
"avg_line_length": 71.4,
"alnum_prop": 0.7843137254901961,
"repo_name": "lowescott/weblog",
"id": "ea8b485453f801a481ad663121bef5056d6f7130",
"size": "1432",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "content/post/2007-03-16-remotely-exploitable-flaw-in-openbsd-found.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25289"
},
{
"name": "HTML",
"bytes": "16683"
}
],
"symlink_target": ""
} |
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Root.h"
// STD lib hreaders:
#include <iostream>
// OS-specific headers:
#if defined(_WIN32)
#include <psapi.h>
#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <signal.h>
#if defined(__linux__)
#include <fstream>
#elif defined(__APPLE__)
#include <mach/mach.h>
#endif
#endif
#include "Server.h"
#include "World.h"
#include "WebAdmin.h"
#include "BrewingRecipes.h"
#include "FurnaceRecipe.h"
#include "CraftingRecipes.h"
#include "Bindings/PluginManager.h"
#include "MonsterConfig.h"
#include "Entities/Player.h"
#include "Blocks/BlockHandler.h"
#include "Items/ItemHandler.h"
#include "Chunk.h"
#include "Protocol/ProtocolRecognizer.h" // for protocol version constants
#include "CommandOutput.h"
#include "DeadlockDetect.h"
#include "LoggerListeners.h"
#include "BuildInfo.h"
#include "IniFile.h"
#include "OverridesSettingsRepository.h"
#include "Logger.h"
#include "ClientHandle.h"
cRoot * cRoot::s_Root = nullptr;
cRoot::cRoot(void) :
m_pDefaultWorld(nullptr),
m_Server(nullptr),
m_MonsterConfig(nullptr),
m_CraftingRecipes(nullptr),
m_FurnaceRecipe(nullptr),
m_BrewingRecipes(nullptr),
m_WebAdmin(nullptr),
m_PluginManager(nullptr),
m_MojangAPI(nullptr)
{
s_Root = this;
m_InputThreadRunFlag.clear();
}
cRoot::~cRoot()
{
s_Root = nullptr;
}
void cRoot::InputThread(cRoot & a_Params)
{
cLogCommandOutputCallback Output;
AString Command;
while (a_Params.m_InputThreadRunFlag.test_and_set() && std::cin.good())
{
#ifndef _WIN32
timeval Timeout{ 0, 0 };
Timeout.tv_usec = 100 * 1000; // 100 msec
fd_set ReadSet;
FD_ZERO(&ReadSet);
FD_SET(STDIN_FILENO, &ReadSet);
if (select(STDIN_FILENO + 1, &ReadSet, nullptr, nullptr, &Timeout) <= 0)
{
// Don't call getline because there's nothing to read
continue;
}
#endif
std::getline(std::cin, Command);
if (!a_Params.m_InputThreadRunFlag.test_and_set())
{
// Already shutting down, can't execute commands
break;
}
if (!Command.empty())
{
// Execute and clear command string when submitted
a_Params.ExecuteConsoleCommand(TrimString(Command), Output);
}
}
// We have come here because the std::cin has received an EOF / a terminate signal has been sent, and the server is still running
// Ignore this when running as a service, cin was never opened in that case
if (!std::cin.good() && !m_RunAsService)
{
// Stop the server:
a_Params.QueueExecuteConsoleCommand("stop");
}
}
void cRoot::Start(std::unique_ptr<cSettingsRepositoryInterface> a_OverridesRepo)
{
#ifdef _WIN32
HMENU ConsoleMenu = GetSystemMenu(GetConsoleWindow(), FALSE);
EnableMenuItem(ConsoleMenu, SC_CLOSE, MF_GRAYED); // Disable close button when starting up; it causes problems with our CTRL-CLOSE handling
#endif
auto consoleLogListener = MakeConsoleListener(m_RunAsService);
auto consoleAttachment = cLogger::GetInstance().AttachListener(std::move(consoleLogListener));
cLogger::cAttachment fileAttachment;
if (!a_OverridesRepo->HasValue("Server","DisableLogFile"))
{
auto fileLogListenerRet = MakeFileListener();
if (!fileLogListenerRet.first)
{
m_TerminateEventRaised = true;
LOGERROR("Failed to open log file, aborting");
return;
}
fileAttachment = cLogger::GetInstance().AttachListener(std::move(fileLogListenerRet.second));
}
LOG("--- Started Log ---");
#ifdef BUILD_ID
LOG("Cuberite " BUILD_SERIES_NAME " build id: " BUILD_ID);
LOG("from commit id: " BUILD_COMMIT_ID " built at: " BUILD_DATETIME);
#endif
cDeadlockDetect dd;
auto BeginTime = std::chrono::steady_clock::now();
LoadGlobalSettings();
LOG("Creating new server instance...");
m_Server = new cServer();
LOG("Reading server config...");
m_SettingsFilename = "settings.ini";
if (a_OverridesRepo->HasValue("Server","ConfigFile"))
{
m_SettingsFilename = a_OverridesRepo->GetValue("Server","ConfigFile");
}
auto IniFile = cpp14::make_unique<cIniFile>();
bool IsNewIniFile = !IniFile->ReadFile(m_SettingsFilename);
if (IsNewIniFile)
{
LOGWARN("Regenerating settings.ini, all settings will be reset");
IniFile->AddHeaderComment(" This is the main server configuration");
IniFile->AddHeaderComment(" Most of the settings here can be configured using the webadmin interface, if enabled in webadmin.ini");
}
auto settingsRepo = cpp14::make_unique<cOverridesSettingsRepository>(std::move(IniFile), std::move(a_OverridesRepo));
LOG("Starting server...");
// cClientHandle::FASTBREAK_PERCENTAGE = settingsRepo->GetValueSetI("AntiCheat", "FastBreakPercentage", 97) / 100.0f;
cClientHandle::FASTBREAK_PERCENTAGE = 0; // AntiCheat disabled due to bugs. We will enabled it once they are fixed. See #3506.
m_MojangAPI = new cMojangAPI;
bool ShouldAuthenticate = settingsRepo->GetValueSetB("Authentication", "Authenticate", true);
m_MojangAPI->Start(*settingsRepo, ShouldAuthenticate); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init
if (!m_Server->InitServer(*settingsRepo, ShouldAuthenticate))
{
settingsRepo->Flush();
LOGERROR("Failure starting server, aborting...");
return;
}
m_WebAdmin = new cWebAdmin();
m_WebAdmin->Init();
LOGD("Loading settings...");
m_RankManager.reset(new cRankManager());
m_RankManager->Initialize(*m_MojangAPI);
m_CraftingRecipes = new cCraftingRecipes();
m_FurnaceRecipe = new cFurnaceRecipe();
m_BrewingRecipes.reset(new cBrewingRecipes());
LOGD("Loading worlds...");
LoadWorlds(dd, *settingsRepo, IsNewIniFile);
LOGD("Loading plugin manager...");
m_PluginManager = new cPluginManager(dd);
m_PluginManager->ReloadPluginsNow(*settingsRepo);
LOGD("Loading MonsterConfig...");
m_MonsterConfig = new cMonsterConfig;
// This sets stuff in motion
LOGD("Starting Authenticator...");
m_Authenticator.Start(*settingsRepo);
LOGD("Starting worlds...");
StartWorlds(dd);
if (settingsRepo->GetValueSetB("DeadlockDetect", "Enabled", true))
{
LOGD("Starting deadlock detector...");
dd.Start(settingsRepo->GetValueSetI("DeadlockDetect", "IntervalSec", 20));
}
settingsRepo->Flush();
LOGD("Finalising startup...");
if (m_Server->Start())
{
m_WebAdmin->Start();
LOGD("Starting InputThread...");
try
{
m_InputThreadRunFlag.test_and_set();
m_InputThread = std::thread(InputThread, std::ref(*this));
}
catch (std::system_error & a_Exception)
{
LOGERROR("cRoot::Start (std::thread) error %i: could not construct input thread; %s", a_Exception.code().value(), a_Exception.what());
}
LOG("Startup complete, took %ldms!", static_cast<long int>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - BeginTime).count()));
// Save the current time
m_StartTime = std::chrono::steady_clock::now();
#ifdef _WIN32
EnableMenuItem(ConsoleMenu, SC_CLOSE, MF_ENABLED); // Re-enable close button
#endif
for (;;)
{
m_StopEvent.Wait();
break;
}
// Stop the server:
m_WebAdmin->Stop();
LOG("Shutting down server...");
m_Server->Shutdown();
} // if (m_Server->Start()
else
{
cRoot::m_TerminateEventRaised = true;
#ifdef _WIN32
EnableMenuItem(ConsoleMenu, SC_CLOSE, MF_ENABLED); // Re-enable close button
#endif
}
delete m_MojangAPI; m_MojangAPI = nullptr;
LOGD("Shutting down deadlock detector...");
dd.Stop();
LOGD("Stopping world threads...");
StopWorlds(dd);
LOGD("Stopping authenticator...");
m_Authenticator.Stop();
LOGD("Freeing MonsterConfig...");
delete m_MonsterConfig; m_MonsterConfig = nullptr;
delete m_WebAdmin; m_WebAdmin = nullptr;
LOGD("Unloading recipes...");
delete m_FurnaceRecipe; m_FurnaceRecipe = nullptr;
delete m_CraftingRecipes; m_CraftingRecipes = nullptr;
LOG("Unloading worlds...");
UnloadWorlds();
LOGD("Stopping plugin manager...");
delete m_PluginManager; m_PluginManager = nullptr;
cItemHandler::Deinit();
LOG("Cleaning up...");
delete m_Server; m_Server = nullptr;
m_InputThreadRunFlag.clear();
#ifdef _WIN32
DWORD Length;
INPUT_RECORD Record
{
KEY_EVENT,
{
{
TRUE,
1,
VK_RETURN,
static_cast<WORD>(MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC)),
{ { VK_RETURN } },
0
}
}
};
// Can't kill the input thread since it breaks cin (getline doesn't block / receive input on restart)
// Apparently no way to unblock getline
// Only thing I can think of for now
if (WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &Record, 1, &Length) == 0)
{
LOGWARN("Couldn't notify the input thread; the server will hang before shutdown!");
m_TerminateEventRaised = true;
m_InputThread.detach();
}
else
{
m_InputThread.join();
}
#else
m_InputThread.join();
#endif
if (m_TerminateEventRaised)
{
LOG("Shutdown successful!");
}
else
{
LOG("Shutdown successful - restarting...");
}
LOG("--- Stopped Log ---");
}
void cRoot::StopServer()
{
// Kick all players from the server with custom disconnect message
bool SentDisconnect = false;
cRoot::Get()->ForEachPlayer([&](cPlayer & a_Player)
{
a_Player.GetClientHandlePtr()->Kick(m_Server->GetShutdownMessage());
SentDisconnect = true;
return false;
}
);
if (SentDisconnect)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
m_TerminateEventRaised = true;
m_StopEvent.Set();
m_InputThreadRunFlag.clear();
}
void cRoot::LoadGlobalSettings()
{
// Nothing needed yet
}
void cRoot::LoadWorlds(cDeadlockDetect & a_dd, cSettingsRepositoryInterface & a_Settings, bool a_IsNewIniFile)
{
if (a_IsNewIniFile)
{
a_Settings.AddValue("Worlds", "DefaultWorld", "world");
a_Settings.AddValue("Worlds", "World", "world_nether");
a_Settings.AddValue("Worlds", "World", "world_the_end");
a_Settings.AddValue("WorldPaths", "world", "world");
a_Settings.AddValue("WorldPaths", "world_nether", "world_nether");
a_Settings.AddValue("WorldPaths", "world_the_end", "world_the_end");
AStringVector WorldNames{ "world", "world_nether", "world_the_end" };
m_pDefaultWorld = new cWorld("world", "world", a_dd, WorldNames);
m_WorldsByName["world"] = m_pDefaultWorld;
m_WorldsByName["world_nether"] = new cWorld("world_nether", "world_nether", a_dd, WorldNames, dimNether, "world");
m_WorldsByName["world_the_end"] = new cWorld("world_the_end", "world_the_end", a_dd, WorldNames, dimEnd, "world");
return;
}
// Build a list of all world names
auto Worlds = a_Settings.GetValues("Worlds");
AStringVector WorldNames(Worlds.size());
for (const auto & World : Worlds)
{
WorldNames.push_back(World.second);
}
// Get the default world
AString DefaultWorldName = a_Settings.GetValueSet("Worlds", "DefaultWorld", "world");
AString DefaultWorldPath = a_Settings.GetValueSet("WorldPaths", DefaultWorldName, DefaultWorldName);
m_pDefaultWorld = new cWorld(DefaultWorldName.c_str(), DefaultWorldPath.c_str(), a_dd, WorldNames);
m_WorldsByName[ DefaultWorldName ] = m_pDefaultWorld;
// Then load the other worlds
if (Worlds.size() <= 0)
{
return;
}
/* Here are the world creation rules. Note that these only apply for a world which is in settings.ini but has no world.ini file.
If an ini file is present, it overrides the world linkages and the dimension type in cWorld::start()
The creation rules are as follows:
- If a world exists in settings.ini but has no world.ini, then:
- If the world name is x_nether, create a world.ini with the dimension type "nether".
- If a world called x exists, set it as x_nether's overworld.
- Otherwise set the default world as x_nether's overworld.
- If the world name is x_the_end or x_end, create a world.ini with the dimension type "end".
- If a world called x exists, set it as x_the_end's overworld.
- Otherwise set the default world as x_the_end's overworld.
- If the world name is x (and doesn't end with _the_end, _end or _nether)
- Create a world.ini with a dimension type of "overworld".
- If a world called x_nether exists, set it as x's nether world.
- Otherwise set x's nether world to blank.h
- If a world called x_the_end or x_end exists, set it as x's end world.
- Otherwise set x's nether world to blank.
*/
bool FoundAdditionalWorlds = false;
for (auto WorldNameValue : Worlds)
{
AString ValueName = WorldNameValue.first;
if (ValueName.compare("World") != 0)
{
continue;
}
AString WorldName = WorldNameValue.second;
if (WorldName.empty())
{
continue;
}
FoundAdditionalWorlds = true;
cWorld * NewWorld;
AString LowercaseName = StrToLower(WorldName);
AString WorldPath = a_Settings.GetValueSet("WorldPaths", WorldName, WorldName);
AString NetherAppend = "_nether";
AString EndAppend1 = "_the_end";
AString EndAppend2 = "_end";
// The default world is an overworld with no links
eDimension Dimension = dimOverworld;
AString LinkTo = "";
// if the world is called x_nether
if ((LowercaseName.size() > NetherAppend.size()) && (LowercaseName.substr(LowercaseName.size() - NetherAppend.size()) == NetherAppend))
{
// The world is called x_nether, see if a world called x exists. If yes, choose it as the linked world,
// otherwise, choose the default world as the linked world.
// As before, any ini settings will completely override this if an ini is already present.
LinkTo = WorldName.substr(0, WorldName.size() - NetherAppend.size());
if (GetWorld(LinkTo) == nullptr)
{
LinkTo = DefaultWorldName;
}
Dimension = dimNether;
}
// if the world is called x_the_end
else if ((LowercaseName.size() > EndAppend1.size()) && (LowercaseName.substr(LowercaseName.size() - EndAppend1.size()) == EndAppend1))
{
// The world is called x_the_end, see if a world called x exists. If yes, choose it as the linked world,
// otherwise, choose the default world as the linked world.
// As before, any ini settings will completely override this if an ini is already present.
LinkTo = WorldName.substr(0, WorldName.size() - EndAppend1.size());
if (GetWorld(LinkTo) == nullptr)
{
LinkTo = DefaultWorldName;
}
Dimension = dimEnd;
}
// if the world is called x_end
else if ((LowercaseName.size() > EndAppend2.size()) && (LowercaseName.substr(LowercaseName.size() - EndAppend2.size()) == EndAppend2))
{
// The world is called x_end, see if a world called x exists. If yes, choose it as the linked world,
// otherwise, choose the default world as the linked world.
// As before, any ini settings will completely override this if an ini is already present.
LinkTo = WorldName.substr(0, WorldName.size() - EndAppend2.size());
if (GetWorld(LinkTo) == nullptr)
{
LinkTo = DefaultWorldName;
}
Dimension = dimEnd;
}
NewWorld = new cWorld(WorldName.c_str(), WorldPath.c_str(), a_dd, WorldNames, Dimension, LinkTo);
m_WorldsByName[WorldName] = NewWorld;
} // for i - Worlds
if (!FoundAdditionalWorlds)
{
if (a_Settings.GetKeyComment("Worlds", 0) != " World=secondworld")
{
a_Settings.DeleteKeyComment("Worlds", 0);
a_Settings.AddKeyComment("Worlds", " World=secondworld");
}
}
}
void cRoot::StartWorlds(cDeadlockDetect & a_DeadlockDetect)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
itr->second->Start();
itr->second->InitializeSpawn();
m_PluginManager->CallHookWorldStarted(*itr->second);
}
}
void cRoot::StopWorlds(cDeadlockDetect & a_DeadlockDetect)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
itr->second->Stop(a_DeadlockDetect);
}
}
void cRoot::UnloadWorlds(void)
{
m_pDefaultWorld = nullptr;
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
delete itr->second;
}
m_WorldsByName.clear();
}
cWorld * cRoot::GetDefaultWorld()
{
return m_pDefaultWorld;
}
cWorld * cRoot::GetWorld(const AString & a_WorldName)
{
WorldMap::iterator itr = m_WorldsByName.find(a_WorldName);
if (itr != m_WorldsByName.end())
{
return itr->second;
}
return nullptr;
}
bool cRoot::ForEachWorld(cWorldListCallback a_Callback)
{
for (auto & World : m_WorldsByName)
{
if (World.second != nullptr)
{
if (a_Callback(*World.second))
{
return false;
}
}
}
return true;
}
void cRoot::TickCommands(void)
{
// Execute any pending commands:
cCommandQueue PendingCommands;
{
cCSLock Lock(m_CSPendingCommands);
std::swap(PendingCommands, m_PendingCommands);
}
for (cCommandQueue::iterator itr = PendingCommands.begin(), end = PendingCommands.end(); itr != end; ++itr)
{
ExecuteConsoleCommand(itr->m_Command, *(itr->m_Output));
}
}
void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
// Put the command into a queue (Alleviates FS #363):
cCSLock Lock(m_CSPendingCommands);
m_PendingCommands.emplace_back(a_Cmd, &a_Output);
}
void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd)
{
// Put the command into a queue (Alleviates FS #363):
cCSLock Lock(m_CSPendingCommands);
m_PendingCommands.push_back(cCommand(a_Cmd, new cLogCommandDeleteSelfOutputCallback));
}
void cRoot::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
// Some commands are built-in:
if (a_Cmd == "stop")
{
StopServer();
return;
}
else if (a_Cmd == "restart")
{
m_StopEvent.Set();
m_InputThreadRunFlag.clear();
return;
}
LOG("Executing console command: \"%s\"", a_Cmd.c_str());
m_Server->ExecuteConsoleCommand(a_Cmd, a_Output);
}
void cRoot::KickUser(int a_ClientID, const AString & a_Reason)
{
m_Server->KickUser(a_ClientID, a_Reason);
}
void cRoot::AuthenticateUser(int a_ClientID, const AString & a_Name, const cUUID & a_UUID, const Json::Value & a_Properties)
{
m_Server->AuthenticateUser(a_ClientID, a_Name, a_UUID, a_Properties);
}
int cRoot::GetTotalChunkCount(void)
{
int res = 0;
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
res += itr->second->GetNumChunks();
}
return res;
}
void cRoot::SaveAllChunks(void)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
itr->second->QueueSaveAllChunks();
}
}
void cRoot::SetSavingEnabled(bool a_SavingEnabled)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
itr->second->SetSavingEnabled(a_SavingEnabled);
}
}
void cRoot::SendPlayerLists(cPlayer * a_DestPlayer)
{
for (const auto & itr : m_WorldsByName)
{
itr.second->SendPlayerList(a_DestPlayer);
} // for itr - m_WorldsByName[]
}
void cRoot::BroadcastPlayerListsAddPlayer(const cPlayer & a_Player, const cClientHandle * a_Exclude)
{
for (const auto & itr : m_WorldsByName)
{
itr.second->BroadcastPlayerListAddPlayer(a_Player);
} // for itr - m_WorldsByName[]
}
void cRoot::BroadcastPlayerListsRemovePlayer(const cPlayer & a_Player, const cClientHandle * a_Exclude)
{
for (const auto & itr : m_WorldsByName)
{
itr.second->BroadcastPlayerListRemovePlayer(a_Player);
} // for itr - m_WorldsByName[]
}
void cRoot::BroadcastChat(const AString & a_Message, eMessageType a_ChatPrefix)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
{
itr->second->BroadcastChat(a_Message, nullptr, a_ChatPrefix);
} // for itr - m_WorldsByName[]
}
void cRoot::BroadcastChat(const cCompositeChat & a_Message)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
{
itr->second->BroadcastChat(a_Message);
} // for itr - m_WorldsByName[]
}
bool cRoot::ForEachPlayer(cPlayerListCallback a_Callback)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(), itr2 = itr; itr != m_WorldsByName.end(); itr = itr2)
{
++itr2;
if (!itr->second->ForEachPlayer(a_Callback))
{
return false;
}
}
return true;
}
bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback a_Callback)
{
class cCallback
{
size_t m_BestRating;
size_t m_NameLength;
const AString m_PlayerName;
public:
bool operator () (cPlayer & a_Player)
{
size_t Rating = RateCompareString (m_PlayerName, a_Player.GetName());
if ((Rating > 0) && (Rating >= m_BestRating))
{
m_BestMatch = a_Player.GetName();
if (Rating > m_BestRating)
{
m_NumMatches = 0;
}
m_BestRating = Rating;
++m_NumMatches;
}
if (Rating == m_NameLength) // Perfect match
{
return true;
}
return false;
}
cCallback (const AString & a_CBPlayerName) :
m_BestRating(0),
m_NameLength(a_CBPlayerName.length()),
m_PlayerName(a_CBPlayerName),
m_BestMatch(),
m_NumMatches(0)
{}
AString m_BestMatch;
unsigned m_NumMatches;
} Callback (a_PlayerName);
ForEachPlayer(Callback);
if (Callback.m_NumMatches == 1)
{
return DoWithPlayer(Callback.m_BestMatch, a_Callback);
}
return false;
}
bool cRoot::DoWithPlayerByUUID(const cUUID & a_PlayerUUID, cPlayerListCallback a_Callback)
{
for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
{
if (itr->second->DoWithPlayerByUUID(a_PlayerUUID, a_Callback))
{
return true;
}
}
return false;
}
bool cRoot::DoWithPlayer(const AString & a_PlayerName, cPlayerListCallback a_Callback)
{
for (auto World : m_WorldsByName)
{
if (World.second->DoWithPlayer(a_PlayerName, a_Callback))
{
return true;
}
}
return false;
}
AString cRoot::GetProtocolVersionTextFromInt(int a_ProtocolVersion)
{
return cProtocolRecognizer::GetVersionTextFromInt(a_ProtocolVersion);
}
int cRoot::GetVirtualRAMUsage(void)
{
#ifdef _WIN32
PROCESS_MEMORY_COUNTERS_EX pmc;
if (GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc)))
{
return (int)(pmc.PrivateUsage / 1024);
}
return -1;
#elif defined(__linux__)
// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
std::ifstream StatFile("/proc/self/status");
if (!StatFile.good())
{
return -1;
}
while (StatFile.good())
{
AString Line;
std::getline(StatFile, Line);
if (strncmp(Line.c_str(), "VmSize:", 7) == 0)
{
int res = atoi(Line.c_str() + 8);
return (res == 0) ? -1 : res; // If parsing failed, return -1
}
}
return -1;
#elif defined (__APPLE__)
// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS == task_info(
mach_task_self(),
TASK_BASIC_INFO,
reinterpret_cast<task_info_t>(&t_info),
&t_info_count
))
{
return static_cast<int>(t_info.virtual_size / 1024);
}
return -1;
#else
LOGINFO("%s: Unknown platform, cannot query memory usage", __FUNCTION__);
return -1;
#endif
}
int cRoot::GetPhysicalRAMUsage(void)
{
#ifdef _WIN32
PROCESS_MEMORY_COUNTERS pmc;
if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
{
return (int)(pmc.WorkingSetSize / 1024);
}
return -1;
#elif defined(__linux__)
// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
std::ifstream StatFile("/proc/self/status");
if (!StatFile.good())
{
return -1;
}
while (StatFile.good())
{
AString Line;
std::getline(StatFile, Line);
if (strncmp(Line.c_str(), "VmRSS:", 6) == 0)
{
int res = atoi(Line.c_str() + 7);
return (res == 0) ? -1 : res; // If parsing failed, return -1
}
}
return -1;
#elif defined (__APPLE__)
// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS == task_info(
mach_task_self(),
TASK_BASIC_INFO,
reinterpret_cast<task_info_t>(&t_info),
&t_info_count
))
{
return static_cast<int>(t_info.resident_size / 1024);
}
return -1;
#else
LOGINFO("%s: Unknown platform, cannot query memory usage", __FUNCTION__);
return -1;
#endif
}
void cRoot::LogChunkStats(cCommandOutputCallback & a_Output)
{
int SumNumValid = 0;
int SumNumDirty = 0;
int SumNumInLighting = 0;
int SumNumInGenerator = 0;
int SumMem = 0;
for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
{
cWorld * World = itr->second;
int NumInGenerator = World->GetGeneratorQueueLength();
int NumInSaveQueue = static_cast<int>(World->GetStorageSaveQueueLength());
int NumInLoadQueue = static_cast<int>(World->GetStorageLoadQueueLength());
int NumValid = 0;
int NumDirty = 0;
int NumInLighting = 0;
World->GetChunkStats(NumValid, NumDirty, NumInLighting);
a_Output.Out("World %s:", World->GetName().c_str());
a_Output.Out(" Num loaded chunks: %d", NumValid);
a_Output.Out(" Num dirty chunks: %d", NumDirty);
a_Output.Out(" Num chunks in lighting queue: %d", NumInLighting);
a_Output.Out(" Num chunks in generator queue: %d", NumInGenerator);
a_Output.Out(" Num chunks in storage load queue: %d", NumInLoadQueue);
a_Output.Out(" Num chunks in storage save queue: %d", NumInSaveQueue);
int Mem = NumValid * static_cast<int>(sizeof(cChunk));
a_Output.Out(" Memory used by chunks: %d KiB (%d MiB)", (Mem + 1023) / 1024, (Mem + 1024 * 1024 - 1) / (1024 * 1024));
a_Output.Out(" Per-chunk memory size breakdown:");
a_Output.Out(" block types: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BlockTypes), (sizeof(cChunkDef::BlockTypes) + 1023) / 1024);
a_Output.Out(" block metadata: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BlockNibbles), (sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
a_Output.Out(" block lighting: %6zu bytes (%3zu KiB)", 2 * sizeof(cChunkDef::BlockNibbles), (2 * sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
a_Output.Out(" heightmap: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::HeightMap), (sizeof(cChunkDef::HeightMap) + 1023) / 1024);
a_Output.Out(" biomemap: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BiomeMap), (sizeof(cChunkDef::BiomeMap) + 1023) / 1024);
SumNumValid += NumValid;
SumNumDirty += NumDirty;
SumNumInLighting += NumInLighting;
SumNumInGenerator += NumInGenerator;
SumMem += Mem;
}
a_Output.Out("Totals:");
a_Output.Out(" Num loaded chunks: %d", SumNumValid);
a_Output.Out(" Num dirty chunks: %d", SumNumDirty);
a_Output.Out(" Num chunks in lighting queue: %d", SumNumInLighting);
a_Output.Out(" Num chunks in generator queue: %d", SumNumInGenerator);
a_Output.Out(" Memory used by chunks: %d KiB (%d MiB)", (SumMem + 1023) / 1024, (SumMem + 1024 * 1024 - 1) / (1024 * 1024));
}
int cRoot::GetFurnaceFuelBurnTime(const cItem & a_Fuel)
{
cFurnaceRecipe * FR = Get()->GetFurnaceRecipe();
return FR->GetBurnTime(a_Fuel);
}
AStringVector cRoot::GetPlayerTabCompletionMultiWorld(const AString & a_Text)
{
AStringVector Results;
ForEachWorld([&](cWorld & a_World)
{
a_World.TabCompleteUserName(a_Text, Results);
return false;
}
);
return Results;
}
| {
"content_hash": "680f84dbf9e1acbe9142ce29fd562937",
"timestamp": "",
"source": "github",
"line_count": 1093,
"max_line_length": 171,
"avg_line_length": 25.089661482159194,
"alnum_prop": 0.6877803303796084,
"repo_name": "nounoursheureux/MCServer",
"id": "b35d7229bc5159617effd5855580b45e8b618fd3",
"size": "27423",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Root.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6949"
},
{
"name": "C",
"bytes": "6523350"
},
{
"name": "C++",
"bytes": "6170407"
},
{
"name": "CMake",
"bytes": "89390"
},
{
"name": "CSS",
"bytes": "12456"
},
{
"name": "Groff",
"bytes": "1612"
},
{
"name": "HTML",
"bytes": "65997"
},
{
"name": "Java",
"bytes": "22153"
},
{
"name": "Lua",
"bytes": "760963"
},
{
"name": "Makefile",
"bytes": "17573"
},
{
"name": "Objective-C",
"bytes": "30562"
},
{
"name": "Python",
"bytes": "4892"
},
{
"name": "QMake",
"bytes": "2927"
},
{
"name": "Shell",
"bytes": "8036"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class SelectionRing : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| {
"content_hash": "d65d5bb62e6f4f74db77abcf1fa9e335",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 44,
"avg_line_length": 14,
"alnum_prop": 0.6857142857142857,
"repo_name": "subdigital/blades-edge",
"id": "f452f4e3f0224e9d502cf7ead45dd186b7825dc7",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/SelectionRing.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "25329"
}
],
"symlink_target": ""
} |
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/primary_dark</item> <!-- Setting this dark lets the recent tab title bar color be darker. We just need to explicity state the color in the toolbar.xml if we want the primary color to be on the toolbar -->
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
<item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorPrimary">@color/primary</item>
<item name="colorAccent">@color/accent</item>
</style>
</resources>
| {
"content_hash": "b175e1dca07071ef01b31ad0dc707561",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 245,
"avg_line_length": 44.80769230769231,
"alnum_prop": 0.6824034334763949,
"repo_name": "DoubleElite/EzCaloriez",
"id": "f7c52b14d7fa69f0b68afeddc1a51bac040fc538",
"size": "1165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/styles.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "28299"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom"
android:background="@drawable/start_background">
</LinearLayout> | {
"content_hash": "202aa9670325c7e4cb931364acdeba72",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 72,
"avg_line_length": 41.888888888888886,
"alnum_prop": 0.6286472148541115,
"repo_name": "air23zj/DuckHuntRobotics",
"id": "1d5769ae7a9eef8c99dae7e162bab7939f13ea58",
"size": "377",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "res/layout-land/app_start.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "754"
},
{
"name": "C++",
"bytes": "13175"
},
{
"name": "Java",
"bytes": "301239"
}
],
"symlink_target": ""
} |
layout: project
type: project
image: images/projects/project-2/linuxterminal.png
title: Project SmartBoard
permalink: projects/projects/project-2/smartboard
date: 2016-06-21
labels:
- Linux/Ubuntu
- SmartBoard
summary: I helped an Electrical Engineering professor to reinstall SmartBoard drivers and tool on a Linux PC.
---
<img class="ui medium right floated rounded image" src="/images/projects/project-2/linuxterminal.png">
One day, when I came to work, and my boss told me about a professor who asked her to help him set up the SmartBoard that can run on Linux (it used to run on Windows). She said <i>"That's a great opportunity for you to learn to work on Linux, you should give it a try."</i> I guess she's right, and I jumped right in to work on this project.
I had worked on Linux before, but it was the first time that I had total control on a Linux machine that I started from scratch. Because the software for the SmartBoard only work on the 32-bit machine, so I had to reinstall the operating system as well.
Although, we planned to finish this project in two weeks (16 hours), it took us the whole month because Linux was not as easy as I thought it was. In order to install the SmartBoard software, I had to modify the keys, extract the packages, sign the packages with my own secret keys...and more things that I never know before.
In this project I gained experience with how to work with Linux, about how to install packages after packages until it meets the requirement for the package that I wanted to install. It wasn't a pleasant journey, but I'm glad I was able to learn enough to succeed.
| {
"content_hash": "5965f936aac0c4a7e9c14c64f16fb4f3",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 340,
"avg_line_length": 81.05,
"alnum_prop": 0.7785317705120296,
"repo_name": "jonathanMNg/jonathanmng.github.io",
"id": "c1f2636b9e736532485757b77e73216e3d8d3e93",
"size": "1625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/project-2.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1490781"
},
{
"name": "HTML",
"bytes": "38688"
},
{
"name": "JavaScript",
"bytes": "2901026"
},
{
"name": "Ruby",
"bytes": "2320"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Wed Nov 05 20:55:14 EST 2014 -->
<title>Int32Serializer (apache-cassandra API)</title>
<meta name="date" content="2014-11-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Int32Serializer (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/Int32Serializer.html">Use</a></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><a href="../../../../org/apache/cassandra/serializers/InetAddressSerializer.html" title="class in org.apache.cassandra.serializers"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/serializers/IntegerSerializer.html" title="class in org.apache.cassandra.serializers"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/serializers/Int32Serializer.html" target="_top">Frames</a></li>
<li><a href="Int32Serializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All 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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.serializers</div>
<h2 title="Class Int32Serializer" class="title">Class Int32Serializer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.serializers.Int32Serializer</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">Int32Serializer</span>
extends java.lang.Object
implements <a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html" title="class in org.apache.cassandra.serializers">Int32Serializer</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#instance">instance</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#Int32Serializer()">Int32Serializer</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Integer</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#deserialize(java.nio.ByteBuffer)">deserialize</a></strong>(java.nio.ByteBuffer bytes)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.Class<java.lang.Integer></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#getType()">getType</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.nio.ByteBuffer</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#serialize(java.lang.Integer)">serialize</a></strong>(java.lang.Integer value)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#toString(java.lang.Integer)">toString</a></strong>(java.lang.Integer value)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html#validate(java.nio.ByteBuffer)">validate</a></strong>(java.nio.ByteBuffer bytes)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="instance">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>instance</h4>
<pre>public static final <a href="../../../../org/apache/cassandra/serializers/Int32Serializer.html" title="class in org.apache.cassandra.serializers">Int32Serializer</a> instance</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Int32Serializer()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Int32Serializer</h4>
<pre>public Int32Serializer()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="deserialize(java.nio.ByteBuffer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>deserialize</h4>
<pre>public java.lang.Integer deserialize(java.nio.ByteBuffer bytes)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html#deserialize(java.nio.ByteBuffer)">deserialize</a></code> in interface <code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></code></dd>
</dl>
</li>
</ul>
<a name="serialize(java.lang.Integer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>serialize</h4>
<pre>public java.nio.ByteBuffer serialize(java.lang.Integer value)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html#serialize(T)">serialize</a></code> in interface <code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></code></dd>
</dl>
</li>
</ul>
<a name="validate(java.nio.ByteBuffer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>validate</h4>
<pre>public void validate(java.nio.ByteBuffer bytes)
throws <a href="../../../../org/apache/cassandra/serializers/MarshalException.html" title="class in org.apache.cassandra.serializers">MarshalException</a></pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html#validate(java.nio.ByteBuffer)">validate</a></code> in interface <code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/MarshalException.html" title="class in org.apache.cassandra.serializers">MarshalException</a></code></dd></dl>
</li>
</ul>
<a name="toString(java.lang.Integer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString(java.lang.Integer value)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html#toString(T)">toString</a></code> in interface <code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></code></dd>
</dl>
</li>
</ul>
<a name="getType()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getType</h4>
<pre>public java.lang.Class<java.lang.Integer> getType()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html#getType()">getType</a></code> in interface <code><a href="../../../../org/apache/cassandra/serializers/TypeSerializer.html" title="interface in org.apache.cassandra.serializers">TypeSerializer</a><java.lang.Integer></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/Int32Serializer.html">Use</a></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><a href="../../../../org/apache/cassandra/serializers/InetAddressSerializer.html" title="class in org.apache.cassandra.serializers"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/serializers/IntegerSerializer.html" title="class in org.apache.cassandra.serializers"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/serializers/Int32Serializer.html" target="_top">Frames</a></li>
<li><a href="Int32Serializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All 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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "3a546537421db3401d1e6ef075882ba3",
"timestamp": "",
"source": "github",
"line_count": 372,
"max_line_length": 354,
"avg_line_length": 40.005376344086024,
"alnum_prop": 0.6603279129149308,
"repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet",
"id": "d0eaaebbacd2b499d0585db3f3457312c2c667bd",
"size": "14882",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apache-cassandra-2.1.2/javadoc/org/apache/cassandra/serializers/Int32Serializer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "59670"
},
{
"name": "PowerShell",
"bytes": "37758"
},
{
"name": "Python",
"bytes": "622552"
},
{
"name": "Shell",
"bytes": "100474"
},
{
"name": "Thrift",
"bytes": "78926"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class ContextPropagationTest
{
MockServiceHelper helper;
Server server;
Channel channel;
[SetUp]
public void Init()
{
helper = new MockServiceHelper();
server = helper.GetServer();
server.Start();
channel = helper.GetChannel();
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
server.ShutdownAsync().Wait();
}
[Test]
public async Task PropagateCancellation()
{
var readyToCancelTcs = new TaskCompletionSource<object>();
var successTcs = new TaskCompletionSource<string>();
helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) =>
{
readyToCancelTcs.SetResult(null); // child call running, ready to parent call
while (!context.CancellationToken.IsCancellationRequested)
{
await Task.Delay(10);
}
successTcs.SetResult("CHILD_CALL_CANCELLED");
return "";
});
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
var propagationToken = context.CreatePropagationToken();
Assert.IsNotNull(propagationToken.AsImplOrNull().ParentCall);
var callOptions = new CallOptions(propagationToken: propagationToken);
try
{
await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
}
catch(RpcException)
{
// Child call will get cancelled, eat the exception.
}
return "";
});
var cts = new CancellationTokenSource();
var parentCall = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token)));
await readyToCancelTcs.Task;
cts.Cancel();
try
{
// cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock.
await parentCall;
Assert.Fail();
}
catch (RpcException)
{
}
Assert.AreEqual("CHILD_CALL_CANCELLED", await successTcs.Task);
}
[Test]
public async Task PropagateDeadline()
{
var deadline = DateTime.UtcNow.AddDays(7);
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.IsTrue(context.Deadline < deadline.AddMinutes(1));
Assert.IsTrue(context.Deadline > deadline.AddMinutes(-1));
return Task.FromResult("PASS");
});
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
Assert.Throws(typeof(ArgumentException), () =>
{
// Trying to override deadline while propagating deadline from parent call will throw.
Calls.BlockingUnaryCall(helper.CreateUnaryCall(
new CallOptions(deadline: DateTime.UtcNow.AddDays(8),
propagationToken: context.CreatePropagationToken())), "");
});
var callOptions = new CallOptions(propagationToken: context.CreatePropagationToken());
return await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
});
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(deadline: deadline)));
await call.RequestStream.CompleteAsync();
Assert.AreEqual("PASS", await call);
}
[Test]
public async Task SuppressDeadlinePropagation()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.AreEqual(DateTime.MaxValue, context.Deadline);
return Task.FromResult("PASS");
});
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
Assert.IsTrue(context.CancellationToken.CanBeCanceled);
var callOptions = new CallOptions(propagationToken: context.CreatePropagationToken(new ContextPropagationOptions(propagateDeadline: false)));
return await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
});
var cts = new CancellationTokenSource();
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(deadline: DateTime.UtcNow.AddDays(7))));
await call.RequestStream.CompleteAsync();
Assert.AreEqual("PASS", await call);
}
[Test]
public void ForeignPropagationTokenInterpretedAsNull()
{
Assert.IsNull(new ForeignContextPropagationToken().AsImplOrNull());
}
[Test]
public async Task ForeignPropagationTokenIsIgnored()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult("PASS");
});
var callOptions = new CallOptions(propagationToken: new ForeignContextPropagationToken());
await Calls.AsyncUnaryCall(helper.CreateUnaryCall(callOptions), "xyz");
}
// For testing, represents context propagation token that's not generated by Grpc.Core
private class ForeignContextPropagationToken : ContextPropagationToken
{
}
}
}
| {
"content_hash": "d48515532316a6e33c3214ded9b4c7d7",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 157,
"avg_line_length": 38.25766871165644,
"alnum_prop": 0.5846696600384862,
"repo_name": "carl-mastrangelo/grpc",
"id": "4158579194f673909895a95cc32bc63f352728b4",
"size": "6877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/csharp/Grpc.Core.Tests/ContextPropagationTest.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "32274"
},
{
"name": "C",
"bytes": "1677470"
},
{
"name": "C#",
"bytes": "1905512"
},
{
"name": "C++",
"bytes": "30667850"
},
{
"name": "CMake",
"bytes": "624762"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "DTrace",
"bytes": "147"
},
{
"name": "Dockerfile",
"bytes": "153845"
},
{
"name": "Go",
"bytes": "34791"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "6907"
},
{
"name": "JavaScript",
"bytes": "53044"
},
{
"name": "M4",
"bytes": "46911"
},
{
"name": "Makefile",
"bytes": "1151674"
},
{
"name": "Objective-C",
"bytes": "441626"
},
{
"name": "Objective-C++",
"bytes": "37623"
},
{
"name": "PHP",
"bytes": "471571"
},
{
"name": "Python",
"bytes": "2754606"
},
{
"name": "Ruby",
"bytes": "993806"
},
{
"name": "Shell",
"bytes": "429791"
},
{
"name": "Swift",
"bytes": "3516"
},
{
"name": "XSLT",
"bytes": "9673"
}
],
"symlink_target": ""
} |
"""This is a collection of grass-related plugins."""
from __future__ import absolute_import
import os
import os.path as osp
import sys
import subprocess
import sqlite3
try:
import pandas as pd
from pandas import DataFrame
except ImportError:
raise ImportError('The grass plugin requires the pandas package '
'for the GrassAttributeTable plugin. '
'Try pip install pandas')
class GrassSession(object):
"""Open a GRASS session in a mapset without launching GRASS.
To be used as a context. The context variable is the grass.script module::
with GrassSession('path/to/mapset') as grass:
grass.run_command()
Arguments
---------
project_or_gisdb : project | str path
Project instance with the settings (below) or the path to a GRASS
database or straight to the mapset if location and mapset are None.
location, mapset : str, optional
grassbin : str
Name or path of GRASS executable.
Settings
--------
grass_db : str path
Path to grass database.
grass_location : str
Grass location name.
grass_mapset : str
Grass mapset where to write to.
grassbin : str, optional (default=grass)
Name or path of the grass executable.
grass_overwrite : bool, optional
Always overwrite maps.
"""
def __init__(self, project_or_gisdb, location=None, mapset=None,
overwrite=None, verbose=None, grassbin='grass'):
if type(project_or_gisdb) is not str:
self.project = project_or_gisdb
project_or_gisdb = self.project.grass_db
location = location or self.project.grass_location
mapset = mapset or self.project.grass_mapset
if hasattr(self.project, "grassbin"):
grassbin = self.project.grassbin
if hasattr(self.project, "grass_overwrite") and overwrite is None:
overwrite = self.project.grass_overwrite
gisdb = project_or_gisdb
# if gisdb is path to mapset
assert osp.exists(gisdb), 'gisdb doesnt exist: %s' % gisdb
if not location and not mapset:
gisdb = gisdb[:-1] if gisdb.endswith('/') else gisdb
mapset = os.path.basename(gisdb)
dblo = os.path.dirname(gisdb)
location = os.path.basename(dblo)
gisdb = os.path.dirname(dblo)
errmsg = 'location %s doesnt exist.' % location
assert osp.exists(osp.join(gisdb, location)), errmsg
self.gisdb, self.location, self.mapset = gisdb, location, mapset
# query GRASS 7 itself for its GISBASE
errmsg = "%s not found or not executable." % grassbin
assert self._which(grassbin), errmsg
startcmd = [grassbin, '--config', 'path']
p = subprocess.Popen(startcmd, shell=False, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise ImportError("ERROR: Cannot find GRASS GIS 7 start script "
"using %s. Try passing correct grassbin."
% (' '.join(startcmd)))
self.gisbase = out.decode().strip().split('\n')[-1]
userdir = osp.expanduser("~")
self.addonpath = osp.join(userdir, '.grass7', 'addons', 'scripts')
self.python_package = os.path.join(self.gisbase, "etc", "python")
self.overwrite = GrassOverwrite(overwrite, verbose=verbose)
return
def _which(self, program):
fpath, fname = os.path.split(program)
if fpath:
if os.path.isfile(program) and os.access(program, os.X_OK):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return None
def setup(self):
# Set environment variables
os.environ['GISBASE'] = self.gisbase
os.environ['GISDBASE'] = self.gisdb
# add path to GRASS addons depends on build/platform
os.environ['PATH'] += os.pathsep + self.addonpath
sys.path.insert(0, self.python_package)
import grass.script as grass
from grass.script import setup
self.grass = grass
self.rcfile = setup.init(self.gisbase, self.gisdb,
self.location, 'PERMANENT')
# always create mapset if it doesnt exist
if self.mapset != 'PERMANENT':
grass.run_command('g.mapset', mapset=self.mapset, flags='c',
quiet=True)
self.overwrite.__enter__()
return grass
def __enter__(self):
return self.setup()
def clean(self):
# remove .gislock and rc file if exists
env = self.grass.gisenv()
lf = osp.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
'.gislock')
for f in [lf, self.rcfile]:
try:
os.remove(f)
except OSError:
pass
# clean envs
sys.path = [p for p in sys.path if p is not self.python_package]
ps = os.pathsep
rmpaths = [self.addonpath]
paths = os.environ['PATH'].split(ps)
os.environ['PATH'] = ps.join([p for p in paths if p not in rmpaths])
self.overwrite.__exit__()
return
def __exit__(self, *args):
self.clean()
return
class GrassOverwrite(object):
"""Context processor to overwrite GRASS mapsself."""
OVERWRITE = 'GRASS_OVERWRITE'
VERBOSE = "GRASS_VERBOSE"
def __init__(self, overwrite=True, verbose=None):
"""
Arguments
---------
overwrite : bool
Convenience argument to avoid putting the context in if block.
verbose : bool | int(-1 ... 3), optional
Optional verbosity setting in the context.
"""
self.overwrite = bool(overwrite)
self.verbose = int(verbose) if verbose is not None else None
return
def __enter__(self):
GO = self.OVERWRITE
self.is_set = GO in os.environ and os.environ[GO] != '0'
self.verbose_is_set = self.VERBOSE in os.environ
if self.overwrite:
os.environ[GO] = '1'
if self.verbose is not None and not self.verbose_is_set:
os.environ[self.VERBOSE] = str(self.verbose)
return
def __exit__(self, *args):
if not self.is_set and self.overwrite:
os.environ.pop(self.OVERWRITE)
if not self.verbose_is_set and self.verbose is not None:
os.environ.pop(self.VERBOSE)
return
def __bool__(self):
return self.overwrite
def __nonzero__(self):
return self.overwrite
class GrassAttributeTable(DataFrame):
"""A plugin to represent a grass vector attribute table.
This plugin can either be used with a project instance as the first
argument to get the GRASS connection parameters or by specifically stating
the database path. E.g.::
dbpath = 'grassloc/PERMANENT/sqlite/sqlite.db'
table = GrassAttributeTable(vector='test', database=dbpath)
Specify `database` and `table`, if you dont want to rely on grass to get
the table connection parameters.
"""
vector = None
#: Optional
layer = 1
#: Specify a different key index, default is the first column
key = None
#: list, optional subset of columns to read, writing reads+writes full tbl
subset_columns = None
#: optional if it shouldnt call grass to find out
database = None
#: optional if it shouldnt call grass to find out
table = None
#: needed to stop exposing all pd.DataFrame methods
plugin = []
def __init__(self, project=None, **override):
super(GrassAttributeTable, self).__init__()
if type(project) == str:
project, override['vector'] = None, project
self.__dict__.update(override)
self.project = project
em = 'vector (str) needed (others are optional).'
assert type(self.vector) == str, em
nms = self.vector.split('@')
if project and not self.database:
self.mapset = nms[1] if len(nms) > 1 else project.grass_mapset
self.database = osp.join(project.grass_db, project.grass_location,
self.mapset, 'sqlite', 'sqlite.db')
# retrive info in a grass session active
elif os.environ.get('GISRC', None) and not self.database:
import grass.script as grass
con = grass.vector_db(self.vector).get(self.layer, None)
msg = '%s has no sqlite database connection.' % self.vector
assert con and con['driver'] == 'sqlite', msg
self.__dict__.update(
{k: con[k] for k in ['table', 'database', 'key']})
else:
assert self.database, 'Without project, database must be given.'
self.table = self.table or nms[0]
self.key = self.key or 0
# fill dataframe
self.read()
return
def read(self):
"""Read table from db."""
sc = self.subset_columns
cols = ','.join(sc) if sc else '*'
with self.dbconnection as con:
tbl = pd.read_sql('select %s from %s;' % (cols, self.table), con)
self.key = tbl.columns[self.key] if type(self.key) == int else self.key
tbl.set_index(self.key, inplace=True, verify_integrity=True)
# fill DataFrame
super(GrassAttributeTable, self).__init__(tbl)
return
@property
def dbconnection(self):
return sqlite3.connect(self.database)
def write(self):
"""Save table back to GRASS sqlite3 database.
"""
cleantbl = self
with self.dbconnection as con:
if self.subset_columns: # read other columns
tbl = pd.read_sql('select * from %s;' % self.table, con)
tbl.set_index(self.key, inplace=True, verify_integrity=True)
tbl[cleantbl.columns] = cleantbl
cleantbl = tbl
cleantbl.to_sql(self.table, con, if_exists='replace')
return
class GrassModulePlugin(object):
"""A representation of a grass module that takes arguments from either
project settings specified by ``argument_setting`` or its own attributes.
"""
#: Name of module
module = None
#: name of dictionary project setting to look for default arguments
argument_setting = None
def __init__(self, project):
self.project = project
errmsg = '%s.module has to be set.' % self.__class__.__name__
assert self.module, errmsg
return
def create(self, verbose=True, **moduleargs):
"""Run the related grass module.
Arguments
---------
verbose : bool
Print all module output. If False, only WARNINGS and ERRORS are
printed at the end.
**moduleargs :
Override any arguments of the module alredy set in settings.
"""
args = {}
aset = self.argument_setting
if aset and hasattr(self.project, aset):
arg_setting = getattr(self.project, aset)
arg_setting = arg_setting if type(arg_setting) == dict else {}
else:
arg_setting = {}
with GrassSession(self.project):
from grass.pygrass.modules import Module
module = Module(self.module, run_=False)
for p in module.params_list:
if p.name in moduleargs:
args[p.name] = moduleargs[p.name]
elif p.name in arg_setting:
args[p.name] = arg_setting[p.name]
elif hasattr(self, p.name):
args[p.name] = getattr(self, p.name)
elif p.required and not p.default:
em = p.name + ' argument is required by ' + self.module
raise AttributeError(em)
# run module
module(quiet=not verbose, **args).run()
return
def update(self, **modulekwargs):
"""Run create and postprocess with GRASS_OVERWRITE."""
with GrassOverwrite():
self.create(**modulekwargs)
self.postprocess(**modulekwargs)
return
def __call__(self, **modulekwargs):
"""Shortcut for `update`."""
return self.update(**modulekwargs)
def postprocess(self, **modulekwargs):
"""Overwrite to perform follow up tasks."""
return
| {
"content_hash": "8a81c600fec18f4107be239a0dd380f4",
"timestamp": "",
"source": "github",
"line_count": 344,
"max_line_length": 79,
"avg_line_length": 37.05813953488372,
"alnum_prop": 0.5838562911829307,
"repo_name": "mwort/modelmanager",
"id": "11f9396e8699a1721668e0b3ae7cb6c8a2a7350e",
"size": "12748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modelmanager/plugins/grass.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "538"
},
{
"name": "HTML",
"bytes": "2995"
},
{
"name": "JavaScript",
"bytes": "378"
},
{
"name": "Makefile",
"bytes": "1732"
},
{
"name": "Python",
"bytes": "138890"
}
],
"symlink_target": ""
} |
// Copyright (c) 2019-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/sendmultirow.h"
#include "qt/pivx/forms/ui_sendmultirow.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "qt/pivx/sendmemodialog.h"
#include "qt/pivx/qtutils.h"
SendMultiRow::SendMultiRow(PIVXGUI* _window, PWidget *parent) :
PWidget(_window, parent),
ui(new Ui::SendMultiRow),
iconNumber(new QPushButton())
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book");
ui->lineEditAddress->setAttribute(Qt::WA_MacShowFocusRect, 0);
setShadow(ui->stackedAddress);
initCssEditLine(ui->lineEditAmount);
GUIUtil::setupAmountWidget(ui->lineEditAmount, this);
/* Description */
setCssProperty(ui->labelSubtitleDescription, "text-title");
initCssEditLine(ui->lineEditDescription);
// future: when we get a designer, this should have another icon. A "memo" icon instead of a "+"
setCssProperty(ui->btnAddMemo, "btn-secundary-add");
setCssProperty(ui->checkboxSubtractFeeFromAmount, "combo-light");
// Button menu
setCssProperty(ui->btnMenu, "btn-menu");
ui->btnMenu->setVisible(false);
// Button Contact
btnContact = ui->lineEditAddress->addAction(QIcon("://ic-contact-arrow-down"), QLineEdit::TrailingPosition);
// Icon Number
ui->stackedAddress->addWidget(iconNumber);
iconNumber->show();
iconNumber->raise();
setCssProperty(iconNumber, "ic-multi-number");
iconNumber->setText("1");
iconNumber->setVisible(false);
QSize size = QSize(24, 24);
iconNumber->setMinimumSize(size);
iconNumber->setMaximumSize(size);
int posIconX = 0;
int posIconY = 14;
iconNumber->move(posIconX, posIconY);
connect(ui->lineEditAmount, &QLineEdit::textChanged, this, &SendMultiRow::amountChanged);
connect(ui->lineEditAddress, &QLineEdit::textChanged, [this](){addressChanged(ui->lineEditAddress->text());});
connect(btnContact, &QAction::triggered, [this](){Q_EMIT onContactsClicked(this);});
connect(ui->btnMenu, &QPushButton::clicked, [this](){Q_EMIT onMenuClicked(this);});
connect(ui->btnAddMemo, &QPushButton::clicked, this, &SendMultiRow::onMemoClicked);
}
void SendMultiRow::amountChanged(const QString& amountStr)
{
if (!amountStr.isEmpty()) {
auto value = GUIUtil::parseValue(amountStr, displayUnit);
if (value > 0) {
GUIUtil::updateWidgetTextAndCursorPosition(ui->lineEditAmount, amountStr);
setCssEditLine(ui->lineEditAmount, true, true);
}
}
Q_EMIT onValueChanged();
}
void SendMultiRow::onMemoClicked()
{
launchMemoDialog();
}
bool SendMultiRow::launchMemoDialog()
{
window->showHide(true);
SendMemoDialog* dialog = new SendMemoDialog(window, walletModel);
dialog->setMemo(recipient.message);
bool ret = false;
if (openDialogWithOpaqueBackgroundY(dialog, window, 3, 5)) {
recipient.message = dialog->getMemo();
ui->btnAddMemo->setText(tr("Update memo"));
setCssProperty(ui->btnAddMemo, "btn-secondary-update", true);
} else if (dialog->getOperationResult()) {
bool isMemoEmpty = recipient.message.isEmpty();
// reset..
recipient.message.clear();
ui->btnAddMemo->setText(tr("Add encrypted memo"));
setCssProperty(ui->btnAddMemo, "btn-secundary-add", true);
if (!isMemoEmpty) inform(tr("Memo field reset"));
ret = false;
}
dialog->deleteLater();
return ret;
}
bool SendMultiRow::addressChanged(const QString& str, bool fOnlyValidate)
{
if (!str.isEmpty()) {
QString trimmedStr = str.trimmed();
bool isShielded = false;
const bool valid = walletModel->validateAddress(trimmedStr, this->onlyStakingAddressAccepted, isShielded);
if (!valid) {
// check URI
SendCoinsRecipient rcp;
if (GUIUtil::parseBitcoinURI(trimmedStr, &rcp)) {
ui->lineEditAddress->setText(rcp.address);
ui->lineEditAmount->setText(BitcoinUnits::format(displayUnit, rcp.amount, false));
QString label = walletModel->getAddressTableModel()->labelForAddress(rcp.address);
if (!label.isNull() && !label.isEmpty()){
ui->lineEditDescription->setText(label);
} else if (!rcp.message.isEmpty())
ui->lineEditDescription->setText(rcp.message);
Q_EMIT onUriParsed(rcp);
} else {
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book-error");
}
} else {
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book");
if (!fOnlyValidate) {
QString label = walletModel->getAddressTableModel()->labelForAddress(trimmedStr);
if (!label.isEmpty()) {
ui->lineEditDescription->setText(label);
}
}
}
updateStyle(ui->lineEditAddress);
return valid;
}
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book");
updateStyle(ui->lineEditAddress);
return false;
}
void SendMultiRow::loadWalletModel()
{
if (walletModel && walletModel->getOptionsModel()) {
displayUnit = walletModel->getOptionsModel()->getDisplayUnit();
connect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendMultiRow::updateDisplayUnit);
}
clear();
}
void SendMultiRow::updateDisplayUnit()
{
// Update edit text..
displayUnit = walletModel->getOptionsModel()->getDisplayUnit();
}
void SendMultiRow::deleteClicked()
{
Q_EMIT removeEntry(this);
}
void SendMultiRow::clear()
{
ui->lineEditAddress->clear();
ui->lineEditAmount->clear();
ui->lineEditDescription->clear();
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book", true);
}
bool SendMultiRow::validate()
{
if (!walletModel)
return false;
// Check input validity
bool retval = true;
// Check address validity, returns false if it's invalid
QString address = ui->lineEditAddress->text();
if (address.isEmpty()){
retval = false;
setCssProperty(ui->lineEditAddress, "edit-primary-multi-book-error", true);
} else
retval = addressChanged(address, true);
CAmount value = getAmountValue();
// Sending a zero amount is invalid
if (value <= 0) {
setCssEditLine(ui->lineEditAmount, false, true);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(address, value)) {
setCssEditLine(ui->lineEditAmount, false, true);
retval = false;
}
return retval;
}
SendCoinsRecipient SendMultiRow::getValue()
{
recipient.address = getAddress();
recipient.label = ui->lineEditDescription->text();
recipient.amount = getAmountValue();
auto dest = Standard::DecodeDestination(recipient.address.toStdString());
recipient.isShieldedAddr = boost::get<libzcash::SaplingPaymentAddress>(&dest);
recipient.fSubtractFee = getSubtractFeeFromAmount();
return recipient;
}
QString SendMultiRow::getAddress()
{
return ui->lineEditAddress->text().trimmed();
}
CAmount SendMultiRow::getAmountValue()
{
return GUIUtil::parseValue(ui->lineEditAmount->text(), displayUnit);
}
QString SendMultiRow::getMemo()
{
return recipient.message;
}
QRect SendMultiRow::getEditLineRect()
{
return ui->lineEditAddress->rect();
}
int SendMultiRow::getEditHeight()
{
return ui->stackedAddress->height();
}
int SendMultiRow::getEditWidth()
{
return ui->lineEditAddress->width();
}
int SendMultiRow::getNumber()
{
return number;
}
bool SendMultiRow::getSubtractFeeFromAmount() const
{
return ui->checkboxSubtractFeeFromAmount->isChecked();
}
void SendMultiRow::setAddress(const QString& address)
{
ui->lineEditAddress->setText(address);
ui->lineEditAmount->setFocus();
}
void SendMultiRow::setAmount(const QString& amount)
{
ui->lineEditAmount->setText(amount);
}
void SendMultiRow::toggleSubtractFeeFromAmount()
{
bool old = ui->checkboxSubtractFeeFromAmount->isChecked();
ui->checkboxSubtractFeeFromAmount->setChecked(!old);
}
void SendMultiRow::setAddressAndLabelOrDescription(const QString& address, const QString& message)
{
QString label = walletModel->getAddressTableModel()->labelForAddress(address);
if (!label.isNull() && !label.isEmpty()){
ui->lineEditDescription->setText(label);
} else if(!message.isEmpty())
ui->lineEditDescription->setText(message);
setAddress(address);
}
void SendMultiRow::setLabel(const QString& label)
{
ui->lineEditDescription->setText(label);
}
bool SendMultiRow::isClear()
{
return ui->lineEditAddress->text().isEmpty();
}
void SendMultiRow::setFocus()
{
ui->lineEditAddress->setFocus();
}
void SendMultiRow::setOnlyStakingAddressAccepted(bool onlyStakingAddress)
{
this->onlyStakingAddressAccepted = onlyStakingAddress;
ui->containerMemo->setVisible(!onlyStakingAddress);
}
void SendMultiRow::setNumber(int _number)
{
number = _number;
iconNumber->setText(QString::number(_number));
}
void SendMultiRow::hideLabels()
{
ui->layoutLabel->setVisible(false);
iconNumber->setVisible(true);
}
void SendMultiRow::showLabels()
{
ui->layoutLabel->setVisible(true);
iconNumber->setVisible(false);
}
void SendMultiRow::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
}
void SendMultiRow::enterEvent(QEvent *)
{
if (!this->isExpanded && iconNumber->isVisible()) {
isExpanded = true;
ui->btnMenu->setVisible(isExpanded);
}
}
void SendMultiRow::leaveEvent(QEvent *)
{
if (isExpanded) {
isExpanded = false;
ui->btnMenu->setVisible(isExpanded);
}
}
int SendMultiRow::getMenuBtnWidth()
{
return ui->btnMenu->width();
}
SendMultiRow::~SendMultiRow()
{
delete ui;
}
| {
"content_hash": "0feba4d334637bf13e95b08399ecca23",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 123,
"avg_line_length": 28.38718662952646,
"alnum_prop": 0.6745167304484349,
"repo_name": "PIVX-Project/PIVX",
"id": "ab86eece3900cf28c567b1be799eefc91b3ca42b",
"size": "10191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/pivx/sendmultirow.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "953297"
},
{
"name": "C",
"bytes": "5168953"
},
{
"name": "C++",
"bytes": "9188709"
},
{
"name": "CMake",
"bytes": "203234"
},
{
"name": "CSS",
"bytes": "211710"
},
{
"name": "HTML",
"bytes": "21833"
},
{
"name": "Java",
"bytes": "30291"
},
{
"name": "JavaScript",
"bytes": "41357"
},
{
"name": "M4",
"bytes": "263162"
},
{
"name": "Makefile",
"bytes": "139139"
},
{
"name": "Objective-C++",
"bytes": "3642"
},
{
"name": "Python",
"bytes": "1505322"
},
{
"name": "QMake",
"bytes": "26219"
},
{
"name": "Rust",
"bytes": "139132"
},
{
"name": "Sage",
"bytes": "30188"
},
{
"name": "Shell",
"bytes": "101041"
},
{
"name": "TypeScript",
"bytes": "10706"
}
],
"symlink_target": ""
} |
using System;
namespace Spine {
public interface AttachmentLoader {
/// <return>May be null to not load any attachment.</return>
Attachment NewAttachment (Skin skin, AttachmentType type, String name);
}
}
| {
"content_hash": "5d17e4336df3f066e9eafe7ecc66c6cb",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 73,
"avg_line_length": 21.4,
"alnum_prop": 0.7383177570093458,
"repo_name": "herman-rogers/Relic",
"id": "6f064600726450622272036c723c3bcc980fa783",
"size": "1948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RelicGame/Assets/spine-csharp/src/Attachments/AttachmentLoader.cs",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "71299"
},
{
"name": "C#",
"bytes": "1864463"
},
{
"name": "JavaScript",
"bytes": "169899"
}
],
"symlink_target": ""
} |
#ifndef _MACHINE_IOCTL_METEOR_H_
#define _MACHINE_IOCTL_METEOR_H_
#include <sys/cdefs.h>
#ifdef __CC_SUPPORTS_WARNING
#warning Include dev/bktr/ioctl_meteor.h instead of this header.
#endif
#include <dev/bktr/ioctl_meteor.h>
#endif /* _MACHINE_IOCTL_METEOR_H_ */
| {
"content_hash": "75adaad1a6aa6c12c60720f8ed54ef4d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 64,
"avg_line_length": 19.214285714285715,
"alnum_prop": 0.724907063197026,
"repo_name": "jrobhoward/SCADAbase",
"id": "0322f1ede2c17fe1d4c56d4e7ca304657f3dc2b8",
"size": "1606",
"binary": false,
"copies": "4",
"ref": "refs/heads/SCADAbase",
"path": "sys/i386/include/ioctl_meteor.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4615704"
},
{
"name": "Awk",
"bytes": "273794"
},
{
"name": "Batchfile",
"bytes": "20333"
},
{
"name": "C",
"bytes": "457666547"
},
{
"name": "C++",
"bytes": "91495356"
},
{
"name": "CMake",
"bytes": "17632"
},
{
"name": "CSS",
"bytes": "104220"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "6321"
},
{
"name": "DIGITAL Command Language",
"bytes": "10638"
},
{
"name": "DTrace",
"bytes": "1904158"
},
{
"name": "Emacs Lisp",
"bytes": "32010"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "204603"
},
{
"name": "GAP",
"bytes": "72078"
},
{
"name": "Groff",
"bytes": "32376243"
},
{
"name": "HTML",
"bytes": "5776268"
},
{
"name": "Haskell",
"bytes": "2458"
},
{
"name": "IGOR Pro",
"bytes": "6510"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "425858"
},
{
"name": "Limbo",
"bytes": "4037"
},
{
"name": "Logos",
"bytes": "179088"
},
{
"name": "Makefile",
"bytes": "12750766"
},
{
"name": "Mathematica",
"bytes": "21782"
},
{
"name": "Max",
"bytes": "4105"
},
{
"name": "Module Management System",
"bytes": "816"
},
{
"name": "Objective-C",
"bytes": "1571960"
},
{
"name": "PHP",
"bytes": "2471"
},
{
"name": "PLSQL",
"bytes": "96552"
},
{
"name": "PLpgSQL",
"bytes": "2212"
},
{
"name": "Perl",
"bytes": "3947402"
},
{
"name": "Perl6",
"bytes": "122803"
},
{
"name": "PostScript",
"bytes": "152255"
},
{
"name": "Prolog",
"bytes": "42792"
},
{
"name": "Protocol Buffer",
"bytes": "54964"
},
{
"name": "Python",
"bytes": "381066"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "67015"
},
{
"name": "Scheme",
"bytes": "5087"
},
{
"name": "Scilab",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "10963470"
},
{
"name": "SourcePawn",
"bytes": "2293"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "7102"
},
{
"name": "TeX",
"bytes": "720582"
},
{
"name": "VimL",
"bytes": "19597"
},
{
"name": "XS",
"bytes": "17496"
},
{
"name": "XSLT",
"bytes": "4564"
},
{
"name": "Yacc",
"bytes": "1881915"
}
],
"symlink_target": ""
} |
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="medium_text">22sp</dimen>
<dimen name="large_text">28sp</dimen>
<dimen name="huge_text">44sp</dimen>
<dimen name="layout_padding">12dp</dimen>
<dimen name="map_size">168dp</dimen>
<dimen name="recycler_icon_size">48dp</dimen>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="nav_header_vertical_spacing">16dp</dimen>
<dimen name="nav_header_height">160dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>
| {
"content_hash": "9029381200ee671c838aeece803ee0c9",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 71,
"avg_line_length": 38.888888888888886,
"alnum_prop": 0.6757142857142857,
"repo_name": "cliffroot/awareness",
"id": "bfce39c40eefa3e4ea03f952c19b4f16470b82e6",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/dimens.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "696"
},
{
"name": "Kotlin",
"bytes": "89524"
}
],
"symlink_target": ""
} |
package p507
/**
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Example:
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
*/
func checkPerfectNumber(num int) bool {
if num <= 1 {
return false
}
n := num - 1
div := 2
for div*div < num {
if num%div == 0 {
n -= div
if div*div != num {
n -= num / div
}
}
div++
}
return n == 0
}
| {
"content_hash": "585f4cec2b84e157001a732c3ab6c032",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 119,
"avg_line_length": 20.5,
"alnum_prop": 0.6422764227642277,
"repo_name": "baishuai/leetcode",
"id": "c333bff50d93f022372f1aac4b7ddffb09a7af87",
"size": "615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "algorithms/p507/507.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "243910"
},
{
"name": "CMake",
"bytes": "577"
},
{
"name": "Go",
"bytes": "652457"
},
{
"name": "Java",
"bytes": "900"
},
{
"name": "Python",
"bytes": "13694"
},
{
"name": "Shell",
"bytes": "276"
}
],
"symlink_target": ""
} |
This document contains a rough outline of a roadmap and a few designs for future features in SubKit GraphQL-Server. Contributions are very welcome! Feel free to pick an of the upcoming features and start implementing, and don't hold back with questions or ideas!
## Roadmap
### Completed
* GraphQL subscriptions via Server-Side-Events (SSE-Transport)
* Build-In and custom directives
* @fetchJSON, @publish, @mock, @execute, @complexity, @cacheControl
* GraphQL request CLI with subscription support
* Simplification of API
* Persistent query support
* Collect traces from query resolvers
### Current
* Performance testing in production settings
* Resolver batching and caching
* Enhance documentation and tests
* more build-in and custom directives
* @requestJSON
* Usage metric calculation
* Web-Hook endpoint to publish events via HTTP
* Integration guide to:
* API-Gateway for Micro/Macro-Services and Datebases
* AWS Lambda
* Azure Functions
* Deployment guide to:
* [DropStack](https://dropstack.run)
* AWS Lambda
### Next up
* Better GraphQL error handling
* Support for simple query timeouts
* GraphQL query batching
* NPM modularization of:
* SubKit GraphQL middleware
* SubKit directives
* SubKit CLI
### Future
* Support for @defer, @stream and @live directives
## Proposed designs
### Support for @defer, @live and @stream
Support for the defer, stream and live directives will require replacing or modifying graphql-js’ `execute` function. The `execute` function would have to be changed to return an observable instead of a promise, and support for each of the directives would have to be built directly into the execution engine.
In addition, a new protocol will need to be devised for sending partial results back to the clients. The most straightforward way seems to be to include a path with the data sent in the response, for example `{ path: [ 'author', 'posts', 0 ], data: { title: 'Hello', views: 10 } }`. Such a response could then be merged on the client.
@defer could be implemented with a queue. Whenever a “defer” is encountered, it is put on the deferred queue. Once the initial response is sent, the deferred queue is processed. As each item in that queue is processed a new chunk is sent back.
Similar to defer, @live requires changes to the execution engine. In particular, it needs to know to set up a task that keeps sending updates. This can again be done by returning an observable, and then sending the data over a websocket or similar persistent transport. In its most basic form, @live could be implemented by re-running the live subtree of the query at a periodic interval. More advanced implementations will depend on setting up event listeners and re-executing parts of the query only when relevant results have changed.
@stream is similar to @defer, except that processing can continue right away, and the streamed part of the result can begin sending right away. | {
"content_hash": "cb3adc6588dc9a444a06242d13ce8cf2",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 537,
"avg_line_length": 51.578947368421055,
"alnum_prop": 0.7741496598639456,
"repo_name": "CodeCommission/subkit",
"id": "cef84ba22db3359bef8ceb4779ad3080e4f03368",
"size": "2967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/ROADMAP.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "85063"
}
],
"symlink_target": ""
} |
package scriptella.text;
import scriptella.configuration.ConfigurationException;
import scriptella.util.StringUtils;
import java.text.Format;
import java.text.MessageFormat;
import java.util.Locale;
/**
* Builder class for constructing {@link Format} instances based on the following parameters:
* <ul>
* <li>type - built-in type name, i.e. timestamp, number, date, time etc</li>
* <li>className - name of the custom sub-class of {@link Format}</li>
* <li>pattern - pattern to use for a specified type</li>
* <li>locale - locale to use for formatting</li>
* </ul>
*
* @author Fyodor Kupolov
* @since 1.1
*/
public class ValueFormatBuilder {
private String type;
private String className;
private String pattern;
private Locale locale;
public String getType() {
return type;
}
public ValueFormatBuilder setType(String type) {
this.type = type;
return this;
}
public String getClassName() {
return className;
}
public ValueFormatBuilder setClassName(String className) {
this.className = className;
return this;
}
public String getPattern() {
return pattern;
}
public ValueFormatBuilder setPattern(String pattern) {
this.pattern = pattern;
return this;
}
public Locale getLocale() {
return locale;
}
public ValueFormatBuilder setLocale(Locale locale) {
this.locale = locale;
return this;
}
public Format build() {
//if format class name is defined - instantiate it and return
if (!StringUtils.isEmpty(className)) {
Class<?> formatClass;
try {
try {
formatClass = Class.forName(className);
} catch (ClassNotFoundException e) {
formatClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
}
if (!Format.class.isAssignableFrom(formatClass)) {
throw new ConfigurationException("Specified format class " + className + " is not a subclass of " + Format.class);
}
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Specified format class " + className + " cannot be found");
}
try {
return (Format) formatClass.newInstance();
} catch (Exception e) {
throw new ConfigurationException("Cannot instantiate format class " + className, e);
}
}
if (type == null) {
throw new IllegalArgumentException("Type must be specified");
}
if (type.equalsIgnoreCase("timestamp")) {
return new TimestampValueFormat();
}
StringBuilder fmt = new StringBuilder("{0,").append(type);
if (pattern != null) {
fmt.append(",").append(pattern);
}
fmt.append("}");
return new MessageFormat(fmt.toString(), locale == null ? Locale.getDefault() : locale);
}
}
| {
"content_hash": "97a2b957a9a64461e34af5c9a5106759",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 134,
"avg_line_length": 30.254901960784313,
"alnum_prop": 0.6007777057679844,
"repo_name": "scriptella/scriptella-etl",
"id": "717720e614c61926312ff65f04a4b7e202053e90",
"size": "3703",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/java/scriptella/text/ValueFormatBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1794"
},
{
"name": "HTML",
"bytes": "90799"
},
{
"name": "Java",
"bytes": "1289261"
},
{
"name": "Shell",
"bytes": "1508"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sylius\Component\Mailer\Provider;
use Sylius\Component\Mailer\Factory\EmailFactoryInterface;
use Sylius\Component\Mailer\Model\EmailInterface;
use Webmozart\Assert\Assert;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
* @author Jérémy Leherpeur <jeremy@leherpeur.net>
*/
final class EmailProvider implements EmailProviderInterface
{
/**
* @var EmailFactoryInterface
*/
private $emailFactory;
/**
* @var array
*/
private $configuration;
/**
* @param EmailFactoryInterface $emailFactory
* @param array $configuration
*/
public function __construct(
EmailFactoryInterface $emailFactory,
array $configuration
) {
$this->emailFactory = $emailFactory;
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getEmail(string $code): EmailInterface
{
return $this->getEmailFromConfiguration($code);
}
/**
* @param string $code
*
* @return EmailInterface
*/
private function getEmailFromConfiguration(string $code): EmailInterface
{
Assert::keyExists($this->configuration, $code, sprintf('Email with code "%s" does not exist!', $code));
/** @var EmailInterface $email */
$email = $this->emailFactory->createNew();
$configuration = $this->configuration[$code];
$email->setCode($code);
$email->setSubject($configuration['subject']);
$email->setTemplate($configuration['template']);
if (isset($configuration['enabled']) && false === $configuration['enabled']) {
$email->setEnabled(false);
}
if (isset($configuration['sender']['name'])) {
$email->setSenderName($configuration['sender']['name']);
}
if (isset($configuration['sender']['address'])) {
$email->setSenderAddress($configuration['sender']['address']);
}
return $email;
}
}
| {
"content_hash": "30b7ca533e28d09259d1f0bf11aacbcc",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 111,
"avg_line_length": 25.94871794871795,
"alnum_prop": 0.6170948616600791,
"repo_name": "ylastapis/Sylius",
"id": "95c54bbeb182abad3b21eee0b945eb5dcfbb5b3f",
"size": "2239",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Sylius/Component/Mailer/Provider/EmailProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "601"
},
{
"name": "CSS",
"bytes": "2192"
},
{
"name": "Gherkin",
"bytes": "813593"
},
{
"name": "HTML",
"bytes": "305193"
},
{
"name": "JavaScript",
"bytes": "72306"
},
{
"name": "PHP",
"bytes": "6802898"
},
{
"name": "Shell",
"bytes": "29158"
}
],
"symlink_target": ""
} |
extern crate protobuf;
extern crate rand;
extern crate time;
use std::default::Default;
use std::fs::File;
use std::path::Path;
use rand::Rng;
use rand::StdRng;
use rand::SeedableRng;
use protobuf::Message;
use protobuf::MessageStatic;
use perftest_data::PerftestData;
mod perftest_data;
fn measure_ns<R, F: FnMut() -> R>(mut f: F) -> (u64, R) {
let start = time::precise_time_ns();
let r = f();
(time::precise_time_ns() - start, r)
}
fn measure_and_print<R, F: FnMut() -> R>(title: &str, iter: u64, f: F) -> R {
let (ns, r) = measure_ns(f);
let ns_per_iter = ns / iter;
println!("{}: {} ns per iter", title, ns_per_iter);
r
}
fn run_test<M : Message + MessageStatic>(name: &str, data: &[M]) {
let mut rng: StdRng = SeedableRng::from_seed(&[10, 20, 30, 40][..]);
let mut random_data: Vec<M> = Vec::new();
let mut total_size = 0;
while total_size < 1000000 {
let ref item = data[rng.gen_range(0, data.len())];
random_data.push(item.clone());
total_size += item.compute_size();
}
let mut buf = Vec::new();
measure_and_print(&format!("{}: write", name), random_data.len() as u64, || {
for m in random_data.iter() {
m.write_length_delimited_to_writer(&mut buf).unwrap();
}
});
let read_data = measure_and_print(&format!("{}: read", name), random_data.len() as u64, || {
let mut r = Vec::new();
let mut coded_input_stream = protobuf::CodedInputStream::from_bytes(&buf);
while !coded_input_stream.eof().unwrap() {
r.push(protobuf::parse_length_delimited_from::<M>(&mut coded_input_stream).unwrap());
}
r
});
assert_eq!(random_data, read_data);
let merged = measure_and_print(&format!("{}: read reuse", name), random_data.len() as u64, || {
let mut coded_input_stream = protobuf::CodedInputStream::from_bytes(&buf);
let mut msg: M = Default::default();
let mut count = 0;
while !coded_input_stream.eof().unwrap() {
msg.clear();
coded_input_stream.merge_message(&mut msg).unwrap();
count += 1;
}
count
});
assert_eq!(random_data.len(), merged);
}
struct TestRunner {
selected: Option<String>,
any_matched: bool,
}
impl TestRunner {
fn test<M : Message + MessageStatic>(&mut self, name: &str, data: &[M]) {
if self.selected.as_ref().map(|s| *s == name).unwrap_or(true) {
run_test(name, data);
self.any_matched = true;
}
}
fn check(&self) {
if !self.any_matched {
let name = self.selected.as_ref().map(|s| &s[..]).unwrap_or("bug");
panic!("no tests found with name {}", name);
}
}
}
fn main() {
let args = std::env::args().collect::<Vec<_>>();
if args.len() > 2 { panic!("usage: {} <test>", args[0]) }
let selected = args.into_iter().nth(1);
let mut runner = TestRunner { selected: selected, any_matched: false };
let mut is = File::open(&Path::new("perftest_data.pbbin")).unwrap();
let test_data = protobuf::parse_from_reader::<PerftestData>(&mut is).unwrap();
runner.test("test1", test_data.get_test1());
runner.test("test_repeated_bool", test_data.get_test_repeated_bool());
runner.test("test_repeated_packed_int32", test_data.get_test_repeated_packed_int32());
runner.test("test_repeated_messages", test_data.get_test_repeated_messages());
runner.test("test_optional_messages", test_data.get_test_optional_messages());
runner.test("test_strings", test_data.get_test_strings());
runner.check();
}
| {
"content_hash": "60254103e4d776c29412ed893eb78d0e",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 99,
"avg_line_length": 31.912280701754387,
"alnum_prop": 0.585761407366685,
"repo_name": "Blei/rust-protobuf",
"id": "9d7231d6e7e6c21544a927eac576e2ca096c056f",
"size": "3638",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/perftest/perftest.rs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "3650"
},
{
"name": "Protocol Buffer",
"bytes": "45189"
},
{
"name": "Rust",
"bytes": "844202"
},
{
"name": "Shell",
"bytes": "2356"
}
],
"symlink_target": ""
} |
.masthead {
font-family: "novamonoregular", Impact, Sans;
font-size: 2em;
}
| {
"content_hash": "f3e35061398ed6c9e414ac81bc4d92af",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 47,
"avg_line_length": 20,
"alnum_prop": 0.675,
"repo_name": "mildmojo/spy-break",
"id": "02a18c0bf00c9209c177f5a05812323464323070",
"size": "80",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "css/main.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1654"
},
{
"name": "JavaScript",
"bytes": "30785"
}
],
"symlink_target": ""
} |
from broker import Broker
from simpleconsumer import SimpleConsumer
from cluster import Cluster
from partition import Partition
from producer import Producer
from topic import Topic
from client import KafkaClient
from balancedconsumer import BalancedConsumer
__version__ = '2.0.0'
__all__ = ["Broker", "SimpleConsumer", "Cluster", "Partition", "Producer",
"Topic", "KafkaClient", "BalancedConsumer"]
| {
"content_hash": "17a862d60382d822d4c3ba471032cffe",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 74,
"avg_line_length": 29.571428571428573,
"alnum_prop": 0.7632850241545893,
"repo_name": "aeroevan/pykafka",
"id": "0af5807098febb004c18b42304437e48498b70da",
"size": "414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pykafka/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "379"
},
{
"name": "Python",
"bytes": "257624"
},
{
"name": "Shell",
"bytes": "626"
}
],
"symlink_target": ""
} |
// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed 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.
/**
* @fileoverview Service to retrieve read only information
* about collections from the backend.
*/
import { downgradeInjectable } from '@angular/upgrade/static';
import { HttpClient } from '@angular/common/http';
import { EventEmitter, Injectable } from '@angular/core';
import cloneDeep from 'lodash/cloneDeep';
import { AppConstants } from 'app.constants';
import { CollectionBackendDict, Collection } from
'domain/collection/collection.model';
import { UrlInterpolationService } from
'domain/utilities/url-interpolation.service';
interface CollectionCache {
[collectionId: string]: Collection;
}
interface CollectionDetails {
canEdit: boolean;
title: string;
}
interface CollectionDetailsCache {
[collectionId: string]: CollectionDetails;
}
export interface ReadOnlyCollectionBackendResponse {
'meta_name': string;
'can_edit': boolean;
'meta_description': string;
'collection': CollectionBackendDict;
}
// TODO(bhenning): For preview mode, this service should be replaced by a
// separate CollectionDataService implementation which returns a local copy of
// the collection instead. This file should not be included on the page in that
// scenario.
@Injectable({
providedIn: 'root'
})
export class ReadOnlyCollectionBackendApiService {
constructor(
private http: HttpClient,
private urlInterpolationService: UrlInterpolationService) {}
private _collectionCache: CollectionCache = {};
private _collectionDetailsCache: CollectionDetailsCache = {};
private _collectionLoadedEventEmitter = new EventEmitter<void>();
private _fetchCollection(
collectionId: string,
successCallback: (value: Collection) => void,
errorCallback: (reason: string) => void): void {
var collectionDataUrl = this.urlInterpolationService.interpolateUrl(
AppConstants.COLLECTION_DATA_URL_TEMPLATE, {
collection_id: collectionId
});
this.http.get<ReadOnlyCollectionBackendResponse>(
collectionDataUrl).toPromise().then(response => {
this._cacheCollectionDetails(response);
var collectionObject = Collection.create(
response.collection);
if (successCallback) {
successCallback(collectionObject);
this._collectionLoadedEventEmitter.emit();
}
}, errorResponse => {
if (errorCallback) {
errorCallback(errorResponse.error.error);
}
});
}
private _cacheCollectionDetails(
details: ReadOnlyCollectionBackendResponse): void {
this._collectionDetailsCache[details.collection.id] = {
canEdit: details.can_edit,
title: details.collection.title,
};
}
private _isCached(collectionId: string): boolean {
return this._collectionCache.hasOwnProperty(collectionId);
}
/**
* Behaves in the exact same way as fetchCollectionAsync (including callback
* behavior and returning a promise object), except this function will
* attempt to see whether the given collection has already been loaded. If
* it has not yet been loaded, it will fetch the collection from the
* backend. If it successfully retrieves the collection from the backend,
* it will store it in the cache to avoid requests from the backend in
* further function calls.
*/
async loadCollectionAsync(collectionId: string): Promise<Collection> {
return new Promise((resolve, reject) => {
if (this._isCached(collectionId)) {
if (resolve) {
resolve(cloneDeep(this._collectionCache[collectionId]));
this._collectionLoadedEventEmitter.emit();
}
} else {
this._fetchCollection(collectionId, collection => {
// Save the fetched collection to avoid future fetches.
this._collectionCache[collectionId] = collection;
if (resolve) {
resolve(cloneDeep(collection));
}
}, reject);
}
});
}
getCollectionDetails(collectionId: string): CollectionDetails {
if (this._collectionDetailsCache[collectionId]) {
return this._collectionDetailsCache[collectionId];
} else {
throw new Error('collection has not been fetched');
}
}
/**
* Returns whether the given collection is stored within the local data
* cache or if it needs to be retrieved from the backend upon a laod.
*/
isCached(collectionId: string): boolean {
return this._isCached(collectionId);
}
/**
* Replaces the current collection in the cache given by the specified
* collection ID with a new collection object.
*/
cacheCollection(collectionId: string, collection: Collection): void {
this._collectionCache[collectionId] = cloneDeep(collection);
}
/**
* Clears the local collection data cache, forcing all future loads to
* re-request the previously loaded collections from the backend.
*/
clearCollectionCache(): void {
this._collectionCache = {};
}
get onCollectionLoad(): EventEmitter<void> {
return this._collectionLoadedEventEmitter;
}
}
angular.module('oppia').factory(
'ReadOnlyCollectionBackendApiService',
downgradeInjectable(ReadOnlyCollectionBackendApiService));
| {
"content_hash": "94d77dc489709893ae2ccf9eb084c15d",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 79,
"avg_line_length": 33.36046511627907,
"alnum_prop": 0.7152317880794702,
"repo_name": "kevinlee12/oppia",
"id": "1f4cd4d39c50cc8f95bcff8d38dbf94d972dad34",
"size": "5738",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/templates/domain/collection/read-only-collection-backend-api.service.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "205771"
},
{
"name": "HTML",
"bytes": "1835761"
},
{
"name": "JavaScript",
"bytes": "1182599"
},
{
"name": "PEG.js",
"bytes": "71377"
},
{
"name": "Python",
"bytes": "13670639"
},
{
"name": "Shell",
"bytes": "2239"
},
{
"name": "TypeScript",
"bytes": "13024194"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Wed Apr 05 10:49:36 BST 2017 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.github.rvesse.airline.parser.suggester (Airline - Library 2.3.0 API)</title>
<meta name="date" content="2017-04-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../com/github/rvesse/airline/parser/suggester/package-summary.html" target="classFrame">com.github.rvesse.airline.parser.suggester</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="SuggestionParser.html" title="class in com.github.rvesse.airline.parser.suggester" target="classFrame">SuggestionParser</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "4f4c0d6824dc87b0098e6406a3c888de",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 179,
"avg_line_length": 48.25,
"alnum_prop": 0.6849740932642487,
"repo_name": "rvesse/airline",
"id": "f3e90f87c88dfe0fb60b5fe8d78baa7d81c9a287",
"size": "965",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/javadoc/2.3.0/airline/com/github/rvesse/airline/parser/suggester/package-frame.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "91"
},
{
"name": "Java",
"bytes": "2176058"
},
{
"name": "Shell",
"bytes": "4550"
}
],
"symlink_target": ""
} |
// Code generated by k8s code-generator DO NOT EDIT.
// Code generated by informer-gen. DO NOT EDIT.
package externalversions
import (
reflect "reflect"
sync "sync"
time "time"
versioned "github.com/kubeflow/arena/pkg/operators/spark-operator/client/clientset/versioned"
internalinterfaces "github.com/kubeflow/arena/pkg/operators/spark-operator/client/informers/externalversions/internalinterfaces"
sparkoperatork8sio "github.com/kubeflow/arena/pkg/operators/spark-operator/client/informers/externalversions/sparkoperator.k8s.io"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
cache "k8s.io/client-go/tools/cache"
)
// SharedInformerOption defines the functional option type for SharedInformerFactory.
type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory
type sharedInformerFactory struct {
client versioned.Interface
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
lock sync.Mutex
defaultResync time.Duration
customResync map[reflect.Type]time.Duration
informers map[reflect.Type]cache.SharedIndexInformer
// startedInformers is used for tracking which informers have been started.
// This allows Start() to be called multiple times safely.
startedInformers map[reflect.Type]bool
}
// WithCustomResyncConfig sets a custom resync period for the specified informer types.
func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption {
return func(factory *sharedInformerFactory) *sharedInformerFactory {
for k, v := range resyncConfig {
factory.customResync[reflect.TypeOf(k)] = v
}
return factory
}
}
// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory.
func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption {
return func(factory *sharedInformerFactory) *sharedInformerFactory {
factory.tweakListOptions = tweakListOptions
return factory
}
}
// WithNamespace limits the SharedInformerFactory to the specified namespace.
func WithNamespace(namespace string) SharedInformerOption {
return func(factory *sharedInformerFactory) *sharedInformerFactory {
factory.namespace = namespace
return factory
}
}
// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces.
func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory {
return NewSharedInformerFactoryWithOptions(client, defaultResync)
}
// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory.
// Listers obtained via this SharedInformerFactory will be subject to the same filters
// as specified here.
// Deprecated: Please use NewSharedInformerFactoryWithOptions instead
func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory {
return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions))
}
// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options.
func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory {
factory := &sharedInformerFactory{
client: client,
namespace: v1.NamespaceAll,
defaultResync: defaultResync,
informers: make(map[reflect.Type]cache.SharedIndexInformer),
startedInformers: make(map[reflect.Type]bool),
customResync: make(map[reflect.Type]time.Duration),
}
// Apply all options
for _, opt := range options {
factory = opt(factory)
}
return factory
}
// Start initializes all requested informers.
func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) {
f.lock.Lock()
defer f.lock.Unlock()
for informerType, informer := range f.informers {
if !f.startedInformers[informerType] {
go informer.Run(stopCh)
f.startedInformers[informerType] = true
}
}
}
// WaitForCacheSync waits for all started informers' cache were synced.
func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool {
informers := func() map[reflect.Type]cache.SharedIndexInformer {
f.lock.Lock()
defer f.lock.Unlock()
informers := map[reflect.Type]cache.SharedIndexInformer{}
for informerType, informer := range f.informers {
if f.startedInformers[informerType] {
informers[informerType] = informer
}
}
return informers
}()
res := map[reflect.Type]bool{}
for informType, informer := range informers {
res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)
}
return res
}
// InternalInformerFor returns the SharedIndexInformer for obj using an internal
// client.
func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {
f.lock.Lock()
defer f.lock.Unlock()
informerType := reflect.TypeOf(obj)
informer, exists := f.informers[informerType]
if exists {
return informer
}
resyncPeriod, exists := f.customResync[informerType]
if !exists {
resyncPeriod = f.defaultResync
}
informer = newFunc(f.client, resyncPeriod)
f.informers[informerType] = informer
return informer
}
// SharedInformerFactory provides shared informers for resources in all known
// API group versions.
type SharedInformerFactory interface {
internalinterfaces.SharedInformerFactory
ForResource(resource schema.GroupVersionResource) (GenericInformer, error)
WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool
Sparkoperator() sparkoperatork8sio.Interface
}
func (f *sharedInformerFactory) Sparkoperator() sparkoperatork8sio.Interface {
return sparkoperatork8sio.New(f, f.namespace, f.tweakListOptions)
}
| {
"content_hash": "671879fd0a82d018b25d2ce83326ee37",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 194,
"avg_line_length": 35.88690476190476,
"alnum_prop": 0.7944932824680709,
"repo_name": "kubeflow/arena",
"id": "b7e56942b1e327999bd4db2a8942b4b6a49abef1",
"size": "6586",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/operators/spark-operator/client/informers/externalversions/factory.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "785"
},
{
"name": "Go",
"bytes": "1676188"
},
{
"name": "Java",
"bytes": "169036"
},
{
"name": "Makefile",
"bytes": "4889"
},
{
"name": "Mustache",
"bytes": "21572"
},
{
"name": "Python",
"bytes": "139551"
},
{
"name": "Shell",
"bytes": "33305"
},
{
"name": "Smarty",
"bytes": "1242"
}
],
"symlink_target": ""
} |
package org.scijava.convert;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.stream.Collectors;
import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.util.ArrayUtils;
import org.scijava.util.Types;
/**
* A {@link Converter} that specializes in converting
* n-dimensional arrays into {@link String}s. This {@link Converter} can convert any array whose
* component types can be converted into {@link String}s. By default, this
* {@link Converter} delimits the array elements with commas.
*
* @author Gabriel Selzer
*/
@Plugin(type = Converter.class, priority = Priority.VERY_LOW)
public class ArrayToStringConverter extends AbstractConverter<Object, String> {
@Parameter(required = false)
private ConvertService convertService;
@Override public boolean canConvert(final Class<?> src, final Class<?> dest) {
if (src == null) return false;
final Class<?> saneSrc = Types.box(src);
final Class<?> saneDest = Types.box(dest);
return saneSrc.isArray() && saneDest == String.class;
}
@Override public boolean canConvert(final Object src, final Class<?> dest) {
if (convertService == null) return false;
if (!canConvert(src.getClass(), dest)) return false;
if (Array.getLength(src) == 0) return true;
return convertService.supports(Array.get(src, 0), dest);
}
@Override
public Object convert(Object src, Type dest) {
// Preprocess the "string-likes"
if (src.getClass().equals(String[].class) || //
src.getClass().equals(Character[].class) || //
src.getClass().equals(char[].class)) //
{
src = preprocessCharacters(src);
}
// Convert each element to Strings
String elementString = ArrayUtils.toCollection(src).stream() //
.map(object -> convertService.convert(object, String.class)) //
.collect(Collectors.joining(", "));
return "{" + elementString + "}";
}
private String[] preprocessStrings(final Object src) {
int numElements = Array.getLength(src);
String[] processed = new String[numElements];
for (int i = 0; i < numElements; i++) {
processed[i] = preprocessString(Array.get(src, i));
}
return processed;
}
private String preprocessString(final Object o) {
String s;
if (o == null) {
return null;
} else {
s = o.toString();
s = s.replace("\\", "\\\\");
s = s.replace("\"", "\\\"");
}
return "\"" + s + "\"";
}
private String[] preprocessCharacters(Object src) {
String[] processed = new String[Array.getLength(src)];
for (int i = 0; i < processed.length; i++) {
Object value = Array.get(src, i);
processed[i] = value == null ? null : value.toString();
}
return preprocessStrings(processed);
}
@SuppressWarnings("unchecked") @Override
public <T> T convert(Object src, Class<T> dest) {
return (T) convert(src, (Type) dest);
}
@Override public Class<String> getOutputType() {
return String.class;
}
@Override public Class<Object> getInputType() {
return Object.class;
}
}
| {
"content_hash": "4f000ec4f998996a4cfa4bd6745c2900",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 96,
"avg_line_length": 29.49019607843137,
"alnum_prop": 0.6865026595744681,
"repo_name": "scijava/scijava-common",
"id": "4000ab6d3fa4eccd92ec5e42e8b22a394a197841",
"size": "4449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/scijava/convert/ArrayToStringConverter.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "3336521"
}
],
"symlink_target": ""
} |
"use strict";
import { Platform } from "react-native";
var RNICloudUserToken = undefined;
if (Platform.OS === "ios") {
RNICloudUserToken = require("react-native").NativeModules.RNICloudUserToken;
}
module.exports = RNICloudUserToken;
| {
"content_hash": "6805dcd7baff19394df1f9b54ad07ba4",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 78,
"avg_line_length": 26.444444444444443,
"alnum_prop": 0.7436974789915967,
"repo_name": "mikaeladlers/react-native-icloud-user-token",
"id": "3a05a4cdeb430d8a0ba078a3e89cabfbd738f63a",
"size": "238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "238"
},
{
"name": "Objective-C",
"bytes": "1437"
},
{
"name": "Ruby",
"bytes": "670"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace GrumPHP\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use GrumPHP\Configuration\GrumPHP;
use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\TaskInterface;
use GrumPHP\TestSuite\TestSuiteInterface;
use SplPriorityQueue;
class TasksCollection extends ArrayCollection
{
public function filterByContext(ContextInterface $context): self
{
return $this->filter(function (TaskInterface $task) use ($context) {
return $task->canRunInContext($context);
});
}
public function filterByTestSuite(?TestSuiteInterface $testSuite = null): self
{
if (null === $testSuite) {
return $this;
}
return $this->filter(function (TaskInterface $task) use ($testSuite) {
return \in_array($task->getName(), $testSuite->getTaskNames(), true);
});
}
/**
* @param string[] $tasks
*/
public function filterByTaskNames(array $tasks): self
{
if (empty($tasks)) {
return $this;
}
return $this->filter(function (TaskInterface $task) use ($tasks) {
return \in_array($task->getName(), $tasks, true);
});
}
/**
* This method sorts the tasks by highest priority first.
*/
public function sortByPriority(GrumPHP $grumPHP): self
{
$priorityQueue = new SplPriorityQueue();
$stableSortIndex = PHP_INT_MAX;
foreach ($this->getIterator() as $task) {
$metadata = $grumPHP->getTaskMetadata($task->getName());
$priorityQueue->insert($task, [$metadata['priority'], $stableSortIndex--]);
}
return new self(array_values(iterator_to_array($priorityQueue)));
}
}
| {
"content_hash": "11a2bec9ac9ace33a68359fa33ed864b",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 87,
"avg_line_length": 28.467741935483872,
"alnum_prop": 0.6243626062322947,
"repo_name": "tombevers/grumphp",
"id": "4c16480a6e095b199b468241aa47c0968be55465",
"size": "1765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Collection/TasksCollection.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "519"
},
{
"name": "PHP",
"bytes": "744432"
},
{
"name": "Shell",
"bytes": "2676"
},
{
"name": "Smarty",
"bytes": "240"
}
],
"symlink_target": ""
} |
module Skeletor
module Rails
class Engine < ::Rails::Engine
isolate_namespace Skeletor::Rails
initializer "skeletor-rails.assets precompile" do |app|
app.config.assets.precompile += %w( normalize.css skeletor-preview.css fontawesome-webfont.eot fontawesome-webfont.svg fontawesome-webfont.ttf fontawesome-webfont.woff)
end
end
end
end
| {
"content_hash": "278071872ed6a731623a5bc46ff09fda",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 176,
"avg_line_length": 37.3,
"alnum_prop": 0.7345844504021448,
"repo_name": "mikereinmiller/skeletor-rails",
"id": "d0d6e5235e7b3cf027bd9ac4ee7c04281427616d",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/skeletor/rails/engine.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56697"
},
{
"name": "HTML",
"bytes": "4671"
},
{
"name": "JavaScript",
"bytes": "829"
},
{
"name": "Ruby",
"bytes": "9737"
}
],
"symlink_target": ""
} |
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a53d3885e412ea77cae6f0e562c6f83d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "e14e74a74e0df9c382702bebc6f9c4a3cc994adf",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Steviopsis/Steviopsis dryophyla/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import {jsonConfiguration} from '#core/types/object/json';
/**
* @typedef {{
* prefetch: (string|undefined),
* preconnect: (string|undefined),
* renderStartImplemented: (boolean|undefined),
* clientIdScope: (string|undefined),
* clientIdCookieName: (string|undefined),
* consentHandlingOverride: (boolean|undefined),
* fullWidthHeightRatio: (number|undefined),
* }}
*/
let AdNetworkConfigDef;
/**
* The config of each ad network.
* Please keep the list alphabetic order.
*
* yourNetworkName: { // This is the "type" attribute of <amp-ad>
*
* // List of URLs for prefetch
* prefetch: string|array
*
* // List of hosts for preconnect
* preconnect: string|array
*
* // The scope used to provide CIDs to ads
* clientIdScope: string
*
* // The cookie name to store the CID. In absence, `clientIdScope` is used.
* clientIdCookieName: string
*
* // If the ad network is willing to override the consent handling, which
* // by default is blocking ad load until the consent is accepted.
* consentHandlingOverride: boolean
*
* // Whether render-start API has been implemented
* // We highly recommend all networks to implement the API,
* // see details in the README.md
* renderStartImplemented: boolean
*
* // The width / height ratio for full width ad units.
* // If absent, it means the network does not support full width ad units.
* // Example value: 1.2
* fullWidthHeightRatio: number
* }
*
* @const {!Object<string, !JsonObject>}
*/
const adConfig = jsonConfiguration({
'_ping_': {
renderStartImplemented: true,
clientIdScope: '_PING_',
consentHandlingOverride: true,
},
'1wo': {},
'24smi': {
prefetch: 'https://jsn.24smi.net/smi.js',
preconnect: 'https://data.24smi.net',
},
'4wmarketplace': {
renderStartImplemented: true,
},
'a8': {
prefetch: 'https://statics.a8.net/amp/ad.js',
renderStartImplemented: true,
},
'a9': {
prefetch: 'https://z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US',
},
'accesstrade': {
prefetch: 'https://h.accesstrade.net/js/amp/amp.js',
},
'adagio': {
prefetch: 'https://js-ssl.neodatagroup.com/adagio_amp.js',
preconnect: [
'https://ad-aws-it.neodatagroup.com',
'https://tracker.neodatagroup.com',
],
renderStartImplemented: true,
},
'adblade': {
prefetch: 'https://web.adblade.com/js/ads/async/show.js',
preconnect: [
'https://staticd.cdn.adblade.com',
'https://static.adblade.com',
],
renderStartImplemented: true,
},
'adbutler': {
prefetch: 'https://servedbyadbutler.com/app.js',
},
'adenza': {
renderStartImplemented: true,
},
'adform': {},
'adfox': {
prefetch: 'https://yandex.ru/ads/system/context.js',
preconnect: ['https://yastatic.net/'],
renderStartImplemented: true,
},
'adgeneration': {
prefetch: 'https://i.socdm.com/sdk/js/adg-script-loader.js',
},
'adglare': {
renderStartImplemented: true,
},
'adhese': {
renderStartImplemented: true,
},
'adincube': {
renderStartImplemented: true,
},
'adition': {},
'adman': {},
'admanmedia': {
renderStartImplemented: true,
},
'admixer': {
renderStartImplemented: true,
preconnect: ['https://inv-nets.admixer.net', 'https://cdn.admixer.net'],
},
'adnuntius': {
prefetch: 'https://cdn.adnuntius.com/adn.js',
renderStartImplemented: true,
},
'adocean': {
consentHandlingOverride: true,
},
'adop': {},
'adpicker': {
renderStartImplemented: true,
},
'adplugg': {
prefetch: 'https://www.adplugg.com/serve/js/ad.js',
renderStartImplemented: true,
},
'adpon': {
prefetch: 'https://ad.adpon.jp/amp.js',
clientIdScope: 'AMP_ECID_ADPON',
},
'adpushup': {
prefetch: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
preconnect: 'https://cdn.adpushup.com',
},
'adreactor': {},
'ads2bid': {
renderStartImplemented: true,
},
'adsensor': {
prefetch: 'https://wfpscripts.webspectator.com/amp/adsensor-amp.js',
clientIdScope: 'amp_ecid_adensor',
renderStartImplemented: true,
},
'adservsolutions': {},
'adskeeper': {
renderStartImplemented: true,
preconnect: [
'https://jsc.adskeeper.com',
'https://servicer.adskeeper.com',
'https://s-img.adskeeper.com',
],
},
'adsloom': {
clientIdScope: 'AMP_ECID_ADSLOOM',
},
'adsnative': {
prefetch: 'https://static.adsnative.com/static/js/render.v1.js',
preconnect: 'https://api.adsnative.com',
},
'adspeed': {
preconnect: 'https://g.adspeed.net',
renderStartImplemented: true,
},
'adspirit': {},
'adstir': {
prefetch: 'https://js.ad-stir.com/js/adstir_async.js',
preconnect: 'https://ad.ad-stir.com',
},
'adstyle': {
prefetch: 'https://widgets.ad.style/amp.js',
preconnect: ['https://w.ad.style'],
},
'adtech': {
prefetch: 'https://s.aolcdn.com/os/ads/adsWrapper3.js',
preconnect: ['https://mads.at.atwola.com', 'https://aka-cdn.adtechus.com'],
},
'adtelligent': {
preconnect: ['https://s.adtelligent.com'],
renderStartImplemented: true,
},
'adthrive': {
prefetch: ['https://www.googletagservices.com/tag/js/gpt.js'],
preconnect: [
'https://partner.googleadservices.com',
'https://securepubads.g.doubleclick.net',
'https://tpc.googlesyndication.com',
],
renderStartImplemented: true,
},
'adunity': {
preconnect: ['https://content.adunity.com'],
renderStartImplemented: true,
},
'aduptech': {
prefetch: 'https://s.d.adup-tech.com/jsapi',
preconnect: [
'https://d.adup-tech.com',
'https://m.adup-tech.com',
'https://v.adup-tech.com',
],
renderStartImplemented: true,
consentHandlingOverride: true,
},
'adventive': {
preconnect: ['https://ads.adventive.com', 'https://amp.adventivedev.com'],
renderStartImplemented: true,
},
'adverline': {
prefetch: 'https://ads.adverline.com/richmedias/amp.js',
preconnect: ['https://adnext.fr'],
renderStartImplemented: true,
},
'adverticum': {},
'advertserve': {
renderStartImplemented: true,
},
'adyoulike': {
consentHandlingOverride: true,
prefetch: 'https://fo-static.omnitagjs.com/amp.js',
renderStartImplemented: true,
},
'adzerk': {},
'affiliateb': {
prefetch: 'https://track.affiliate-b.com/amp/a.js',
renderStartImplemented: true,
},
'aja': {
prefetch: [
'https://cdn.as.amanad.adtdp.com/sdk/asot-amp.js',
'https://cdn.as.amanad.adtdp.com/sdk/asot-v2.js',
],
preconnect: ['https://ad.as.amanad.adtdp.com'],
},
'appvador': {
prefetch: [
'https://cdn.apvdr.com/js/VastAdUnit.min.js',
'https://cdn.apvdr.com/js/VideoAd.min.js',
'https://cdn.apvdr.com/js/VideoAd3PAS.min.js',
'https://cdn.apvdr.com/js/VideoAdAutoPlay.min.js',
'https://cdn.apvdr.com/js/VideoAdNative.min.js',
],
renderStartImplemented: true,
},
'amoad': {
prefetch: ['https://j.amoad.com/js/a.js', 'https://j.amoad.com/js/n.js'],
preconnect: [
'https://d.amoad.com',
'https://i.amoad.com',
'https://m.amoad.com',
'https://v.amoad.com',
],
},
'amplified': {
preconnect: 'https://srv.clickfuse.com',
renderStartImplemented: true,
},
'andbeyond': {
prefetch: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
preconnect: 'https://cdn.andbeyond.media',
},
'aniview': {
renderStartImplemented: true,
},
'anyclip': {
prefetch:
'https://player.anyclip.com/anyclip-widget/lre-widget/prod/v1/src/lre.js',
preconnect: [
'https://trafficmanager.anyclip.com',
'https://lreprx-server.anyclip.com',
],
renderStartImplemented: true,
},
'appnexus': {
prefetch: 'https://acdn.adnxs.com/ast/ast.js',
preconnect: 'https://ib.adnxs.com',
renderStartImplemented: true,
},
'atomx': {
prefetch: 'https://s.ato.mx/p.js',
},
'avantisvideo': {
renderStartImplemented: true,
},
'beaverads': {
renderStartImplemented: true,
},
'beopinion': {
prefetch: 'https://widget.beop.io/sdk.js',
preconnect: [
'https://t.beop.io',
'https://s.beop.io',
'https://data.beop.io',
],
renderStartImplemented: true,
},
'bidtellect': {},
'blade': {
prefetch: 'https://sdk.streamrail.com/blade/sr.blade.js',
renderStartImplemented: true,
},
'brainy': {},
'bringhub': {
renderStartImplemented: true,
preconnect: ['https://static.bh-cdn.com', 'https://core-api.bringhub.io'],
},
'broadbandy': {
renderStartImplemented: true,
},
'broadstreetads': {
prefetch: 'https://cdn.broadstreetads.com/init-2.min.js',
renderStartImplemented: true,
},
'byplay': {},
'caajainfeed': {
prefetch: ['https://cdn.amanad.adtdp.com/sdk/ajaamp.js'],
preconnect: ['https://ad.amanad.adtdp.com'],
},
'capirs': {
renderStartImplemented: true,
},
'caprofitx': {
prefetch: [
'https://cdn.caprofitx.com/pfx.min.js',
'https://cdn.caprofitx.com/tags/amp/profitx_amp.js',
],
preconnect: 'https://ad.caprofitx.adtdp.com',
},
'cedato': {
renderStartImplemented: true,
},
'chargeads': {}, // Deprecated, to be removed on 2019-05-23
'colombia': {
prefetch: 'https://static.clmbtech.com/ad/commons/js/colombia-amp.js',
},
'colombiafeed': {
prefetch:
'https://static.clmbtech.com/c1e/static/themes/js/colombiafeed-amp.js',
},
'conative': {
renderStartImplemented: true,
},
'connatix': {
renderStartImplemented: true,
},
'contentad': {},
'criteo': {
prefetch: 'https://static.criteo.net/js/ld/publishertag.js',
preconnect: 'https://cas.criteo.com',
},
'csa': {
prefetch: 'https://www.google.com/adsense/search/ads.js',
},
'dable': {
preconnect: [
'https://static.dable.io',
'https://api.dable.io',
'https://images.dable.io',
],
renderStartImplemented: true,
},
'dex': {
renderStartImplemented: true,
},
'digiteka': {
renderStartImplemented: true,
},
'directadvert': {
renderStartImplemented: true,
},
'distroscale': {
preconnect: [
'https://c.jsrdn.com',
'https://s.jsrdn.com',
'https://i.jsrdn.com',
],
renderStartImplemented: true,
},
'dotandads': {
prefetch: 'https://amp.ad.dotandad.com/dotandadsAmp.js',
preconnect: 'https://bal.ad.dotandad.com',
},
'dynad': {
preconnect: ['https://t.dynad.net', 'https://tm.jsuol.com.br'],
},
'eadv': {
renderStartImplemented: true,
clientIdScope: 'AMP_ECID_EADV',
prefetch: [
'https://www.eadv.it/track/esr.min.js',
'https://www.eadv.it/track/ead.min.js',
],
},
'empower': {
prefetch: 'https://cdn.empower.net/sdk/amp-ad.min.js',
renderStartImplemented: true,
},
'engageya': {},
'epeex': {},
'eplanning': {
prefetch: 'https://us.img.e-planning.net/layers/epl-amp.js',
},
'exco': {
renderStartImplemented: true,
},
'ezoic': {
prefetch: [
'https://www.googletagservices.com/tag/js/gpt.js',
'https://g.ezoic.net/ezoic/ampad.js',
],
clientIdScope: 'AMP_ECID_EZOIC',
consentHandlingOverride: true,
renderStartImplemented: true,
},
'f1e': {
prefetch: 'https://img.ak.impact-ad.jp/util/f1e_amp.min.js',
},
'f1h': {
preconnect: 'https://img.ak.impact-ad.jp',
renderStartImplemented: true,
},
'fake': {},
'fake-delayed': {
renderStartImplemented: true,
},
'feedad': {
clientIdScope: '__fa_amp',
prefetch: 'https://web.feedad.com/sdk/feedad-async.js',
renderStartImplemented: true,
fullWidthHeightRatio: 16 / 9,
consentHandlingOverride: true,
},
'felmat': {
prefetch: 'https://t.felmat.net/js/fmamp.js',
renderStartImplemented: true,
},
'finative': {},
'firstimpression': {
prefetch: 'https://ecdn.firstimpression.io/static/js/fiamp.js',
preconnect: 'https://cdn.firstimpression.io',
renderStartImplemented: true,
consentHandlingOverride: true,
},
'flite': {},
'fluct': {
prefetch: ['https://pdn.adingo.jp/p.js'],
preconnect: [
'https://cdn-fluct.sh.adingo.jp',
'https://sh.adingo.jp',
'https://i.adingo.jp',
],
},
'forkmedia': {
renderStartImplemented: true,
},
'freewheel': {
prefetch: 'https://cdn.stickyadstv.com/prime-time/fw-amp.min.js',
renderStartImplemented: true,
},
'fusion': {
prefetch: 'https://assets.adtomafusion.net/fusion/latest/fusion-amp.min.js',
},
'gecko': {},
'genieessp': {
prefetch: 'https://js.gsspcln.jp/l/amp.js',
},
'giraff': {
renderStartImplemented: true,
},
'glomex': {
prefetch: 'https://player.glomex.com/integration/1/amp-embed.js',
},
'gmossp': {
prefetch: 'https://cdn.gmossp-sp.jp/ads/amp.js',
},
'gumgum': {
prefetch: 'https://js.gumgum.com/slot.js',
renderStartImplemented: true,
},
'holder': {
prefetch: 'https://i.holder.com.ua/js2/holder/ajax/ampv1.js',
preconnect: 'https://h.holder.com.ua',
renderStartImplemented: true,
},
'ibillboard': {},
'idealmedia': {
renderStartImplemented: true,
preconnect: [
'https://jsc.idealmedia.io',
'https://servicer.idealmedia.io',
'https://s-img.idealmedia.io/',
],
},
'imedia': {
prefetch: 'https://i.imedia.cz/js/im3.js',
renderStartImplemented: true,
},
'imobile': {
prefetch: 'https://spamp.i-mobile.co.jp/script/amp.js',
preconnect: 'https://spad.i-mobile.co.jp',
},
'imonomy': {
renderStartImplemented: true,
},
'improvedigital': {},
'industrybrains': {
prefetch: 'https://web.industrybrains.com/js/ads/async/show.js',
preconnect: [
'https://staticd.cdn.industrybrains.com',
'https://static.industrybrains.com',
],
renderStartImplemented: true,
},
'inmobi': {
prefetch: 'https://cf.cdn.inmobi.com/ad/inmobi.secure.js',
renderStartImplemented: true,
},
'innity': {
prefetch: 'https://cdn.innity.net/admanager.js',
preconnect: 'https://as.innity.com',
renderStartImplemented: true,
},
'insticator': {
preconnect: 'https://d3lcz8vpax4lo2.cloudfront.net', // can also be array if more than one URL needed
renderStartImplemented: true,
},
'insurads': {
prefetch: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
preconnect: [
'https://tpc.googlesyndication.com',
'https://adservice.google.com',
'https://cdn.insurads.com',
'https://services.insurads.com',
'https://messaging.insurads.com',
],
renderStartImplemented: true,
consentHandlingOverride: true,
},
'invibes': {
prefetch: 'https://k.r66net.com/GetAmpLink',
renderStartImplemented: true,
consentHandlingOverride: true,
},
'iprom': {
prefetch: 'https://cdn.ipromcloud.com/ipromNS.js',
},
'ix': {
prefetch: ['https://js-sec.indexww.com/apl/amp.js'],
preconnect: 'https://as-sec.casalemedia.com',
renderStartImplemented: true,
},
'jubna': {},
'kargo': {},
'ketshwa': {},
'kiosked': {
renderStartImplemented: true,
},
'jioads': {
renderStartImplemented: true,
},
'jixie': {
prefetch: ['https://scripts.jixie.media/jxamp.min.js'],
clientIdScope: '__jxamp',
clientIdCookieName: '_jx',
renderStartImplemented: true,
},
'kixer': {
prefetch: 'https://cdn.kixer.com/ad/load.js',
renderStartImplemented: true,
},
'kuadio': {},
'lentainform': {
renderStartImplemented: true,
preconnect: [
'https://jsc.lentainform.com',
'https://servicer.lentainform.com',
'https://s-img.lentainform.com',
],
},
'ligatus': {
prefetch: 'https://ssl.ligatus.com/render/ligrend.js',
renderStartImplemented: true,
},
'lockerdome': {
prefetch: 'https://cdn2.lockerdomecdn.com/_js/amp.js',
renderStartImplemented: true,
},
'logly': {
preconnect: ['https://l.logly.co.jp', 'https://cdn.logly.co.jp'],
renderStartImplemented: true,
},
'loka': {
prefetch: 'https://loka-cdn.akamaized.net/scene/amp.js',
preconnect: [
'https://scene-front.lokaplatform.com',
'https://loka-materials.akamaized.net',
],
renderStartImplemented: true,
},
'luckyads': {
renderStartImplemented: true,
},
'macaw': {
renderStartImplemented: true,
},
'mads': {
prefetch: 'https://eu2.madsone.com/js/tags.js',
},
'mantis-display': {
prefetch: 'https://assets.mantisadnetwork.com/mantodea.min.js',
preconnect: [
'https://mantodea.mantisadnetwork.com',
'https://res.cloudinary.com',
'https://resize.mantisadnetwork.com',
],
},
'marfeel': {
prefetch: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
preconnect: [
'https://live.mrf.io',
'https://tpc.googlesyndication.com',
'https://fastlane.rubiconproject.com',
'https://htlb.casalemedia.com',
'https://prg.smartadserver.com',
'https://ib.adnxs.com',
'https://bidder.criteo.com',
'https://marfeel-d.openx.net',
'https://ice.360yield.com',
'https://mbid.marfeelrev.com',
'https://adservice.google.com',
],
consentHandlingOverride: true,
},
'mantis-recommend': {
prefetch: 'https://assets.mantisadnetwork.com/recommend.min.js',
preconnect: [
'https://mantodea.mantisadnetwork.com',
'https://resize.mantisadnetwork.com',
],
},
'mediaad': {},
'medianet': {
preconnect: 'https://contextual.media.net',
renderStartImplemented: true,
},
'mediavine': {
prefetch: 'https://amp.mediavine.com/wrapper.min.js',
preconnect: [
'https://partner.googleadservices.com',
'https://securepubads.g.doubleclick.net',
'https://tpc.googlesyndication.com',
],
renderStartImplemented: true,
consentHandlingOverride: true,
},
'medyanet': {
renderStartImplemented: true,
},
'meg': {
renderStartImplemented: true,
},
'mgid': {
renderStartImplemented: true,
preconnect: [
'https://jsc.mgid.com',
'https://servicer.mgid.com',
'https://s-img.mgid.com',
],
},
'microad': {
prefetch: 'https://j.microad.net/js/camp.js',
preconnect: [
'https://s-rtb.send.microad.jp',
'https://s-rtb.send.microadinc.com',
'https://cache.send.microad.jp',
'https://cache.send.microadinc.com',
'https://deb.send.microad.jp',
],
},
'miximedia': {
renderStartImplemented: true,
},
'mixpo': {
prefetch: 'https://cdn.mixpo.com/js/loader.js',
preconnect: ['https://player1.mixpo.com', 'https://player2.mixpo.com'],
},
'monetizer101': {
renderStartImplemented: true,
},
'mox': {
prefetch: [
'https://ad.mox.tv/js/amp.min.js',
'https://ad.mox.tv/mox/mwayss_invocation.min.js',
],
renderStartImplemented: true,
},
'my6sense': {
renderStartImplemented: true,
},
'myfinance': {
preconnect: [
'https://a.myfidevs.io',
'https://static.myfinance.com',
'https://www.myfinance.com',
],
renderStartImplemented: true,
clientIdScope: 'AMP_ECID_GOOGLE',
},
'myoffrz': {
renderStartImplemented: true,
},
'mytarget': {
prefetch: 'https://ad.mail.ru/static/ads-async.js',
renderStartImplemented: true,
},
'myua': {
renderStartImplemented: true,
},
'mywidget': {
preconnect: 'https://likemore-fe.go.mail.ru',
prefetch: 'https://likemore-go.imgsmail.ru/widget_amp.js',
renderStartImplemented: true,
},
'nativeroll': {
prefetch: 'https://cdn01.nativeroll.tv/js/seedr-player.min.js',
},
'nativery': {
preconnect: 'https://cdn.nativery.com',
},
'nativo': {
prefetch: 'https://s.ntv.io/serve/load.js',
},
'navegg': {
renderStartImplemented: true,
},
'nend': {
prefetch: 'https://js1.nend.net/js/amp.js',
preconnect: ['https://output.nend.net', 'https://img1.nend.net'],
},
'netletix': {
preconnect: ['https://call.netzathleten-media.de'],
renderStartImplemented: true,
},
'noddus': {
prefetch: 'https://noddus.com/amp_loader.js',
renderStartImplemented: true,
},
'nokta': {
prefetch: 'https://static.virgul.com/theme/mockups/noktaamp/ampjs.js',
renderStartImplemented: true,
},
'nws': {},
'oblivki': {
renderStartImplemented: true,
},
'onead': {
prefetch: 'https://ad-specs.guoshipartners.com/static/js/onead-amp.min.js',
renderStartImplemented: true,
},
'onnetwork': {
renderStartImplemented: true,
},
'openadstream': {},
'openx': {
prefetch: 'https://www.googletagservices.com/tag/js/gpt.js',
preconnect: [
'https://partner.googleadservices.com',
'https://securepubads.g.doubleclick.net',
'https://tpc.googlesyndication.com',
],
renderStartImplemented: true,
},
'opinary': {
renderStartImplemented: true,
},
'outbrain': {
renderStartImplemented: true,
prefetch: 'https://widgets.outbrain.com/widgetAMP/outbrainAMP.min.js',
preconnect: ['https://odb.outbrain.com'],
consentHandlingOverride: true,
},
'pixels': {
prefetch: 'https://cdn.adsfactor.net/amp/pixels-amp.min.js',
clientIdCookieName: '__AF',
renderStartImplemented: true,
},
'playstream': {
prefetch: 'https://app.playstream.media/js/amp.js',
renderStartImplemented: true,
},
'plista': {},
'polymorphicads': {
prefetch: 'https://www.polymorphicads.jp/js/amp.js',
preconnect: [
'https://img.polymorphicads.jp',
'https://ad.polymorphicads.jp',
],
renderStartImplemented: true,
},
'popin': {
renderStartImplemented: true,
},
'postquare': {},
'ppstudio': {
renderStartImplemented: true,
},
'pressboard': {
renderStartImplemented: true,
},
'promoteiq': {},
'pubexchange': {},
'pubguru': {
renderStartImplemented: true,
},
'pubmatic': {
prefetch: 'https://ads.pubmatic.com/AdServer/js/amp.js',
},
'pubmine': {
prefetch: ['https://s.pubmine.com/head.js'],
preconnect: 'https://delivery.g.switchadhub.com',
renderStartImplemented: true,
},
'puffnetwork': {
prefetch: 'https://static.puffnetwork.com/amp_ad.js',
renderStartImplemented: true,
},
'pulse': {
prefetch: 'https://static.pulse.mail.ru/pulse-widget-amp.js',
renderStartImplemented: true,
},
'pulsepoint': {
prefetch: 'https://ads.contextweb.com/TagPublish/getjs.static.js',
preconnect: 'https://tag.contextweb.com',
},
'purch': {
prefetch: 'https://ramp.purch.com/serve/creative_amp.js',
renderStartImplemented: true,
},
'quoraad': {
prefetch: 'https://a.quora.com/amp_ad.js',
preconnect: 'https://ampad.quora.com',
renderStartImplemented: true,
},
'rakutenunifiedads': {
prefetch: 'https://s-cdn.rmp.rakuten.co.jp/js/amp.js',
renderStartImplemented: true,
},
'rbinfox': {
renderStartImplemented: true,
},
'rcmwidget': {
prefetch: 'https://rcmjs.rambler.ru/static/rcmw/rcmw-amp.js',
renderStartImplemented: true,
clientIdScope: '__rcmw_amp',
},
'readmo': {
renderStartImplemented: true,
},
'realclick': {
renderStartImplemented: true,
},
'recomad': {
renderStartImplemented: true,
},
'recreativ': {
prefetch: 'https://go.rcvlink.com/static/amp.js',
renderStartImplemented: true,
},
'relap': {
renderStartImplemented: true,
},
'relappro': {
prefetch: 'https://cdn.relappro.com/adservices/amp/relappro.amp.min.js',
preconnect: 'https://tags.relappro.com',
renderStartImplemented: true,
},
'remixd': {
preconnect: 'https://tags.remixd.com',
renderStartImplemented: true,
},
'revcontent': {
prefetch:
'https://labs-cdn.revcontent.com/build/amphtml/revcontent.amp.min.js',
preconnect: [
'https://trends.revcontent.com',
'https://cdn.revcontent.com',
'https://img.revcontent.com',
],
renderStartImplemented: true,
},
'revjet': {
prefetch: 'https://cdn.revjet.com/~cdn/JS/03/amp.js',
renderStartImplemented: true,
},
'rfp': {
prefetch: 'https://js.rfp.fout.jp/rfp-amp.js',
preconnect: 'https://ad.rfp.fout.jp',
renderStartImplemented: true,
},
'rnetplus': {},
'rubicon': {},
'runative': {
prefetch: 'https://cdn.run-syndicate.com/sdk/v1/n.js',
renderStartImplemented: true,
},
'sabavision': {
renderStartImplemented: true,
},
'sas': {
renderStartImplemented: true,
},
'seedingalliance': {},
'seedtag': {
prefetch: 'https://config.seedtag.com/omid/bridge/bridge.js',
preconnect: ['https://s.seedtag.com'],
consentHandlingOverride: true,
renderStartImplemented: true,
},
'sekindo': {
renderStartImplemented: true,
},
'sharethrough': {
renderStartImplemented: true,
},
'shemedia': {
prefetch: [
'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
'https://ads.shemedia.com/static/amp.js',
],
preconnect: [
'https://partner.googleadservices.com',
'https://tpc.googlesyndication.com',
'https://ads.blogherads.com',
],
renderStartImplemented: true,
},
'sklik': {
prefetch: 'https://c.imedia.cz/js/amp.js',
},
'slimcutmedia': {
preconnect: [
'https://sb.freeskreen.com',
'https://static.freeskreen.com',
'https://video.freeskreen.com',
],
renderStartImplemented: true,
},
'smartads': {
prefetch: 'https://smart-ads.biz/amp.js',
},
'smartadserver': {
prefetch: 'https://ec-ns.sascdn.com/diff/js/amp.v0.js',
preconnect: 'https://static.sascdn.com',
renderStartImplemented: true,
},
'smartclip': {
prefetch: 'https://cdn.smartclip.net/amp/amp.v0.js',
preconnect: 'https://des.smartclip.net',
renderStartImplemented: true,
},
'smi2': {
renderStartImplemented: true,
},
'smilewanted': {
prefetch: 'https://prebid.smilewanted.com/amp/amp.js',
preconnect: 'https://static.smilewanted.com',
renderStartImplemented: true,
},
'sogouad': {
prefetch: 'https://theta.sogoucdn.com/wap/js/aw.js',
renderStartImplemented: true,
},
'sortable': {
prefetch: 'https://www.googletagservices.com/tag/js/gpt.js',
preconnect: [
'https://tags-cdn.deployads.com',
'https://partner.googleadservices.com',
'https://securepubads.g.doubleclick.net',
'https://tpc.googlesyndication.com',
],
renderStartImplemented: true,
},
'sona': {
renderStartImplemented: true,
},
'sovrn': {
prefetch: 'https://ap.lijit.com/www/sovrn_amp/sovrn_ads.js',
},
'speakol': {
renderStartImplemented: true,
},
'spotx': {
preconnect: 'https://js.spotx.tv',
renderStartImplemented: true,
},
'springAds': {
preconnect: ['https://ib.adnxs.com'],
renderStartImplemented: true,
},
'ssp': {
prefetch: 'https://ssp.imedia.cz/static/js/ssp.js',
renderStartImplemented: true,
consentHandlingOverride: true,
},
'strossle': {
preconnect: [
'https://amp.spklw.com',
'https://widgets.sprinklecontent.com',
'https://images.sprinklecontent.com',
],
},
'sunmedia': {
preconnect: [
'https://static.sunmedia.tv',
'https://services.sunmedia.tv',
'https://creative.sunmedia.tv',
'https://vod.sunmedia.tv',
'https://mx-sunmedia.videoplaza.tv',
'https://es-sunicontent.videoplaza.tv',
'https://es-sunelespanol.videoplaza.tv',
'https://es-suncopperland.videoplaza.tv',
'https://search.spotxchange.com',
'https://tpc.googlesyndication.com',
],
clientIdScope: 'AMP_ECID_SUNMEDIA',
fullWidthHeightRatio: 1 / 1,
renderStartImplemented: true,
},
'svknative': {
renderStartImplemented: true,
prefetch: 'https://widget.svk-native.ru/js/embed.js',
},
'swoop': {
prefetch: 'https://www.swoop-amp.com/amp.js',
preconnect: ['https://www.swpsvc.com', 'https://client.swpcld.com'],
renderStartImplemented: true,
},
'taboola': {},
'tagon': {
prefetch: 'https://js.tagon.co/tagon-amp.min.js',
},
'tail': {
renderStartImplemented: true,
},
'tcsemotion': {
prefetch: 'https://ads.tcsemotion.com/www/delivery/amphb.js',
renderStartImplemented: true,
},
'teads': {
prefetch: 'https://a.teads.tv/media/format/v3/teads-format.min.js',
preconnect: [
'https://cdn2.teads.tv',
'https://t.teads.tv',
'https://r.teads.tv',
],
consentHandlingOverride: true,
},
'temedya': {
prefetch: [
'https://widget.cdn.vidyome.com/builds/loader-amp.js',
'https://vidyome-com.cdn.vidyome.com/vidyome/builds/widgets.js',
],
renderStartImplemented: true,
},
'torimochi': {
renderStartImplemented: true,
},
'tracdelight': {
prefetch: 'https://scripts.tracdelight.io/amp.js',
renderStartImplemented: true,
},
'trafficstars': {
prefetch: 'https://cdn.tsyndicate.com/sdk/v1/master.spot.js',
renderStartImplemented: true,
},
'triplelift': {},
'trugaze': {
clientIdScope: '__tg_amp',
renderStartImplemented: true,
},
'uas': {
prefetch: 'https://ads.pubmatic.com/AdServer/js/phoenix.js',
},
'ucfunnel': {
renderStartImplemented: true,
},
'uzou': {
preconnect: ['https://speee-ad.akamaized.net'],
renderStartImplemented: true,
},
'unruly': {
prefetch: 'https://video.unrulymedia.com/native/native-loader.js',
renderStartImplemented: true,
},
'valuecommerce': {
prefetch: 'https://amp.valuecommerce.com/amp_bridge.js',
preconnect: ['https://ad.jp.ap.valuecommerce.com'],
renderStartImplemented: true,
},
'vdoai': {
prefetch: 'https://a.vdo.ai/core/dependencies_amp/vdo.min.js',
renderStartImplemented: true,
},
'videointelligence': {
preconnect: 'https://s.vi-serve.com',
renderStartImplemented: true,
},
'videonow': {
renderStartImplemented: true,
},
'viralize': {
renderStartImplemented: true,
},
'vlyby': {
prefetch: 'https://cdn.vlyby.com/amp/qad/qad-outer2.js',
},
'vmfive': {
prefetch: 'https://man.vm5apis.com/dist/adn-web-sdk.js',
preconnect: ['https://vawpro.vm5apis.com', 'https://vahfront.vm5apis.com'],
renderStartImplemented: true,
},
'vox': {
renderStartImplemented: true,
},
'webediads': {
prefetch: 'https://eu1.wbdds.com/amp.min.js',
preconnect: ['https://goutee.top', 'https://mediaathay.org.uk'],
renderStartImplemented: true,
},
'weborama-display': {
prefetch: [
'https://cstatic.weborama.fr/js/advertiserv2/adperf_launch_1.0.0_scrambled.js',
'https://cstatic.weborama.fr/js/advertiserv2/adperf_core_1.0.0_scrambled.js',
],
},
'whopainfeed': {
prefetch: 'https://widget.infeed.com.ar/widget/widget-amp.js',
},
'widespace': {},
'wisteria': {
renderStartImplemented: true,
},
'wpmedia': {
prefetch: 'https://std.wpcdn.pl/wpjslib/wpjslib-amp.js',
preconnect: ['https://www.wp.pl', 'https://v.wpimg.pl'],
renderStartImplemented: true,
},
'wunderkind': {
preconnect: ['https://tag.wknd.ai', 'https://api.bounceexchange.com'],
renderStartImplemented: true,
fullWidthHeightRatio: 4 / 3,
},
'xlift': {
prefetch: 'https://cdn.x-lift.jp/resources/common/xlift_amp.js',
renderStartImplemented: true,
},
'yahoo': {
prefetch: 'https://s.yimg.com/aaq/ampad/display.js',
preconnect: 'https://us.adserver.yahoo.com',
},
'yahoofedads': {
renderStartImplemented: true,
},
'yahoojp': {
prefetch: [
'https://s.yimg.jp/images/listing/tool/yads/ydn/amp/amp.js',
'https://yads.c.yimg.jp/js/yads.js',
],
preconnect: 'https://yads.yahoo.co.jp',
},
'yahoonativeads': {
renderStartImplemented: true,
},
'yandex': {
prefetch: 'https://yandex.ru/ads/system/context.js',
preconnect: ['https://yastatic.net/'],
renderStartImplemented: true,
},
'yektanet': {
preconnect: [
'https://cdn.yektanet.com',
'https://cg-sc.yektanet.com',
'https://native.yektanet.com',
'https://nfetch.yektanet.net',
'https://rfetch.yektanet.net',
'https://scrapper.yektanet.com',
'https://ua.yektanet.com',
'https://bfetch.yektanet.com',
'https://mostatil.cdn.yektanet.com',
],
renderStartImplemented: true,
},
'yengo': {
renderStartImplemented: true,
},
'yieldbot': {
prefetch: [
'https://cdn.yldbt.com/js/yieldbot.intent.amp.js',
'https://msg.yldbt.com/js/ybmsg.html',
],
preconnect: 'https://i.yldbt.com',
},
'yieldmo': {
prefetch: 'https://static.yieldmo.com/ym.1.js',
preconnect: ['https://s.yieldmo.com', 'https://ads.yieldmo.com'],
renderStartImplemented: true,
},
'yieldone': {
prefetch: 'https://img.ak.impact-ad.jp/ic/pone/commonjs/yone-amp.js',
},
'yieldpro': {
preconnect: 'https://creatives.yieldpro.eu',
renderStartImplemented: true,
},
'zedo': {
prefetch: 'https://ss3.zedo.com/gecko/tag/Gecko.amp.min.js',
renderStartImplemented: true,
},
'zen': {
prefetch: 'https://zen.yandex.ru/widget-loader',
preconnect: ['https://yastatic.net/'],
renderStartImplemented: true,
},
'zergnet': {},
'zucks': {
preconnect: [
'https://j.zucks.net.zimg.jp',
'https://sh.zucks.net',
'https://k.zucks.net',
'https://static.zucks.net.zimg.jp',
],
},
'baidu': {
prefetch: 'https://dup.baidustatic.com/js/dm.js',
renderStartImplemented: true,
},
'sulvo': {},
});
export {adConfig};
| {
"content_hash": "4dddea6f0030bedcb9ff20d90da17477",
"timestamp": "",
"source": "github",
"line_count": 1532,
"max_line_length": 105,
"avg_line_length": 22.142297650130548,
"alnum_prop": 0.6132008725900595,
"repo_name": "mhc-gh/amphtml",
"id": "389bd0bfcde8e7d9d05dd2042d795ada8a932d99",
"size": "33922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ads/_config.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "256"
},
{
"name": "C++",
"bytes": "1602446"
},
{
"name": "CSS",
"bytes": "509363"
},
{
"name": "Go",
"bytes": "6528"
},
{
"name": "HTML",
"bytes": "2103955"
},
{
"name": "JavaScript",
"bytes": "19603394"
},
{
"name": "Python",
"bytes": "64581"
},
{
"name": "Shell",
"bytes": "20625"
},
{
"name": "Starlark",
"bytes": "33981"
},
{
"name": "TypeScript",
"bytes": "127235"
},
{
"name": "Yacc",
"bytes": "28669"
}
],
"symlink_target": ""
} |
describe("A function sum()", function() {
it("should be defined", function() {
expect( sum ).toBeDefined();
});
it("should return a number", function() {
var result = sum();
expect( typeof(result) ).toEqual("number");
});
it("should be defined with 2 parameters", function() {
expect( sum.length ).toEqual(2);
});
it("should return sum(2,3) = 5", function() {
expect( sum(2,3) ).toEqual(5);
});
it("should return sum(2,3) = 5", function() {
expect( sum(2,3) ).toEqual(5);
});
});
| {
"content_hash": "dc1d43f48e627cd6fa9a9fcf7c27d731",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 58,
"avg_line_length": 25.391304347826086,
"alnum_prop": 0.5171232876712328,
"repo_name": "juan-domenech/my-first-TDD",
"id": "fa4d88249524e3829313f02556ca88e5eefd1f19",
"size": "584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/addSpec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "5083"
},
{
"name": "JavaScript",
"bytes": "138979"
}
],
"symlink_target": ""
} |
//
// MMPDFPageDecoderSpec.m
//
// Created by Markus Müller on 18.12.13.
// Copyright 2013 www.isnotnil.com. All rights reserved.
//
#import <Quartz/Quartz.h>
#import <Kiwi.h>
#import "MMPDFPageDecoder.h"
#import "MMMacros.h"
SPEC_BEGIN(MMPDFPageDecoderSpec)
describe(@"MMPDFPageDecoder", ^{
__block MMPDFPageDecoder *sut = nil;
__block CGImageRef imageRef = NULL;
__block PDFDocument *document = nil;
__block PDFPage *pdfPage = nil;
const NSUInteger expectedPixelSize = 100;
beforeAll(^{
NSURL *resource = [[NSBundle bundleForClass:[self class]] URLForResource:@"Test" withExtension:@"pdf"];
document = [[PDFDocument alloc] initWithURL:resource];
pdfPage = [document pageAtIndex:0];
});
afterAll(^{
document = nil;
pdfPage = nil;
});
context(@"when not creating with designated initializer", ^{
it(@"should throw an NSInternalInconsistencyException", ^{
[[theBlock(^{
sut = [[MMPDFPageDecoder alloc] init];
}) should] raiseWithName:NSInternalInconsistencyException];
});
});
context(@"when created with designated initializer from a PDFPage", ^{
beforeEach(^{
sut = [[MMPDFPageDecoder alloc] initWithItem:pdfPage maxPixelSize:expectedPixelSize];
});
afterEach(^{
sut = nil;
});
it(@"should exist", ^{
[[sut shouldNot] beNil];
});
it(@"should conform to MMImageDecoderProtocol", ^{
[[sut should] conformToProtocol:@protocol(MMImageDecoderProtocol)];
});
it(@"should respond to initWithItem:maxPixelSize:", ^{
[[sut should] respondToSelector:@selector(initWithItem:maxPixelSize:)];
});
it(@"should respond to CGImage", ^{
[[sut should] respondToSelector:@selector(CGImage)];
});
it(@"should respond to image", ^{
[[sut should] respondToSelector:@selector(image)];
});
context(NSStringFromSelector(@selector(CGImage)), ^{
beforeEach(^{
imageRef = sut.CGImage;
});
it(@"should return an image", ^{
[[theValue(imageRef != NULL) should] beTrue];
});
it(@"should have a width less or equal 100", ^{
[[theValue(CGImageGetWidth(imageRef)) should] beLessThanOrEqualTo:theValue(100)];
});
it(@"should have a height less or equal 100", ^{
[[theValue(CGImageGetHeight(imageRef)) should] beLessThanOrEqualTo:theValue(100)];
});
});
context(NSStringFromSelector(@selector(image)), ^{
__block NSImage *image = nil;
context(@"creating an image from a PDFPage", ^{
beforeAll(^{
image = sut.image;
});
afterAll(^{
image = nil;
});
it(@"should return an image", ^{
[[image shouldNot] beNil];
});
it(@"should return an NSImage", ^{
[[image should] beKindOfClass:[NSImage class]];
});
});
});
});
context(@"when created with designated initializer from a CGPDFPageRef", ^{
beforeEach(^{
sut = [[MMPDFPageDecoder alloc] initWithItem:(id)[pdfPage pageRef] maxPixelSize:expectedPixelSize];
});
afterEach(^{
sut = nil;
});
context(NSStringFromSelector(@selector(CGImage)), ^{
beforeEach(^{
imageRef = sut.CGImage;
});
it(@"should return an image", ^{
[[theValue(imageRef != NULL) should] beTrue];
});
it(@"should have a width less or equal 100", ^{
[[theValue(CGImageGetWidth(imageRef)) should] beLessThanOrEqualTo:theValue(100)];
});
it(@"should have a height less or equal 100", ^{
[[theValue(CGImageGetHeight(imageRef)) should] beLessThanOrEqualTo:theValue(100)];
});
});
context(NSStringFromSelector(@selector(image)), ^{
__block NSImage *image = nil;
context(@"creating an image from a PDFPage", ^{
beforeAll(^{
image = sut.image;
});
afterAll(^{
image = nil;
});
it(@"should return an image", ^{
[[image shouldNot] beNil];
});
it(@"should return an NSImage", ^{
[[image should] beKindOfClass:[NSImage class]];
});
});
});
});
context(@"when created with designated initializer with a nil item", ^{
it(@"should raise an NSInternalInconsistencyException", ^{
[[theBlock(^{
sut = [[MMPDFPageDecoder alloc] initWithItem:nil maxPixelSize:expectedPixelSize];
}) should] raiseWithName:NSInternalInconsistencyException];
});
});
context(@"when created with designated initializer with a zero maxImageSize", ^{
it(@"should raise an NSInternalInconsistencyException", ^{
[[theBlock(^{
sut = [[MMPDFPageDecoder alloc] initWithItem:pdfPage maxPixelSize:0];
}) should] raiseWithName:NSInternalInconsistencyException];
});
});
});
SPEC_END
| {
"content_hash": "2d46bcb76fc3743b6e11118319270790",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 105,
"avg_line_length": 28.93548387096774,
"alnum_prop": 0.6595317725752509,
"repo_name": "mmllr/MMFlowView",
"id": "fbce44b9bee6c88199bdd771175dd43e719fe607",
"size": "5642",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Classes/osx/Specs/MMPDFPageDecoderSpec.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "616284"
},
{
"name": "Python",
"bytes": "70426"
},
{
"name": "Rich Text Format",
"bytes": "436"
},
{
"name": "Ruby",
"bytes": "9787"
},
{
"name": "Shell",
"bytes": "3239"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/mediatailor/MediaTailor_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/mediatailor/model/ChannelState.h>
#include <aws/core/utils/DateTime.h>
#include <aws/mediatailor/model/SlateSource.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/mediatailor/model/ResponseOutputItem.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace MediaTailor
{
namespace Model
{
class AWS_MEDIATAILOR_API UpdateChannelResult
{
public:
UpdateChannelResult();
UpdateChannelResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
UpdateChannelResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The ARN of the channel.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetArn(const Aws::String& value) { m_arn = value; }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetArn(Aws::String&& value) { m_arn = std::move(value); }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetArn(const char* value) { m_arn.assign(value); }
/**
* <p>The ARN of the channel.</p>
*/
inline UpdateChannelResult& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>The ARN of the channel.</p>
*/
inline UpdateChannelResult& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>The ARN of the channel.</p>
*/
inline UpdateChannelResult& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>The name of the channel.</p>
*/
inline const Aws::String& GetChannelName() const{ return m_channelName; }
/**
* <p>The name of the channel.</p>
*/
inline void SetChannelName(const Aws::String& value) { m_channelName = value; }
/**
* <p>The name of the channel.</p>
*/
inline void SetChannelName(Aws::String&& value) { m_channelName = std::move(value); }
/**
* <p>The name of the channel.</p>
*/
inline void SetChannelName(const char* value) { m_channelName.assign(value); }
/**
* <p>The name of the channel.</p>
*/
inline UpdateChannelResult& WithChannelName(const Aws::String& value) { SetChannelName(value); return *this;}
/**
* <p>The name of the channel.</p>
*/
inline UpdateChannelResult& WithChannelName(Aws::String&& value) { SetChannelName(std::move(value)); return *this;}
/**
* <p>The name of the channel.</p>
*/
inline UpdateChannelResult& WithChannelName(const char* value) { SetChannelName(value); return *this;}
/**
* <p>Indicates whether the channel is in a running state or not.</p>
*/
inline const ChannelState& GetChannelState() const{ return m_channelState; }
/**
* <p>Indicates whether the channel is in a running state or not.</p>
*/
inline void SetChannelState(const ChannelState& value) { m_channelState = value; }
/**
* <p>Indicates whether the channel is in a running state or not.</p>
*/
inline void SetChannelState(ChannelState&& value) { m_channelState = std::move(value); }
/**
* <p>Indicates whether the channel is in a running state or not.</p>
*/
inline UpdateChannelResult& WithChannelState(const ChannelState& value) { SetChannelState(value); return *this;}
/**
* <p>Indicates whether the channel is in a running state or not.</p>
*/
inline UpdateChannelResult& WithChannelState(ChannelState&& value) { SetChannelState(std::move(value)); return *this;}
/**
* <p>The timestamp of when the channel was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; }
/**
* <p>The timestamp of when the channel was created.</p>
*/
inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTime = value; }
/**
* <p>The timestamp of when the channel was created.</p>
*/
inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTime = std::move(value); }
/**
* <p>The timestamp of when the channel was created.</p>
*/
inline UpdateChannelResult& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;}
/**
* <p>The timestamp of when the channel was created.</p>
*/
inline UpdateChannelResult& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;}
/**
* <p>Contains information about the slate used to fill gaps between programs in
* the schedule.</p>
*/
inline const SlateSource& GetFillerSlate() const{ return m_fillerSlate; }
/**
* <p>Contains information about the slate used to fill gaps between programs in
* the schedule.</p>
*/
inline void SetFillerSlate(const SlateSource& value) { m_fillerSlate = value; }
/**
* <p>Contains information about the slate used to fill gaps between programs in
* the schedule.</p>
*/
inline void SetFillerSlate(SlateSource&& value) { m_fillerSlate = std::move(value); }
/**
* <p>Contains information about the slate used to fill gaps between programs in
* the schedule.</p>
*/
inline UpdateChannelResult& WithFillerSlate(const SlateSource& value) { SetFillerSlate(value); return *this;}
/**
* <p>Contains information about the slate used to fill gaps between programs in
* the schedule.</p>
*/
inline UpdateChannelResult& WithFillerSlate(SlateSource&& value) { SetFillerSlate(std::move(value)); return *this;}
/**
* <p>The timestamp of when the channel was last modified.</p>
*/
inline const Aws::Utils::DateTime& GetLastModifiedTime() const{ return m_lastModifiedTime; }
/**
* <p>The timestamp of when the channel was last modified.</p>
*/
inline void SetLastModifiedTime(const Aws::Utils::DateTime& value) { m_lastModifiedTime = value; }
/**
* <p>The timestamp of when the channel was last modified.</p>
*/
inline void SetLastModifiedTime(Aws::Utils::DateTime&& value) { m_lastModifiedTime = std::move(value); }
/**
* <p>The timestamp of when the channel was last modified.</p>
*/
inline UpdateChannelResult& WithLastModifiedTime(const Aws::Utils::DateTime& value) { SetLastModifiedTime(value); return *this;}
/**
* <p>The timestamp of when the channel was last modified.</p>
*/
inline UpdateChannelResult& WithLastModifiedTime(Aws::Utils::DateTime&& value) { SetLastModifiedTime(std::move(value)); return *this;}
/**
* <p>The channel's output properties.</p>
*/
inline const Aws::Vector<ResponseOutputItem>& GetOutputs() const{ return m_outputs; }
/**
* <p>The channel's output properties.</p>
*/
inline void SetOutputs(const Aws::Vector<ResponseOutputItem>& value) { m_outputs = value; }
/**
* <p>The channel's output properties.</p>
*/
inline void SetOutputs(Aws::Vector<ResponseOutputItem>&& value) { m_outputs = std::move(value); }
/**
* <p>The channel's output properties.</p>
*/
inline UpdateChannelResult& WithOutputs(const Aws::Vector<ResponseOutputItem>& value) { SetOutputs(value); return *this;}
/**
* <p>The channel's output properties.</p>
*/
inline UpdateChannelResult& WithOutputs(Aws::Vector<ResponseOutputItem>&& value) { SetOutputs(std::move(value)); return *this;}
/**
* <p>The channel's output properties.</p>
*/
inline UpdateChannelResult& AddOutputs(const ResponseOutputItem& value) { m_outputs.push_back(value); return *this; }
/**
* <p>The channel's output properties.</p>
*/
inline UpdateChannelResult& AddOutputs(ResponseOutputItem&& value) { m_outputs.push_back(std::move(value)); return *this; }
/**
* <p>The channel's playback mode.</p>
*/
inline const Aws::String& GetPlaybackMode() const{ return m_playbackMode; }
/**
* <p>The channel's playback mode.</p>
*/
inline void SetPlaybackMode(const Aws::String& value) { m_playbackMode = value; }
/**
* <p>The channel's playback mode.</p>
*/
inline void SetPlaybackMode(Aws::String&& value) { m_playbackMode = std::move(value); }
/**
* <p>The channel's playback mode.</p>
*/
inline void SetPlaybackMode(const char* value) { m_playbackMode.assign(value); }
/**
* <p>The channel's playback mode.</p>
*/
inline UpdateChannelResult& WithPlaybackMode(const Aws::String& value) { SetPlaybackMode(value); return *this;}
/**
* <p>The channel's playback mode.</p>
*/
inline UpdateChannelResult& WithPlaybackMode(Aws::String&& value) { SetPlaybackMode(std::move(value)); return *this;}
/**
* <p>The channel's playback mode.</p>
*/
inline UpdateChannelResult& WithPlaybackMode(const char* value) { SetPlaybackMode(value); return *this;}
/**
* <p>The tags assigned to the channel.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tags = value; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tags = std::move(value); }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(const Aws::String& key, const Aws::String& value) { m_tags.emplace(key, value); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(Aws::String&& key, const Aws::String& value) { m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(const Aws::String& key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(Aws::String&& key, Aws::String&& value) { m_tags.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(const char* key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(Aws::String&& key, const char* value) { m_tags.emplace(std::move(key), value); return *this; }
/**
* <p>The tags assigned to the channel.</p>
*/
inline UpdateChannelResult& AddTags(const char* key, const char* value) { m_tags.emplace(key, value); return *this; }
private:
Aws::String m_arn;
Aws::String m_channelName;
ChannelState m_channelState;
Aws::Utils::DateTime m_creationTime;
SlateSource m_fillerSlate;
Aws::Utils::DateTime m_lastModifiedTime;
Aws::Vector<ResponseOutputItem> m_outputs;
Aws::String m_playbackMode;
Aws::Map<Aws::String, Aws::String> m_tags;
};
} // namespace Model
} // namespace MediaTailor
} // namespace Aws
| {
"content_hash": "7de72fa9f2cc869e43975c73e26e3e4b",
"timestamp": "",
"source": "github",
"line_count": 374,
"max_line_length": 147,
"avg_line_length": 32.106951871657756,
"alnum_prop": 0.6415722851432378,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "ee446249fd5c77be97ee1cd9e991bbb2b6ab9470",
"size": "12127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-mediatailor/include/aws/mediatailor/model/UpdateChannelResult.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
<p align="center">
<img src="https://github.com/fishtown-analytics/dbt/blob/master/etc/dbt-horizontal.png?raw=true" alt="dbt logo"/>
</p>
**[dbt](https://www.getdbt.com/)** (data build tool) enables data analysts and engineers to transform their data using the same practices that software engineers use to build applications.
dbt is the T in ELT. Organize, cleanse, denormalize, filter, rename, and pre-aggregate the raw data in your warehouse so that it's ready for analysis.
## dbt-snowflake
The `dbt-snowflake` package contains all of the code required to make dbt operate on a Snowflake database. For
more information on using dbt with Snowflake, consult [the docs](https://docs.getdbt.com/docs/profile-snowflake).
## Find out more
- Check out the [Introduction to dbt](https://dbt.readme.io/docs/introduction).
- Read the [dbt Viewpoint](https://dbt.readme.io/docs/viewpoint).
## Join thousands of analysts in the dbt community
- Join the [chat](http://slack.getdbt.com/) on Slack.
- Find community posts on [dbt Discourse](https://discourse.getdbt.com).
## Reporting bugs and contributing code
- Want to report a bug or request a feature? Let us know on [Slack](http://slack.getdbt.com/), or open [an issue](https://github.com/fishtown-analytics/dbt/issues/new).
- Want to help us build dbt? Check out the [Contributing Getting Started Guide](/CONTRIBUTING.md)
## Code of Conduct
Everyone interacting in the dbt project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [PyPA Code of Conduct](https://www.pypa.io/en/latest/code-of-conduct/).
| {
"content_hash": "31d3c64fe4b4abf0c42eecfe36649943",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 196,
"avg_line_length": 50.34375,
"alnum_prop": 0.7467411545623837,
"repo_name": "fishtown-analytics/dbt",
"id": "fc7ee257401f5ba933397f8167f6ae757b86c308",
"size": "1611",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev/octavius-catto",
"path": "plugins/snowflake/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1247"
},
{
"name": "HTML",
"bytes": "1343185"
},
{
"name": "Makefile",
"bytes": "997"
},
{
"name": "PLpgSQL",
"bytes": "1649"
},
{
"name": "Python",
"bytes": "2059566"
},
{
"name": "Shell",
"bytes": "2419"
},
{
"name": "TSQL",
"bytes": "396955"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.2//EN"
"http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<!-- THIS CHECKSYTLE CONFIGURATION IS SIMILAR TO THE ONE USED BY SQUARE INC. IF YOU WANT TO
CONFIGURE YOUR IDE TO USE THIS CHECKSTYLE TAKE A LOOK AT https://github.com/square/java-code-styles-->
<module name="Checker">
<!--module name="NewlineAtEndOfFile"/-->
<!--<module name="FileLength"/>-->
<module name="FileTabCharacter"/>
<!-- Trailing spaces -->
<module name="RegexpSingleline">
<property name="format" value="\s+$"/>
<property name="message" value="Line has trailing spaces."/>
</module>
<!-- For each spacing -->
<module name="RegexpSingleline">
<property name="format" value="^\s*for \(.*?([^ ]:|:[^ ])"/>
<property name="message" value="Space needed around ':' character."/>
</module>
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sf.net/config_sizes.html -->
<module name="LineLength">
<property name="max" value="120"/>
</module>
<module name="TreeWalker">
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sf.net/config_naming.html -->
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="TypeName"/>
<module name="ConstantName"/>
<!-- Checks for imports -->
<!-- See http://checkstyle.sf.net/config_import.html -->
<module name="AvoidStarImport"/>
<module name="IllegalImport"/>
<!-- defaults to sun.* packages -->
<module name="RedundantImport"/>
<module name="UnusedImports">
<property name="processJavadoc" value="true"/>
</module>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="GenericWhitespace"/>
<module name="EmptyForIteratorPad"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<!-- Modifier Checks -->
<!-- See http://checkstyle.sf.net/config_modifiers.html -->
<module name="RedundantModifier"/>
<!-- Checks for blocks. You know, those {}'s -->
<!-- See http://checkstyle.sf.net/config_blocks.html -->
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>
<!-- Checks for common coding problems -->
<!-- See http://checkstyle.sf.net/config_coding.html -->
<module name="CovariantEquals"/>
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<module name="IllegalInstantiation"/>
<module name="MissingSwitchDefault"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sf.net/config_misc.html -->
<module name="UpperEll"/>
</module>
</module>
| {
"content_hash": "3fb29e5b8ef92b0c5ce8db7f3025cd46",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 103,
"avg_line_length": 36.53846153846154,
"alnum_prop": 0.5930827067669173,
"repo_name": "voghDev/PdfViewPager",
"id": "124da7f7928e7caeed83340f8e66723ca320e073",
"size": "3325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/checkstyle.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "171744"
}
],
"symlink_target": ""
} |
'use strict';
/**
* @class
* Initializes a new instance of the ServerPropertiesForCreate class.
* @constructor
* The properties used to create a new server.
*
* @member {number} [storageMB] The maximum storage allowed for a server.
*
* @member {string} [version] Server version. Possible values include: '5.6',
* '5.7'
*
* @member {string} [sslEnforcement] Enable ssl enforcement or not when connect
* to server. Possible values include: 'Enabled', 'Disabled'
*
* @member {string} createMode Polymorphic Discriminator
*
*/
class ServerPropertiesForCreate {
constructor() {
}
/**
* Defines the metadata of ServerPropertiesForCreate
*
* @returns {object} metadata of ServerPropertiesForCreate
*
*/
mapper() {
return {
required: false,
serializedName: 'ServerPropertiesForCreate',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'createMode',
clientName: 'createMode'
},
uberParent: 'ServerPropertiesForCreate',
className: 'ServerPropertiesForCreate',
modelProperties: {
storageMB: {
required: false,
serializedName: 'storageMB',
constraints: {
InclusiveMinimum: 1024
},
type: {
name: 'Number'
}
},
version: {
required: false,
serializedName: 'version',
type: {
name: 'String'
}
},
sslEnforcement: {
required: false,
serializedName: 'sslEnforcement',
type: {
name: 'Enum',
allowedValues: [ 'Enabled', 'Disabled' ]
}
},
createMode: {
required: true,
serializedName: 'createMode',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ServerPropertiesForCreate;
| {
"content_hash": "4b8325727294e817f8ea2a48ccacc2b0",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 79,
"avg_line_length": 24.27710843373494,
"alnum_prop": 0.539454094292804,
"repo_name": "AuxMon/azure-sdk-for-node",
"id": "27926fb7d57b883e1680ec46b6f38206b18ad817",
"size": "2332",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/mysqlManagement/lib/models/serverPropertiesForCreate.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "48689677"
},
{
"name": "Shell",
"bytes": "437"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCodeTranslationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('code_translations', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('code_id')->unsigned();
$table->string('description');
$table->longtext('notes')->nullable();
$table->string('locale')->index();
$table->unique(['code_id', 'locale']);
$table->foreign('code_id')->references('id')->on('codes')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('code_translations');
}
}
| {
"content_hash": "76f280d548cc0684e7a6cf2f52cfd2af",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 91,
"avg_line_length": 25.83783783783784,
"alnum_prop": 0.5606694560669456,
"repo_name": "lasselehtinen/onix-codelist",
"id": "6ccdf0501bd6d7356fad5c421872261f786855ff",
"size": "956",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2016_11_24_122306_create_code_translation_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "API Blueprint",
"bytes": "3359"
},
{
"name": "CSS",
"bytes": "72"
},
{
"name": "HTML",
"bytes": "11857"
},
{
"name": "JavaScript",
"bytes": "1411"
},
{
"name": "PHP",
"bytes": "114245"
}
],
"symlink_target": ""
} |
package rocks.xmpp.core.stanza.model.errors;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* The implementation of the {@code <remote-server-timeout/>} stanza error.
* <blockquote>
* <p><cite><a href="http://xmpp.org/rfcs/rfc6120.html#stanzas-error-conditions-remote-server-timeout">8.3.3.17. remote-server-timeout</a></cite></p>
* <p>A remote server or service specified as part or all of the JID of the intended recipient (or needed to fulfill a request) was resolved but communications could not be established within a reasonable amount of time (e.g., an XML stream cannot be established at the resolved IP address and port, or an XML stream can be established but stream negotiation fails because of problems with TLS, SASL, Server Dialback, etc.); the associated error type SHOULD be "wait" (unless the error is of a more permanent nature, e.g., the remote server is found but it cannot be authenticated or it violates security policies).</p>
* </blockquote>
* This class is a singleton.
*
* @see #REMOTE_SERVER_TIMEOUT
*/
@XmlRootElement(name = "remote-server-timeout")
@XmlType(factoryMethod = "create")
final class RemoteServerTimeout extends Condition {
RemoteServerTimeout() {
}
private static RemoteServerTimeout create() {
return (RemoteServerTimeout) REMOTE_SERVER_TIMEOUT;
}
} | {
"content_hash": "ec3157eeac65e97b91c20f13d2685cb8",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 619,
"avg_line_length": 50.25,
"alnum_prop": 0.736318407960199,
"repo_name": "jeozey/XmppServerTester",
"id": "7c8e681f8c1cf93ea44b0b51a7fe857a99b436a3",
"size": "2582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xmpp-core/src/main/java/rocks/xmpp/core/stanza/model/errors/RemoteServerTimeout.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3433"
},
{
"name": "Java",
"bytes": "4408957"
}
],
"symlink_target": ""
} |
package be.xvrt.times.util;
import android.app.Fragment;
import android.app.FragmentManager;
import be.xvrt.times.R;
public final class FragmentUtil {
private FragmentUtil() {
}
public static void addOnlyOnce(FragmentManager fragmentManager, Fragment fragment, String tag) {
fragmentManager.executePendingTransactions();
Fragment existingFragment = fragmentManager.findFragmentByTag(tag);
if (existingFragment == null) {
fragmentManager.beginTransaction()
.add(R.id.main_fragment_container, fragment, tag)
.commit();
}
}
}
| {
"content_hash": "51574f9a6d1d70fcb176ef3d0fa5dfad",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 100,
"avg_line_length": 27.956521739130434,
"alnum_prop": 0.6547433903576982,
"repo_name": "XavierTalpe/android-toptal-24-times",
"id": "9c72e3e94db030aaf0b8f6e8880206443de412c3",
"size": "643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "24-Times/src/main/java/be/xvrt/times/util/FragmentUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "46954"
}
],
"symlink_target": ""
} |
set -e
set -v
sudo add-apt-repository ppa:natefoo/slurm-drmaa -y
sudo apt update
sudo apt install -y libxml2-dev libxslt1-dev libcurl4-openssl-dev python-pycurl openssh-server
#pip install -r requirements$REQUIREMENTS_SUFFIX.txt --use-mirrors || true
#pip install -r dev-requirements.txt --use-mirrors || true
#pip install coveralls # Required fro coveralls reporting.
sudo apt install -y slurm-wlm slurm-wlm-torque munge slurm-drmaa1 slurm-drmaa-dev
sudo apt install -y libswitch-perl libgnutls28-dev # A missing dependency of slurm-llnl-torque
# DEBIAN_FRONTEND=noninteractive sudo apt install htcondor ## htcondor installation
yes | sudo /usr/sbin/create-munge-key
sudo service munge start
sudo python scripts/configure_test_slurm.py
echo "export DRMAA_LIBRARY_PATH=/usr/lib/slurm-drmaa/lib/libdrmaa.so" >> local_env.sh
#echo ". $VIRTUAL_ENV/bin/activate" >> local_env.sh
echo "umask 002" >> local_env.sh
sudo useradd --home-dir /home/u1 --shell /bin/bash --create-home --comment TEST,,, --groups $(id -gn) u1 ## Create user for run-as-user test.
mkdir -p ~/.ssh && cp test_data/testkey.pub ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys
| {
"content_hash": "23b1e233363cbb616a7bc38853f598ee",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 142,
"avg_line_length": 52.63636363636363,
"alnum_prop": 0.7573402417962003,
"repo_name": "natefoo/pulsar",
"id": "10a00dd59144dd1683880fc26c50b5b338540d11",
"size": "1171",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".ci/setup_tests.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "241"
},
{
"name": "Dockerfile",
"bytes": "5135"
},
{
"name": "Makefile",
"bytes": "5889"
},
{
"name": "Python",
"bytes": "659280"
},
{
"name": "Shell",
"bytes": "17011"
}
],
"symlink_target": ""
} |
require 'spec_helper'
VALID_FIXTURES = Dir.glob(File.join(File.expand_path('../..', __FILE__), 'spec', 'fixtures', 'valid_css', '*'))
INVALID_FIXTURES = Dir.glob(File.join(File.expand_path('../..', __FILE__), 'spec', 'fixtures', 'invalid_css', '*'))
describe CssValidator do
webpage_class = Class.new do
include ActiveModel::Validations
attr_accessor :css
validates :css, css: true
end
webpage_class_nil_allowed = Class.new do
include ActiveModel::Validations
attr_accessor :css
validates :css, css: { allow_nil: true }
end
webpage_class_blank_allowed = Class.new do
include ActiveModel::Validations
attr_accessor :css
validates :css, css: { allow_blank: true }
end
describe "validating css" do
let!(:errors) { [ "is invalid" ] }
subject { webpage_class.new }
it "should pass when css empty" do
subject.valid?.should be_true
subject.errors[:css].should be_empty
end
VALID_FIXTURES.each do |css_file|
it "should pass when css is valid" do
css_content = File.read(css_file)
subject.css = css_content
subject.valid?.should be_true
subject.errors[:css].should be_empty
end
end
INVALID_FIXTURES.each do |css_file|
it "should fail when css is not valid" do
css_content = File.read(css_file)
subject.css = css_content
subject.valid?.should be_false
subject.errors[:css].should == errors
end
end
end
describe "Can allow nil" do
subject { webpage_class_nil_allowed.new }
it "should pass even if css isn't set" do
subject.css = nil
subject.should be_valid
subject.errors[:css].should be_empty
end
end
describe "Can allow blank" do
subject { webpage_class_blank_allowed.new }
it "should pass even if css is a blank string set" do
subject.css = ''
subject.should be_valid
subject.errors[:css].should be_empty
end
end
end
| {
"content_hash": "bd1157a122e45c07faa62b205f537a7e",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 115,
"avg_line_length": 26.68918918918919,
"alnum_prop": 0.64,
"repo_name": "siong1987/css_validator",
"id": "37adc264e33b4495f5015e5c8ed0e6500802bef0",
"size": "1975",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/css_validator_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "108"
},
{
"name": "Ruby",
"bytes": "4882"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class model_dashboard extends CI_Model{
var $table='member';
public function __construct(){
parent::__construct();
$this->load->database();
}
public function tampil_kategori(){
$this->db->select('nama_kategori_pekerjaan');
$query = $this->db->get('kategori_pekerjaan');
return $query->result();
}
}
?> | {
"content_hash": "d5e29dd444621797e2e3bac6b2abf308",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 63,
"avg_line_length": 17.17391304347826,
"alnum_prop": 0.660759493670886,
"repo_name": "RezaNurRochmat13/seekers",
"id": "abaf074dd0169751ea2964d73c908ea89d781941",
"size": "523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/model_dashboard.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "65832"
},
{
"name": "JavaScript",
"bytes": "112101"
},
{
"name": "PHP",
"bytes": "10261403"
}
],
"symlink_target": ""
} |
package io.opencensus.trace;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auto.value.AutoValue;
import javax.annotation.concurrent.Immutable;
/**
* A class that enables overriding the default values used when ending a {@link Span}. Allows
* overriding the {@link Status status}.
*/
@Immutable
@AutoValue
public abstract class EndSpanOptions {
/** The default {@code EndSpanOptions}. */
public static final EndSpanOptions DEFAULT = builder().build();
/**
* Returns a new {@link Builder} with default options.
*
* @return a new {@code Builder} with default options.
*/
public static Builder builder() {
return new AutoValue_EndSpanOptions.Builder().setStatus(Status.OK);
}
/**
* Returns the status.
*
* @return the status.
*/
public abstract Status getStatus();
/** Builder class for {@link EndSpanOptions}. */
@AutoValue.Builder
public abstract static class Builder {
/**
* Sets the status for the {@link Span}.
*
* <p>If set, this will override the default {@code Span} status. Default is {@link Status#OK}.
*
* @param status the status.
* @return this.
*/
public abstract Builder setStatus(Status status);
abstract EndSpanOptions autoBuild(); // not public
/**
* Builds and returns a {@code EndSpanOptions} with the desired settings.
*
* @return a {@code EndSpanOptions} with the desired settings.
* @throws NullPointerException if {@code status} is {@code null}.
*/
public EndSpanOptions build() {
EndSpanOptions endSpanOptions = autoBuild();
checkNotNull(endSpanOptions.getStatus(), "status");
return endSpanOptions;
}
Builder() {}
}
EndSpanOptions() {}
}
| {
"content_hash": "85096d8cf1236b71c9e4e946f8f3b513",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 99,
"avg_line_length": 26.417910447761194,
"alnum_prop": 0.6706214689265537,
"repo_name": "ubschmidt2/instrumentation-java",
"id": "e58a06c3810cb6fec1e87e87e3620d3e21d949d0",
"size": "2356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/src/main/java/io/opencensus/trace/EndSpanOptions.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "797776"
},
{
"name": "Python",
"bytes": "1378"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NOpenCL.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")]
[assembly: AssemblyProduct("NOpenCL.Test")]
[assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("185c251c-65ef-4f51-be16-ec9a941286e5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "d2a6ca72de6b8cc5289c0c8fdb0edd4c",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 84,
"avg_line_length": 37.921052631578945,
"alnum_prop": 0.7467036780013879,
"repo_name": "SunsetQuest/Asm4GCN",
"id": "c1a8adefbb1d1a9f628b7eadc06bd9b5c9d8fda5",
"size": "1617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NOpenCL/NOpenCL.Test/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "13152"
},
{
"name": "C#",
"bytes": "1158538"
}
],
"symlink_target": ""
} |
'use strict';
const assert = require('assert');
const app = require('../../../src/app').services;
describe('storage service', function() {
const storage = {
server: 'test',
used_inodes: 1000,
used_space: 1000,
};
let storageEntity = {};
it('creates new record', () => {
app.service('storage').create(storage).then(
s => {
storageEntity = s;
assert(s._id);
}
);
});
it('finds new record', () => {
app.service('storage').find({server: storage.server}).then(
res => {
assert(res.length > 0);
assert(res[0]._id == storageEntity._id);
}
);
});
it('remove new record', () => {
app.service('storage').remove(storageEntity._id).then(assert);
});
});
| {
"content_hash": "275f4cee08cde2977f1081fb945a82a6",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 70,
"avg_line_length": 23.88888888888889,
"alnum_prop": 0.4697674418604651,
"repo_name": "matas-valuzis/server-monitor",
"id": "fe574e7a045faa22bec6d62271429a9608ec15e1",
"size": "860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/services/storage/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5433"
},
{
"name": "HTML",
"bytes": "1071"
},
{
"name": "JavaScript",
"bytes": "112512"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using Ionic.Zip;
/*
* 制作和解压绿色更新安装包的实用工具程序
* 用法: greenutility -action:xxx -source:xxxxx -target:xxxxx -wait:xxxx -files:xxxx
* 源目录内应该有 *.csproj 文件;打包后形成的 .zip 文件会被放到目标目录内
* action 可用值有 build install
* wait 是一个 .exe 的纯文件名,例如 dp2circulation.exe
* files 要安装的 .zip 文件名。纯文件名,逗号间隔的字符串
* */
namespace GreenUtility
{
class Program
{
static string TempDir = "";
static void Main(string[] args)
{
string strError = "";
int nRet = 0;
// Debug.Assert(false, "");
string strAction = "";
string strSourceDir = "";
string strTargetDir = "";
string strWaitExe = ""; // 要等待这个 .exe 进程退出才能进行安装操作
string strFiles = ""; // 安装那些 .zip 文件。纯文件名列表
foreach(string arg in args)
{
if (arg.StartsWith("-source:") == true)
strSourceDir = arg.Substring("-source:".Length);
if (arg.StartsWith("-target:") == true)
strTargetDir = arg.Substring("-target:".Length);
if (arg.StartsWith("-action:") == true)
strAction = arg.Substring("-action:".Length).ToLower();
if (arg.StartsWith("-wait:") == true)
strWaitExe = arg.Substring("-wait:".Length).ToLower();
if (arg.StartsWith("-files:") == true)
strFiles = arg.Substring("-files:".Length).ToLower();
}
if (string.IsNullOrEmpty(strSourceDir) == true)
{
strError = "缺乏 -source:xxxx 参数";
goto ERROR1;
}
if (string.IsNullOrEmpty(strTargetDir) == true)
{
strError = "缺乏 -target:xxxx 参数";
goto ERROR1;
}
if (string.IsNullOrEmpty(strFiles) == true)
strFiles = "app.zip,data.zip"; // 缺省值
string strTempDir = "c:\\~dp2circulation_temp_file";
CreateDirIfNeed(strTempDir);
TempDir = strTempDir;
if (strAction == "build")
{
string strProjectFileName = GetProjectFileName(strSourceDir);
if (string.IsNullOrEmpty(strProjectFileName) == true)
{
strError = "源目录 '" + strSourceDir + "' 中没有任何 .csproj 文件";
goto ERROR1;
}
nRet = CreateZipFile(strProjectFileName,
strTargetDir,
out strError);
if (nRet == -1)
goto ERROR1;
Console.WriteLine("创建成功");
return;
}
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi);
bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
if (strAction == "install")
{
Console.WriteLine("*** GreenUtility.exe 绿色安装工具 ***");
if (string.IsNullOrEmpty(strWaitExe) == false)
{
Console.WriteLine("等待 " + strWaitExe + " 结束 ...");
bool bRet = WaitProcessEnd(strWaitExe, new TimeSpan(0, 0, 10));
if (bRet == false)
{
if (runAsAdmin == false)
{
//strError = "等待 10 秒后进程 " + strWaitExe + " 依然没有退出。放弃 install";
//goto ERROR1;
// 如果此法失败,则尝试用管理员权限进行安装
if (RestartAsAdministrator() == false)
goto ERROR1;
return;
}
}
}
#if NO
// strTargetDir 一般为 c:\dp2circulation
string strNewDir = strTargetDir + "_new";
string strOldDir = strTargetDir + "_old";
// *** 将 c:\dp2circulation 目录中的全部文件,复制到 c:\dp2circulation_new 中
if (Directory.Exists(strTargetDir) == true)
{
Console.WriteLine("复制 "+strTargetDir+" 到 "+strNewDir+" ...");
// app.zip 和 data.zip 不要复制
// return:
// -1 出错
// >=0 复制的文件总数
nRet = CopyDirectory(strTargetDir,
strNewDir,
null,
out strError);
if (nRet == -1)
goto ERROR1;
}
// *** 将 app.zip 和 data.zip 展开覆盖到 c:\dp2circulation_new 目录
string strZipFileName = Path.Combine(strSourceDir, "app.zip");
Console.WriteLine("展开 " + strZipFileName + " 到 " + strNewDir + " ...");
nRet = ExtractFile(strZipFileName,
strNewDir,
out strError);
if (nRet == -1)
goto ERROR1;
strZipFileName = Path.Combine(strSourceDir, "data.zip");
Console.WriteLine("展开 " + strZipFileName + " 到 " + strNewDir + " ...");
nRet = ExtractFile(strZipFileName,
strNewDir,
out strError);
if (nRet == -1)
goto ERROR1;
// (准备工作) 将以前遗留的 c:\dp2circulation_old 目录删除
DeleteDirectory(strOldDir);
// *** 将 c:\dp2circulation 目录改名为 c:\dp2circulation_old 目录
// 如果改名失败,则终止
try
{
Console.WriteLine("将目录 " + strTargetDir + " 改名为 " + strOldDir + " ...");
Directory.Move(strTargetDir, strOldDir);
}
catch (Exception ex)
{
strError = "将目录 " + strTargetDir + " 改名为 " + strOldDir + " 时出错: " + ex.Message;
goto ERROR1;
}
// *** 将 c:\dp2circulation_new 目录改名为 c:\dp2circulation 目录
// 如果改名失败,需将上一步 Undo,然后终止
try
{
Console.WriteLine("将目录 " + strNewDir + " 改名为 " + strTargetDir + " ...");
Directory.Move(strNewDir, strTargetDir);
}
catch (Exception ex)
{
Directory.Move(strOldDir, strTargetDir);
strError = "将目录 " + strNewDir + " 改名为 " + strTargetDir + " 时出错: " + ex.Message;
goto ERROR1;
}
#endif
if (runAsAdmin == false)
{
// 安装软件。用目录改名法
nRet = Install_1(
strSourceDir,
strTargetDir,
strFiles,
strWaitExe,
out strError);
if (nRet == -1)
{
// 如果此法失败,则尝试用管理员权限进行安装
if (RestartAsAdministrator() == false)
goto ERROR1;
}
}
else
{
// 安装软件。用 MoveFileEx 法
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
nRet = Install_2(
strSourceDir,
strTargetDir,
strFiles,
strWaitExe,
out strError);
if (nRet == -1)
goto ERROR1;
if (nRet == 1)
MessageBox.Show("dp2circulation 安装复制文件已经完成。请重启 Windows,以完成安装");
}
Console.WriteLine("升级安装成功");
return;
}
return;
ERROR1:
Console.WriteLine(strError);
}
static bool RestartAsAdministrator()
{
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi);
bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
if (!runAsAdmin)
{
// It is not possible to launch a ClickOnce app as administrator directly,
// so instead we launch the app as administrator in a new process.
var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);
// The following properties run the new process as administrator
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
string [] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
string[] parameters = new string[args.Length - 1];
Array.Copy(args, 1, parameters, 0, parameters.Length);
processInfo.Arguments = string.Join(" ", parameters);
}
// Start the new process
try
{
Process.Start(processInfo);
}
catch (Exception)
{
MessageBox.Show("GreenUtility 无法运行。\r\n\r\n因为安装复制文件的需要,必须在 Administrator 权限下才能运行");
return false;
}
// Shut down the current process
// Application.Exit();
}
return true;
}
// 将目录路径变为临时形态。例如,将 c:\dp2circulation_old 变为 c:\~dp2circulation_old
static void MakeTempStyle(ref string strPath)
{
strPath = Path.Combine(Path.GetDirectoryName(strPath),
"~" + Path.GetFileName(strPath));
}
// 安装软件。用目录改名法
static int Install_1(
string strSourceDir,
string strTargetDir,
string strFiles,
string strWaitExe,
out string strError)
{
strError = "";
int nRet = 0;
// strTargetDir 一般为 c:\dp2circulation
string strNewDir = strTargetDir + "_new";
string strOldDir = strTargetDir + "_old";
MakeTempStyle(ref strNewDir);
MakeTempStyle(ref strOldDir);
// *** 将 c:\dp2circulation 目录中的全部文件,复制到 c:\dp2circulation_new 中
if (Directory.Exists(strTargetDir) == true)
{
Console.WriteLine("复制 " + strTargetDir + " 到 " + strNewDir + " ...");
// app.zip 和 data.zip 不要复制
// return:
// -1 出错
// >=0 复制的文件总数
nRet = CopyDirectory(strTargetDir,
strNewDir,
null,
out strError);
if (nRet == -1)
goto ERROR1;
}
// *** 将 app.zip 和 data.zip 展开覆盖到 c:\dp2circulation_new 目录
string[] files = strFiles.Split(new char[] { ',' });
foreach (string file in files)
{
string strZipFileName = Path.Combine(strSourceDir, file);
Console.WriteLine("展开 " + strZipFileName + " 到 " + strNewDir + " ...");
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
nRet = ExtractFile(strZipFileName,
strNewDir,
false,
out strError);
if (nRet == -1)
goto ERROR1;
}
#if NO
strZipFileName = Path.Combine(strSourceDir, "data.zip");
Console.WriteLine("展开 " + strZipFileName + " 到 " + strNewDir + " ...");
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
nRet = ExtractFile(strZipFileName,
strNewDir,
false,
out strError);
if (nRet == -1)
goto ERROR1;
#endif
// (准备工作) 将以前遗留的 c:\dp2circulation_old 目录删除
try
{
Directory.Delete(strOldDir, true);
}
catch (DirectoryNotFoundException)
{
// 不存在就算了
}
catch(Exception ex)
{
strError = "删除目录 " + strOldDir + " 时出错: " + ex.Message;
goto ERROR1;
}
// *** 将 c:\dp2circulation 目录改名为 c:\dp2circulation_old 目录
// 如果改名失败,则终止
try
{
Console.WriteLine("将目录 " + strTargetDir + " 改名为 " + strOldDir + " ...");
Directory.Move(strTargetDir, strOldDir);
}
catch (Exception ex)
{
strError = "将目录 " + strTargetDir + " 改名为 " + strOldDir + " 时出错: " + ex.Message;
goto ERROR1;
}
// *** 将 c:\dp2circulation_new 目录改名为 c:\dp2circulation 目录
// 如果改名失败,需将上一步 Undo,然后终止
try
{
Console.WriteLine("将目录 " + strNewDir + " 改名为 " + strTargetDir + " ...");
Directory.Move(strNewDir, strTargetDir);
}
catch (Exception ex)
{
Directory.Move(strOldDir, strTargetDir);
strError = "将目录 " + strNewDir + " 改名为 " + strTargetDir + " 时出错: " + ex.Message;
goto ERROR1;
}
return 0;
ERROR1:
return -1;
}
// 安装软件。用 MoveFileEx 法
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
static int Install_2(
string strSourceDir,
string strTargetDir,
string strFiles,
string strWaitExe,
out string strError)
{
strError = "";
int nRet = 0;
// strTargetDir 一般为 c:\dp2circulation
#if NO
string strNewDir = strTargetDir + "_new";
string strOldDir = strTargetDir + "_old";
// *** 将 c:\dp2circulation 目录中的全部文件,复制到 c:\dp2circulation_new 中
if (Directory.Exists(strTargetDir) == true)
{
Console.WriteLine("复制 " + strTargetDir + " 到 " + strNewDir + " ...");
// app.zip 和 data.zip 不要复制
// return:
// -1 出错
// >=0 复制的文件总数
nRet = CopyDirectory(strTargetDir,
strNewDir,
null,
out strError);
if (nRet == -1)
goto ERROR1;
}
#endif
// *** 将 app.zip 和 data.zip 展开覆盖到 c:\dp2circulation_new 目录
bool bNeedReboot = false;
string[] files = strFiles.Split(new char[] { ',' });
foreach (string file in files)
{
string strZipFileName = Path.Combine(strSourceDir, file);
Console.WriteLine("展开 " + strZipFileName + " 到 " + strTargetDir + " ...");
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
nRet = ExtractFile(strZipFileName,
strTargetDir,
true,
out strError);
if (nRet == -1)
goto ERROR1;
if (nRet == 1)
bNeedReboot = true;
}
#if NO
strZipFileName = Path.Combine(strSourceDir, "data.zip");
Console.WriteLine("展开 " + strZipFileName + " 到 " + strTargetDir + " ...");
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
nRet = ExtractFile(strZipFileName,
strTargetDir,
true,
out strError);
if (nRet == -1)
goto ERROR1;
if (nRet == 1)
bNeedReboot = true;
#endif
if (bNeedReboot)
return 1;
return 0;
ERROR1:
return -1;
}
// return:
// -1 出错
// 0 成功。不需要 reboot
// 1 成功。需要 reboot
static int ExtractFile(string strZipFileName,
string strTargetDir,
bool bAllowDelayOverwrite,
out string strError)
{
strError = "";
bool bNeedReboot = false;
try
{
using (ZipFile zip = ZipFile.Read(strZipFileName))
{
foreach (ZipEntry e in zip)
{
// e.Extract(this.UserDir, ExtractExistingFileAction.OverwriteSilently);
if ((e.Attributes & FileAttributes.Directory) == 0)
{
if (ExtractFile(e, strTargetDir, bAllowDelayOverwrite) == true)
bNeedReboot = true;
}
else
e.Extract(strTargetDir, ExtractExistingFileAction.OverwriteSilently);
}
}
}
catch (Exception ex)
{
strError = ex.Message;
return -1;
}
if (bNeedReboot == true)
return 1;
return 0;
}
// parameters:
// bAllowDelayOverwrite 是否允许延迟到 reboot 后的覆盖
// return:
// false 正常结束
// true 发生了 MoveFileEx,需要 reboot 才会发生作用
static bool ExtractFile(ZipEntry e,
string strTargetDir,
bool bAllowDelayOverwrite)
{
string strTempDir = TempDir;
string strTempPath = Path.Combine(strTempDir, Path.GetFileName(e.FileName));
string strTargetPath = Path.Combine(strTargetDir, e.FileName);
using (FileStream stream = new FileStream(strTempPath, FileMode.Create))
{
e.Extract(stream);
}
int nErrorCount = 0;
for (; ; )
{
try
{
// 确保目标目录已经创建
CreateDirIfNeed(Path.GetDirectoryName(strTargetPath));
File.Copy(strTempPath, strTargetPath, true);
File.SetLastWriteTime(strTargetPath, e.LastModified);
Console.WriteLine("展开文件 " + strTargetPath);
}
catch (Exception ex)
{
if (nErrorCount > 10 || bAllowDelayOverwrite)
{
if (bAllowDelayOverwrite == false)
throw new Exception("复制文件 " + strTempPath + " 到 " + strTargetPath + " 的过程中出现错误: " + ex.Message);
else
{
string strLastFileName = Path.Combine(strTempDir, Guid.NewGuid().ToString());
File.Move(strTempPath, strLastFileName);
strTempPath = "";
if (MoveFileEx(strLastFileName, strTargetPath, MoveFileFlags.DelayUntilReboot | MoveFileFlags.ReplaceExisting) == false)
throw new Exception("MoveFileEx() '"+strLastFileName+"' '"+strTargetPath+"' 失败");
File.SetLastWriteTime(strLastFileName, e.LastModified);
Console.WriteLine("延迟展开文件 " + strTargetPath);
return true;
}
}
nErrorCount++;
Thread.Sleep(1000);
continue;
}
break;
}
if (string.IsNullOrEmpty(strTempPath) == false)
File.Delete(strTempPath);
return false;
}
#region MoveFileEx
[Flags]
internal enum MoveFileFlags
{
None = 0,
ReplaceExisting = 1,
CopyAllowed = 2,
DelayUntilReboot = 4,
WriteThrough = 8,
CreateHardlink = 16,
FailIfNotTrackable = 32,
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool MoveFileEx(
string lpExistingFileName,
string lpNewFileName,
MoveFileFlags dwFlags);
#endregion
// 在指定目录中找到第一个 *.csproj 文件名
static string GetProjectFileName(string strSourceDir)
{
DirectoryInfo di = new DirectoryInfo(strSourceDir);
FileInfo [] fis = di.GetFiles("*.csproj");
foreach(FileInfo fi in fis)
{
return fi.FullName;
}
return null;
}
static int CreateZipFile(string strProjectFileName,
string strTargetDir,
out string strError)
{
strError = "";
XmlDocument dom = new XmlDocument();
try
{
dom.Load(strProjectFileName);
}
catch (Exception ex)
{
strError = "装载文件 '" + strProjectFileName + "' 到 XmlDocument 时出错: " + ex.Message;
return -1;
}
string strSourceDir = Path.GetDirectoryName(strProjectFileName);
List<string> filenames = new List<string>();
#if NO
/*
<PublishFile Include="acceptorigin.css">
<Visible>False</Visible>
<Group>
</Group>
<TargetPath>
</TargetPath>
<PublishState>DataFile</PublishState>
<IncludeHash>True</IncludeHash>
<FileType>File</FileType>
</PublishFile>
* */
XmlNodeList publishs = dom.DocumentElement.SelectNodes("//PublishFile");
foreach (XmlElement publishFile in publishs)
{
XmlElement publishState = publishFile.SelectSingleNode("PublishState") as XmlElement;
if (publishState == null)
continue;
string strPublishState = publishState.InnerText.Trim();
if (strPublishState == "Exclude")
continue;
string strInclude = publishFile.GetAttribute("Include");
if (string.IsNullOrEmpty(strInclude) == true)
continue;
string strSourceFileName = Path.Combine(strSourceDir, strInclude);
if (File.Exists(strSourceFileName) == false)
{
strError = "拟复制的文件 '" + strSourceFileName + "' 不存在";
return -1;
}
filenames.Add(strSourceFileName);
}
#endif
/*
<Content Include="exchangeratetable.css" />
<Content Include="getsummary.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="history.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="isbn.xml" />
<Content Include="itemhandover.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
* */
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");
_referenceTable.Clear();
BuildReferenceTable(dom, nsmgr, ref _referenceTable);
XmlNodeList contents = dom.DocumentElement.SelectNodes("//ns:Content", nsmgr);
foreach (XmlElement content in contents)
{
XmlElement copyto = content.SelectSingleNode("ns:CopyToOutputDirectory", nsmgr) as XmlElement;
if (copyto == null)
continue;
string strCopyTo = copyto.InnerText.Trim();
if (string.IsNullOrEmpty(strCopyTo) == true)
continue;
string strInclude = content.GetAttribute("Include");
if (string.IsNullOrEmpty(strInclude) == true)
continue;
string strSourceFileName = Path.Combine(strSourceDir, strInclude);
if (File.Exists(strSourceFileName) == false)
{
strError = "拟复制的文件 '" + strSourceFileName + "' 不存在";
return -1;
}
filenames.Add(strSourceFileName);
}
string strZipFileName = Path.Combine(strTargetDir, "data.zip");
int nRet = Compress(
strSourceDir,
filenames,
Encoding.UTF8,
strZipFileName,
out strError);
if (nRet == -1)
return -1;
// .exe .exe.config .exe.manifest
string strBinSourceDir = Path.Combine(strSourceDir, "bin\\debug");
strZipFileName = Path.Combine(strTargetDir, "app.zip");
filenames = GetExeFileNames(strBinSourceDir);
// Debug.Assert(false, "");
// 添加一些可能遗漏的文件 2016/3/29
/*
<PublishFile Include="DocumentFormat.OpenXml">
<Visible>False</Visible>
<Group>
</Group>
<TargetPath>
</TargetPath>
<PublishState>Include</PublishState>
<IncludeHash>True</IncludeHash>
<FileType>Assembly</FileType>
</PublishFile>
* */
XmlNodeList publishFiles = dom.DocumentElement.SelectNodes("//ns:PublishFile", nsmgr);
foreach(XmlElement publishFile in publishFiles)
{
string strFileType = GetNodeInnerText(publishFile.SelectSingleNode("ns:FileType", nsmgr));
string strPublishState = GetNodeInnerText(publishFile.SelectSingleNode("ns:PublishState", nsmgr));
if (strFileType != "Assembly" || strPublishState != "Include")
continue;
string strFileName = publishFile.GetAttribute("Include") + ".dll";
string strHintPath = (string)_referenceTable[strFileName];
if (string.IsNullOrEmpty(strHintPath))
continue;
string strFilePath = Path.Combine(strSourceDir, strHintPath);
// 复制文件到 bin 目录
string strTargetPath = Path.Combine(strBinSourceDir, strFileName);
File.Copy(strFilePath, strTargetPath, true);
Console.WriteLine("追加文件: " + strTargetPath);
strFilePath = new FileInfo(strTargetPath).FullName;
if (filenames.IndexOf(strTargetPath) == -1)
filenames.Add(strTargetPath);
}
nRet = Compress(
strBinSourceDir,
filenames,
Encoding.UTF8,
strZipFileName,
out strError);
if (nRet == -1)
return -1;
return 0;
}
static Hashtable _referenceTable = new Hashtable(); // Reference 对照表。纯文件名 --> 相对路径
static void BuildReferenceTable(XmlDocument dom,
XmlNamespaceManager nsmgr,
ref Hashtable referenceTable)
{
/*
<Reference Include="DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>packages\DocumentFormat.OpenXml.2.5\lib\DocumentFormat.OpenXml.dll</HintPath>
</Reference>
* */
XmlNodeList references = dom.DocumentElement.SelectNodes("//ns:Reference", nsmgr);
foreach (XmlElement reference in references)
{
string strHintPath = GetNodeInnerText(reference.SelectSingleNode("ns:HintPath", nsmgr));
if (string.IsNullOrEmpty(strHintPath))
continue;
string strFileName = GetLeft(reference.GetAttribute("Include")) + ".dll";
referenceTable[strFileName] = strHintPath;
}
}
// 获得逗号左边的字符串
static string GetLeft(string strText)
{
if (string.IsNullOrEmpty(strText) == true)
return "";
int nRet = strText.IndexOf(",");
if (nRet == -1)
return strText;
return strText.Substring(0, nRet).Trim();
}
static string GetNodeInnerText(XmlNode node)
{
if (node == null)
return "";
return node.InnerText.Trim();
}
static int Compress(
string strBaseDir,
List<string> filenames,
Encoding encoding,
string strZipFileName,
out string strError)
{
strError = "";
if (filenames.Count == 0)
return 0;
using (ZipFile zip = new ZipFile(encoding))
{
// http://stackoverflow.com/questions/15337186/dotnetzip-badreadexception-on-extract
// https://dotnetzip.codeplex.com/workitem/14087
// uncommenting the following line can be used as a work-around
zip.ParallelDeflateThreshold = -1;
foreach (string filename in filenames)
{
string strShortFileName = filename.Substring(strBaseDir.Length + 1);
string directoryPathInArchive = Path.GetDirectoryName(strShortFileName);
zip.AddFile(filename, directoryPathInArchive);
}
zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
zip.Save(strZipFileName);
}
return 1;
}
// 获得一个目录下的全部文件名。包括子目录中的
static List<string> GetExeFileNames(string strDataDir)
{
// Application.DoEvents();
DirectoryInfo di = new DirectoryInfo(strDataDir);
List<string> result = new List<string>();
FileInfo[] fis = di.GetFiles();
foreach (FileInfo fi in fis)
{
string strFileName = fi.Name.ToLower();
string strExtention = Path.GetExtension(strFileName);
if (strExtention == ".exe"
|| strExtention == ".dll"
|| strFileName.EndsWith(".exe.config") == true
|| strFileName.EndsWith(".exe.manifest") == true)
result.Add(fi.FullName);
}
#if NO
// 处理下级目录,递归
DirectoryInfo[] dis = di.GetDirectories();
foreach (DirectoryInfo subdir in dis)
{
result.AddRange(GetExeFileNames(subdir.FullName));
}
#endif
return result;
}
#region CopyDirectory()
public delegate bool FileNameFilterProc(FileSystemInfo fi);
// 拷贝目录
// return:
// -1 出错
// >=0 复制的文件总数
public static int CopyDirectory(string strSourceDir,
string strTargetDir,
FileNameFilterProc filter_proc,
out string strError)
{
strError = "";
int nCount = 0;
try
{
DirectoryInfo di = new DirectoryInfo(strSourceDir);
if (di.Exists == false)
{
strError = "源目录 '" + strSourceDir + "' 不存在...";
return -1;
}
#if NO
if (bDeleteTargetBeforeCopy == true)
{
if (Directory.Exists(strTargetDir) == true)
Directory.Delete(strTargetDir, true);
}
#endif
CreateDirIfNeed(strTargetDir);
FileSystemInfo[] subs = di.GetFileSystemInfos();
foreach (FileSystemInfo sub in subs)
{
if (filter_proc != null && filter_proc(sub) == false)
continue;
// 复制目录
if ((sub.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
int nRet = CopyDirectory(sub.FullName,
Path.Combine(strTargetDir, sub.Name),
filter_proc,
out strError);
if (nRet == -1)
return -1;
nCount += nRet;
continue;
}
// 复制文件
string source = sub.FullName;
string target = Path.Combine(strTargetDir, sub.Name);
// 如果目标文件已经存在,并且修后修改时间相同,则不复制了
if (File.Exists(target) == true && File.GetLastWriteTimeUtc(source) == File.GetLastWriteTimeUtc(target))
continue;
File.Copy(source, target, true);
// 把最后修改时间设置为和 source 一样
File.SetLastWriteTimeUtc(target, File.GetLastWriteTimeUtc(source));
nCount++;
}
}
catch (Exception ex)
{
strError = ex.Message;
return -1;
}
return nCount;
}
// 如果目录不存在则创建之
// return:
// false 已经存在
// true 刚刚新创建
public static bool CreateDirIfNeed(string strDir)
{
DirectoryInfo di = new DirectoryInfo(strDir);
if (di.Exists == false)
{
di.Create();
return true;
}
return false;
}
#endregion
public static void DeleteDirectory(string strDirPath)
{
try
{
Directory.Delete(strDirPath, true);
}
catch (DirectoryNotFoundException)
{
// 不存在就算了
}
}
// return:
// true 成功等到进程结束了
// false 到超时也没有等到进程结束
static bool WaitProcessEnd(string strName, TimeSpan timeout)
{
DateTime start = DateTime.Now;
while (true)
{
if (DateTime.Now - start > timeout)
return false;
System.Diagnostics.Process[] process_list = System.Diagnostics.Process.GetProcesses();
bool bFound = false;
foreach (Process process in process_list)
{
string ModuleName = "";
try
{
ModuleName = process.MainModule.ModuleName;
}
catch (Exception ex)
{
continue;
}
if (ModuleName.StartsWith(strName,
StringComparison.OrdinalIgnoreCase))
{
bFound = true;
break;
}
}
if (bFound == false)
return true;
Thread.Sleep(2000);
}
}
}
}
| {
"content_hash": "172986905db7b01296e0d9626d77a0ac",
"timestamp": "",
"source": "github",
"line_count": 1050,
"max_line_length": 148,
"avg_line_length": 34.007619047619045,
"alnum_prop": 0.4679623613756021,
"repo_name": "renyh1013/dp2",
"id": "ec617526bfc03ebb7e98fce3779cb52a9800c676",
"size": "37764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GreenUtility/Program.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "219049"
},
{
"name": "Batchfile",
"bytes": "4200"
},
{
"name": "C#",
"bytes": "44914579"
},
{
"name": "CSS",
"bytes": "806240"
},
{
"name": "HTML",
"bytes": "1339609"
},
{
"name": "JavaScript",
"bytes": "379570"
},
{
"name": "PHP",
"bytes": "36009"
},
{
"name": "PowerShell",
"bytes": "87046"
},
{
"name": "Roff",
"bytes": "3758"
},
{
"name": "Smalltalk",
"bytes": "39606"
},
{
"name": "XSLT",
"bytes": "64230"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
<info organisation="asm"
module="asm"
revision="3.3"
status="release"
publication="20101007000318"
>
<description homepage="" />
<m:dependency.management__asm__asm-analysis__version>3.3</m:dependency.management__asm__asm-analysis__version>
<m:dependency.management__asm__asm-xml__version>3.3</m:dependency.management__asm__asm-xml__version>
<m:dependency.management__asm__asm-tree__version>3.3</m:dependency.management__asm__asm-tree__version>
<m:dependency.management__asm__asm__version>3.3</m:dependency.management__asm__asm__version>
<m:dependency.management__asm__asm-commons__version>3.3</m:dependency.management__asm__asm-commons__version>
<m:dependency.management__asm__asm-util__version>3.3</m:dependency.management__asm__asm-util__version>
</info>
<configurations>
<conf name="default" visibility="public" description="runtime dependencies and master artifact can be used with this conf" extends="runtime,master"/>
<conf name="master" visibility="public" description="contains only the artifact published by this module itself, with no transitive dependencies"/>
<conf name="compile" visibility="public" description="this is the default scope, used if none is specified. Compile dependencies are available in all classpaths."/>
<conf name="provided" visibility="public" description="this is much like compile, but indicates you expect the JDK or a container to provide it. It is only available on the compilation classpath, and is not transitive."/>
<conf name="runtime" visibility="public" description="this scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath." extends="compile"/>
<conf name="test" visibility="private" description="this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases." extends="runtime"/>
<conf name="system" visibility="public" description="this scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository."/>
<conf name="sources" visibility="public" description="this configuration contains the source artifact of this module, if any."/>
<conf name="javadoc" visibility="public" description="this configuration contains the javadoc artifact of this module, if any."/>
<conf name="optional" visibility="public" description="contains all optional dependencies"/>
</configurations>
<publications>
<artifact name="asm" type="jar" ext="jar" conf="master"/>
</publications>
</ivy-module>
| {
"content_hash": "6ee7d352782a455b1bfa37bb348aaa0b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 245,
"avg_line_length": 87.5,
"alnum_prop": 0.7585714285714286,
"repo_name": "noel-yap/setter-for-catan",
"id": "2e9141d4bc7e28345825422dd9c98473d4c1f029",
"size": "2800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play-2.1.1/repository/local/asm/asm/3.3/ivys/ivy.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "6386"
},
{
"name": "Java",
"bytes": "463689"
},
{
"name": "JavaScript",
"bytes": "841409"
},
{
"name": "Scala",
"bytes": "1510018"
},
{
"name": "Shell",
"bytes": "7220"
}
],
"symlink_target": ""
} |
#include <sbml/common/common.h>
#include <sbml/common/extern.h>
#include <sbml/xml/XMLNode.h>
#include <sbml/xml/XMLInputStream.h>
#include <sbml/packages/layout/sbml/test/utility.h>
#include <sbml/packages/render/extension/RenderExtension.h>
#include <RenderInformationBase.h>
#include <GlobalRenderInformation.h>
#include <check.h>
#include <limits>
#include <string>
LIBSBML_CPP_NAMESPACE_USE
BEGIN_C_DECLS
static RenderInformationBase *R;
static RenderPkgNamespaces *renderns;
void
RenderInformationBaseTest_setup (void)
{
renderns = new (std::nothrow) RenderPkgNamespaces();
R = new (std::nothrow) GlobalRenderInformation(renderns);
if (R == NULL)
{
fail("new(std::nothrow)GlobalRenderInformation(renderns) returned a NULL pointer.");
}
}
void
RenderInformationBaseTest_teardown (void)
{
delete R;
delete renderns;
}
START_TEST (test_RenderInformationBase_programname )
{
fail_unless(R->getProgramName() == "");
R->setProgramName("SomeProgram");
fail_unless(R->getProgramName() == "SomeProgram");
R->setProgramName("");
fail_unless(R->getProgramName() == "");
}
END_TEST
START_TEST (test_RenderInformationBase_programversion )
{
fail_unless(R->getProgramVersion() == "");
R->setProgramVersion("1.0.0");
fail_unless(R->getProgramVersion() == "1.0.0");
R->setProgramVersion("");
fail_unless(R->getProgramVersion() == "");
}
END_TEST
START_TEST (test_RenderInformationBase_referencerenderinformation )
{
fail_unless(R->getReferenceRenderInformationId() == "");
R->setReferenceRenderInformationId("Other_Render_Information");
fail_unless(R->getReferenceRenderInformationId() == "Other_Render_Information");
R->setReferenceRenderInformationId("");
fail_unless(R->getReferenceRenderInformationId() == "");
}
END_TEST
START_TEST (test_RenderInformationBase_backgroundcolor )
{
R->setBackgroundColor("");
fail_unless(R->getBackgroundColor() == "");
R->setBackgroundColor("#FF3478");
fail_unless(R->getBackgroundColor() == "#FF3478");
R->setBackgroundColor("");
fail_unless(R->getBackgroundColor() == "");
}
END_TEST
START_TEST (test_RenderInformationBase_id )
{
fail_unless( !R->isSetId() );
fail_unless( R->getId() == "");
R->setId("render_info");
fail_unless( R->isSetId() );
fail_unless( R->getId() == "render_info");
R->unsetId();
fail_unless( !R->isSetId() );
fail_unless( R->getId() == "");
}
END_TEST
START_TEST (test_RenderInformationBase_name )
{
fail_unless( !R->isSetName() );
fail_unless( R->getName() == "");
R->setName("render_info");
fail_unless( R->isSetName() );
fail_unless( R->getName() == "render_info");
R->unsetName();
fail_unless( !R->isSetName() );
fail_unless( R->getName() == "");
}
END_TEST
START_TEST ( test_RenderInformationBase_createMethods )
{
// create color definition
ColorDefinition* pCD=R->createColorDefinition();
fail_unless ( pCD != NULL );
fail_unless ( R->getNumColorDefinitions() == 1 );
ColorDefinition* pCD2 = R->removeColorDefinition(0);
fail_unless( pCD2 != NULL );
fail_unless( pCD == pCD2 );
fail_unless ( R->getNumColorDefinitions() == 0 );
delete pCD2;
// create linear gradient definition
LinearGradient* pLG=R->createLinearGradientDefinition();
fail_unless ( pLG != NULL );
fail_unless ( R->getNumGradientDefinitions() == 1 );
GradientBase* pG2 = R->removeGradientDefinition(0);
fail_unless( pG2 != NULL );
fail_unless( pLG == pG2 );
fail_unless ( R->getNumGradientDefinitions() == 0 );
delete pG2;
// create radial gradient definition
RadialGradient* pRG=R->createRadialGradientDefinition();
fail_unless ( pRG != NULL );
fail_unless ( R->getNumGradientDefinitions() == 1 );
pG2 = R->removeGradientDefinition(0);
fail_unless( pG2 != NULL );
fail_unless( pRG == pG2 );
fail_unless ( R->getNumGradientDefinitions() == 0 );
delete pG2;
// create line ending
LineEnding* pLE=R->createLineEnding();
fail_unless ( pLE != NULL );
fail_unless ( R->getNumLineEndings() == 1 );
LineEnding* pLE2 = R->removeLineEnding(0);
fail_unless( pLE2 != NULL );
fail_unless( pLE == pLE2 );
fail_unless ( R->getNumLineEndings() == 0 );
delete pLE2;
}
END_TEST
START_TEST ( test_RenderInformationBase_addMethods )
{
fail_unless( R->getNumColorDefinitions() == 0 );
fail_unless( R->getNumGradientDefinitions() == 0 );
fail_unless( R->getNumLineEndings() == 0 );
// add color definition
ColorDefinition* pCD=new ColorDefinition(renderns);
fail_unless ( pCD != NULL );
pCD->setId("ColorDefinition_1");
fail_unless ( R->addColorDefinition( pCD ) == LIBSBML_OPERATION_SUCCESS );
fail_unless( R->getNumColorDefinitions() == 1 );
fail_unless( pCD != R->getColorDefinition(0));
delete pCD;
pCD = new ColorDefinition(renderns);
fail_unless ( R->addColorDefinition( pCD ) == LIBSBML_INVALID_OBJECT );
fail_unless( R->getNumColorDefinitions() == 1 );
delete pCD;
pCD = new ColorDefinition(2,1);
fail_unless ( pCD != NULL );
pCD->setId("ColorDefinition_2");
fail_unless( R->addColorDefinition( pCD ) == LIBSBML_LEVEL_MISMATCH );
fail_unless( R->getNumColorDefinitions() == 1 );
delete pCD;
// add gradient definition
LinearGradient* pLG=new LinearGradient(renderns);
fail_unless ( pLG != NULL );
fail_unless ( R->addGradientDefinition( pLG ) == LIBSBML_INVALID_OBJECT );
fail_unless( R->getNumGradientDefinitions() == 0 );
pLG->setId("lineargradient_1");
fail_unless ( R->addGradientDefinition( pLG ) == LIBSBML_OPERATION_SUCCESS );
fail_unless( R->getNumGradientDefinitions() == 1 );
fail_unless( pLG != R->getGradientDefinition(0));
delete pLG;
pLG = new LinearGradient(renderns);
fail_unless ( R->addGradientDefinition( pLG ) == LIBSBML_INVALID_OBJECT );
fail_unless( R->getNumGradientDefinitions() == 1 );
delete pLG;
pLG = new LinearGradient(2,1);
pLG->setId("lineargradient_5");
fail_unless ( pLG != NULL );
fail_unless( R->addGradientDefinition( pLG ) == LIBSBML_LEVEL_MISMATCH );
fail_unless( R->getNumGradientDefinitions() == 1 );
delete pLG;
RadialGradient* pRG=new RadialGradient(renderns);
fail_unless ( pRG != NULL );
pRG->setId("radial_gradient_2");
fail_unless ( R->addGradientDefinition( pRG ) == LIBSBML_OPERATION_SUCCESS );
fail_unless( R->getNumGradientDefinitions() == 2 );
delete pRG;
pRG=new RadialGradient(renderns);
fail_unless ( pRG != NULL );
fail_unless ( R->addGradientDefinition( pRG ) == LIBSBML_INVALID_OBJECT );
fail_unless( R->getNumGradientDefinitions() == 2 );
fail_unless( pRG != R->getGradientDefinition(1));
delete pRG;
pRG = new RadialGradient(2,1);
fail_unless ( pRG != NULL );
pRG->setId("radial_gradient_5");
fail_unless( R->addGradientDefinition( pRG ) == LIBSBML_LEVEL_MISMATCH );
fail_unless( R->getNumGradientDefinitions() == 2 );
delete pRG;
// add line ending
LineEnding* pLE=new LineEnding(renderns);
fail_unless ( pLE != NULL );
pLE->setId("lineending_1");
fail_unless ( R->addLineEnding( pLE ) == LIBSBML_OPERATION_SUCCESS );
fail_unless( R->getNumLineEndings() == 1 );
fail_unless( pLE != R->getLineEnding(0));
delete pLE;
pLE=new LineEnding(renderns);
fail_unless ( pLE != NULL );
fail_unless ( R->addLineEnding( pLE ) == LIBSBML_INVALID_OBJECT );
fail_unless( R->getNumLineEndings() == 1 );
delete pLE;
pLE = new LineEnding(2,1);
fail_unless ( pLE != NULL );
pLE->setId("lineending_5");
fail_unless( R->addLineEnding( pLE ) == LIBSBML_LEVEL_MISMATCH );
fail_unless( R->getNumLineEndings() == 1 );
delete pLE;
}
END_TEST
Suite *
create_suite_RenderInformationBase (void)
{
Suite *suite = suite_create("RenderInformationBase");
TCase *tcase = tcase_create("RenderInformationBase");
tcase_add_checked_fixture( tcase,
RenderInformationBaseTest_setup,
RenderInformationBaseTest_teardown );
tcase_add_test( tcase, test_RenderInformationBase_id );
tcase_add_test( tcase, test_RenderInformationBase_name );
tcase_add_test( tcase, test_RenderInformationBase_programname );
tcase_add_test( tcase, test_RenderInformationBase_programversion );
tcase_add_test( tcase, test_RenderInformationBase_referencerenderinformation );
tcase_add_test( tcase, test_RenderInformationBase_backgroundcolor );
tcase_add_test( tcase, test_RenderInformationBase_createMethods );
tcase_add_test( tcase, test_RenderInformationBase_addMethods );
suite_add_tcase(suite, tcase);
return suite;
}
END_C_DECLS
| {
"content_hash": "19f62a4d499b371fcd20212d9cbd2893",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 92,
"avg_line_length": 34.87832699619772,
"alnum_prop": 0.6375231658127112,
"repo_name": "TheCoSMoCompany/biopredyn",
"id": "dd0a40038472e06ffff40e444b777537f3664cba",
"size": "10963",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Prototype/src/libsbml-5.10.0/src/sbml/packages/render/sbml/test/TestRenderInformationBase.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3535918"
},
{
"name": "C++",
"bytes": "26120778"
},
{
"name": "CMake",
"bytes": "455400"
},
{
"name": "CSS",
"bytes": "49020"
},
{
"name": "Gnuplot",
"bytes": "206"
},
{
"name": "HTML",
"bytes": "193068"
},
{
"name": "Java",
"bytes": "66517"
},
{
"name": "JavaScript",
"bytes": "3847"
},
{
"name": "Makefile",
"bytes": "30905"
},
{
"name": "Perl",
"bytes": "3018"
},
{
"name": "Python",
"bytes": "7891301"
},
{
"name": "Shell",
"bytes": "247654"
},
{
"name": "TeX",
"bytes": "22566"
},
{
"name": "XSLT",
"bytes": "55564"
}
],
"symlink_target": ""
} |
package pkg
// SyncDef stores synchronisation definition
type SyncDef struct {
TargetRepoPrefix string `yaml:"targetRepoPrefix"`
Sign bool `yaml:"sign"`
Images []Image
}
// Image stores image location
type Image struct {
Source string
Tag string `yaml:"tag,omitempty"`
Sign *bool `yaml:"sign,omitempty"`
}
| {
"content_hash": "82322b1a8d3a6bac74e06ee1ce395ff8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 50,
"avg_line_length": 22.933333333333334,
"alnum_prop": 0.6831395348837209,
"repo_name": "kyma-project/test-infra",
"id": "501e974d37b628343791b0107381a808677f1c60",
"size": "344",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "development/image-syncer/pkg/common.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "29768"
},
{
"name": "Go",
"bytes": "1320295"
},
{
"name": "Jsonnet",
"bytes": "86522"
},
{
"name": "Makefile",
"bytes": "21421"
},
{
"name": "Mustache",
"bytes": "1403"
},
{
"name": "Python",
"bytes": "19305"
},
{
"name": "Shell",
"bytes": "592845"
}
],
"symlink_target": ""
} |
package api
import (
"fmt"
"net/http"
"testing"
"github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/dao/project"
"github.com/goharbor/harbor/src/common/models"
)
func TestProjectMemberAPI_Get(t *testing.T) {
cases := []*codeCheckingCase{
// 401
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/1/members",
},
code: http.StatusUnauthorized,
},
// 200
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/1/members",
credential: admin,
},
code: http.StatusOK,
},
// 400
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/0/members",
credential: admin,
},
code: http.StatusBadRequest,
},
// 404
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/1/members/121",
credential: admin,
},
code: http.StatusNotFound,
},
// 404
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/99999/members/121",
credential: admin,
},
code: http.StatusNotFound,
},
}
runCodeCheckingCases(t, cases...)
}
func TestProjectMemberAPI_Post(t *testing.T) {
userID, err := dao.Register(models.User{
Username: "restuser",
Password: "Harbor12345",
Email: "restuser@example.com",
})
defer dao.DeleteUser(int(userID))
if err != nil {
t.Errorf("Error occurred when create user: %v", err)
}
cases := []*codeCheckingCase{
// 401
{
request: &testingRequest{
method: http.MethodPost,
url: "/api/projects/1/members",
bodyJSON: &models.MemberReq{
Role: 1,
MemberUser: models.User{
UserID: int(userID),
},
},
},
code: http.StatusUnauthorized,
},
{
request: &testingRequest{
method: http.MethodPost,
url: "/api/projects/1/members",
bodyJSON: &models.MemberReq{
Role: 1,
MemberUser: models.User{
UserID: int(userID),
},
},
credential: admin,
},
code: http.StatusCreated,
},
{
request: &testingRequest{
method: http.MethodPost,
url: "/api/projects/1/members",
bodyJSON: &models.MemberReq{
Role: 1,
MemberUser: models.User{
Username: "notexistuser",
},
},
credential: admin,
},
code: http.StatusNotFound,
},
{
request: &testingRequest{
method: http.MethodPost,
url: "/api/projects/1/members",
bodyJSON: &models.MemberReq{
Role: 1,
MemberUser: models.User{
UserID: 0,
},
},
credential: admin,
},
code: http.StatusInternalServerError,
},
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/1/members?entityname=restuser",
credential: admin,
},
code: http.StatusOK,
},
{
request: &testingRequest{
method: http.MethodGet,
url: "/api/projects/1/members",
credential: admin,
},
code: http.StatusOK,
},
}
runCodeCheckingCases(t, cases...)
}
func TestProjectMemberAPI_PutAndDelete(t *testing.T) {
userID, err := dao.Register(models.User{
Username: "restuser",
Password: "Harbor12345",
Email: "restuser@example.com",
})
defer dao.DeleteUser(int(userID))
if err != nil {
t.Errorf("Error occurred when create user: %v", err)
}
ID, err := project.AddProjectMember(models.Member{
ProjectID: 1,
Role: 1,
EntityID: int(userID),
EntityType: "u",
})
if err != nil {
t.Errorf("Error occurred when add project member: %v", err)
}
URL := fmt.Sprintf("/api/projects/1/members/%v", ID)
badURL := fmt.Sprintf("/api/projects/1/members/%v", 0)
cases := []*codeCheckingCase{
// 401
{
request: &testingRequest{
method: http.MethodPut,
url: URL,
bodyJSON: &models.Member{
Role: 2,
},
},
code: http.StatusUnauthorized,
},
// 200
{
request: &testingRequest{
method: http.MethodPut,
url: URL,
bodyJSON: &models.Member{
Role: 2,
},
credential: admin,
},
code: http.StatusOK,
},
// 200
{
request: &testingRequest{
method: http.MethodPut,
url: URL,
bodyJSON: &models.Member{
Role: 4,
},
credential: admin,
},
code: http.StatusOK,
},
// 400
{
request: &testingRequest{
method: http.MethodPut,
url: badURL,
bodyJSON: &models.Member{
Role: 2,
},
credential: admin,
},
code: http.StatusBadRequest,
},
// 400
{
request: &testingRequest{
method: http.MethodPut,
url: URL,
bodyJSON: &models.Member{
Role: -2,
},
credential: admin,
},
code: http.StatusBadRequest,
},
// 200
{
request: &testingRequest{
method: http.MethodDelete,
url: URL,
credential: admin,
},
code: http.StatusOK,
},
}
runCodeCheckingCases(t, cases...)
}
| {
"content_hash": "99bbde8826da1f64c9e805d447a24c3d",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 62,
"avg_line_length": 19.821862348178136,
"alnum_prop": 0.5959967320261438,
"repo_name": "steven-zou/harbor",
"id": "e440ce0e926b12c4a4d5050292be33bed6439205",
"size": "5495",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/core/api/projectmember_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "65898"
},
{
"name": "Dockerfile",
"bytes": "15610"
},
{
"name": "Go",
"bytes": "2394949"
},
{
"name": "HTML",
"bytes": "323559"
},
{
"name": "JavaScript",
"bytes": "2238"
},
{
"name": "Makefile",
"bytes": "26935"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "PLSQL",
"bytes": "148"
},
{
"name": "PLpgSQL",
"bytes": "11853"
},
{
"name": "Python",
"bytes": "238276"
},
{
"name": "RobotFramework",
"bytes": "281940"
},
{
"name": "Shell",
"bytes": "68780"
},
{
"name": "Smarty",
"bytes": "26225"
},
{
"name": "TypeScript",
"bytes": "961483"
}
],
"symlink_target": ""
} |
<?php
/**
* Zend_Service_Amazon_Exception
*/
//require_once 'Zend/Service/Amazon/Exception.php';
/**
* @category Zend
* @package Zend_Service
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Amazon_S3_Exception extends Zend_Service_Amazon_Exception
{}
| {
"content_hash": "e3f95f1b67602e4df5ea2ced7e6da5eb",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 87,
"avg_line_length": 22.5,
"alnum_prop": 0.6938271604938272,
"repo_name": "illibejiep/YiiBoilerplate",
"id": "e88a084499436461643fcf55748f9bb9b89749ea",
"size": "1174",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "common/lib/Zend/Service/Amazon/S3/Exception.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "49212"
},
{
"name": "Batchfile",
"bytes": "1263"
},
{
"name": "CSS",
"bytes": "111863"
},
{
"name": "Gherkin",
"bytes": "514"
},
{
"name": "HTML",
"bytes": "4160678"
},
{
"name": "JavaScript",
"bytes": "1744248"
},
{
"name": "PHP",
"bytes": "33269841"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
import Control.Monad
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Char
pangram line = if Set.size s == 26 then "pangram" else "not pangram"
where
s = Set.fromList (concatMap id (words lowLine))
lowLine = map toLower line
main :: IO ()
main = do
line <- getLine
let ans = pangram line
putStr ans
| {
"content_hash": "c3f67585832d8a89f2be29f8c84ca12e",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 68,
"avg_line_length": 23.4,
"alnum_prop": 0.6638176638176638,
"repo_name": "mgrebenets/hackerrank",
"id": "fe9eefb0061145520a0aef508a738e648b28b0d9",
"size": "351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "alg/strings/pangrams.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "564"
},
{
"name": "C++",
"bytes": "24188"
},
{
"name": "Haskell",
"bytes": "56606"
},
{
"name": "Makefile",
"bytes": "3915"
},
{
"name": "Objective-C",
"bytes": "126"
},
{
"name": "Ruby",
"bytes": "1577"
},
{
"name": "Shell",
"bytes": "2030"
},
{
"name": "Swift",
"bytes": "7998"
}
],
"symlink_target": ""
} |
package cc.factorie.app.nlp.load
import java.io.File
import cc.factorie.app.nlp.{Document, Sentence, Token, UnknownDocumentAnnotator, _}
import cc.factorie.app.nlp.coref.Mention
import cc.factorie.app.nlp.ner.ConllNerSpan
import cc.factorie.app.nlp.phrase.Phrase
import cc.factorie.app.nlp.pos.PennPosTag
import cc.factorie.variable.SetVariable
import scala.Array.fallbackCanBuildFrom
import scala.xml.{NodeSeq, XML}
trait ReACEMentionIdentifiers {
val mId: Option[String]
val eId: Option[String]
val headStart: Option[Int]
val headEnd: Option[Int]
val headLength: Option[Int]
val mType: String
val mSubType: String
}
trait ReACERelationIdentifiers {
val rId: Option[String]
val rType: Option[String]
val rSubtype: Option[String]
}
trait ReACESentenceAnnotations {
val paragraphId: Option[String]
val sentenceId: Option[String]
}
trait ReACEWordAnnotations {
val lemma: Option[String]
val pos: Option[String]
val chunk: Option[String]
val nounHead: Option[String]
val verbStem: Option[String]
val verbHead: Option[String]
val verbVoice: Option[String]
val verbNeg: Option[String]
}
class ReACESentenceId(val sentId: String)
object LoadReACE {
private def getAttr(ns: NodeSeq, key: String): Option[String] = {
val fullKey: String = "@" + key
val v = (ns \ fullKey).text
if (v == "") None
else Some(v)
}
private def makeTokenAnnotations(wordXml: NodeSeq): ReACEWordAnnotations = {
val a: String => Option[String] = getAttr(wordXml, _)
new ReACEWordAnnotations {
val lemma: Option[String] = a("l")
val pos: Option[String] = a("p")
val chunk: Option[String] = a("phr")
val nounHead: Option[String] = a("headn")
val verbStem: Option[String] = a("vstem")
val verbHead: Option[String] = a("headv")
val verbVoice: Option[String] = a("voice")
val verbNeg: Option[String] = a("neg")
}
}
private def makeDoc(xml: String): Document = {
val doc = new Document().setName(xml)
doc.annotators(classOf[Token]) = UnknownDocumentAnnotator.getClass
doc.annotators(classOf[Sentence]) = UnknownDocumentAnnotator.getClass
doc.annotators(classOf[PennPosTag]) = UnknownDocumentAnnotator.getClass
doc.attr += new ACEFileIdentifier(xml)
val xmlText: NodeSeq = XML.loadFile(xml + ".ttt.xml")
var currP = 0
for (p <- xmlText \\ "p") {
currP += 1
for (s <- p \\ "s") {
val sId = getAttr(s, "id")
val sent = new Sentence(doc)
sent.attr += new ReACESentenceAnnotations {
val paragraphId = Some(currP.toString)
val sentenceId = sId
}
for (w <- s \\ "w") {
val t = new Token(sent, w.text)
doc.appendString(" ")
val annotations = makeTokenAnnotations(w)
t.attr += annotations // TODO I think these annotations should go in more standard FACTORIE NLP form -akm
annotations.pos.foreach(p => t.attr += new PennPosTag(t, p))
}
}
}
doc
}
private def lookupEntityMention(doc: Document, id: String): Option[Mention] = {
val opt = doc.attr[ner.ConllNerSpanBuffer].find {
s => {
val a = s.attr[ReACEMentionIdentifiers]
(a ne null) && a.mId.get == id
}
}
if (opt == None) None
else Some(opt.get.asInstanceOf[Mention])
}
def addNrm(doc: Document, xml: String): Document = {
val coref = doc.getCoref
var xmlText: NodeSeq = XML.loadFile(xml + ".nrm.xml")
assert(doc.attr[ACEFileIdentifier].fileId == xml) // adding to the right document?
// Add mentions
for (mention <- xmlText \\ "ne") {
// named-entity mentions
// phrase span
val start = (mention \ "@fr").text.drop(1).toInt - 1
val end = (mention \ "@to").text.drop(1).toInt - 1
val length = end - start + 1
// head span
val hstart = (mention \ "@hfr").text.drop(1).toInt - 1
val hend = (mention \ "@hto").text.drop(1).toInt - 1
val hlength = hend - hstart + 1
// ner type
val nerType = (mention \ "@t").text
val nerSubType = (mention \ "@st").text
val phrase = new Phrase(doc.asSection,start,length,hend)
phrase.attr += new ConllNerSpan(doc.asSection,start,length,nerType)
val m = coref.addMention(phrase)
m.attr += new ReACEMentionIdentifiers {
val mId = getAttr(mention, "id")
val eId = getAttr(mention, "gid")
val headStart = Some(hstart)
val headEnd = Some(hend)
val headLength = Some(hlength)
val mType = nerType
val mSubType = nerSubType
}
}
// Add relations
xmlText = XML.loadFile(xml + ".nrm.xml") // is there a way to avoid rereading?
// doc.attr += new RelationMentions
// for (rel <- xmlText \\ "rel") {
// val ids = new ReACERelationIdentifiers {
// val rId = getAttr(rel, "id")
// val rType = getAttr(rel, "t")
// val rSubtype = getAttr(rel, "st")
// }
//
// val e1 = lookupEntityMention(doc, getAttr(rel, "e1").get).get
// val e2 = lookupEntityMention(doc, getAttr(rel, "e2").get).get
// val args = Seq(e1, e2)
//
// val m = new RelationMention(e1, e2, ids.rType.get, Some(ids.rSubtype.get))
// m.attr += ids
// doc.attr[RelationMentions].add(m)(null)
// args.foreach(_.attr.getOrElseUpdate(new RelationMentions).add(m)(null))
// }
doc
}
class MentionsSet extends SetVariable[Mention]
// TODO: consider renaming this to fromFile to match the API for other loaders.
// But if renamed, how can the user know that ttt.xml is required?
def fromTtt(ttt: String): Document = {
val fileStr = ttt.dropRight(8)
val doc = makeDoc(fileStr)
addNrm(doc, fileStr)
doc
}
def fromDirectory(dir: String, takeOnly: Int = Int.MaxValue): Seq[Document] =
new File(dir).listFiles().filter(_.getName.endsWith(".ttt.xml")).take(takeOnly).map(f => fromTtt(f.getAbsolutePath))
def main(args: Array[String]): Unit = {
val docs = fromDirectory(args(0))
for (d <- docs)
d.attr[ner.ConllNerSpanBuffer].foreach(s => println(s))
}
}
| {
"content_hash": "8a19099efee515125257ebdc30c728bf",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 120,
"avg_line_length": 31.572164948453608,
"alnum_prop": 0.6364081632653061,
"repo_name": "patverga/factorie",
"id": "9c1d7a127dd401d6dff5229157d3b20bc3610ec4",
"size": "6872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/cc/factorie/app/nlp/load/LoadReACE.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Emacs Lisp",
"bytes": "80286"
},
{
"name": "Lex",
"bytes": "19711"
},
{
"name": "Makefile",
"bytes": "2639"
},
{
"name": "Scala",
"bytes": "3453937"
},
{
"name": "Shell",
"bytes": "23614"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.