file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
llvm-asm-in-moved.rs
// run-pass #![feature(llvm_asm)] #![allow(deprecated)] // llvm_asm! #![allow(dead_code)] use std::cell::Cell; #[repr(C)] struct NoisyDrop<'a>(&'a Cell<&'static str>); impl<'a> Drop for NoisyDrop<'a> { fn drop(&mut self)
} #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn main() { let status = Cell::new("alive"); { let _y: Box<NoisyDrop>; let x = Box::new(NoisyDrop(&status)); unsafe { llvm_asm!("mov $1, $0" : "=r"(_y) : "r"(x)); } assert_eq!(status.get(), "alive");...
{ self.0.set("destroyed"); }
identifier_body
app.module.ts
import {NgModule} from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {FormsModule} from "@angular/forms"; import {HttpModule} from "@angular/http"; import {RouterModule} from "@angular/router"; import {ENV_PROVIDERS} from "./environment"; import {ROUTES} from "./app.routes"; import {A...
{ }
AppModule
identifier_name
app.module.ts
import {NgModule} from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {FormsModule} from "@angular/forms"; import {HttpModule} from "@angular/http"; import {RouterModule} from "@angular/router"; import {ENV_PROVIDERS} from "./environment"; import {ROUTES} from "./app.routes"; import {A...
HttpModule, RouterModule.forRoot(ROUTES, { useHash: true }) ], providers: [ // expose our Services and Providers into Angular's dependency injection ENV_PROVIDERS, APP_PROVIDERS ] }) export class AppModule { }
FormsModule,
random_line_split
datedetectortestcase.py
# This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban is distributed in the hope t...
def testGetEpochTime(self): log = "1138049999 [sshd] error: PAM: Authentication failure" date = [2006, 1, 23, 21, 59, 59, 0, 23, 0] dateUnix = 1138049999.0 self.assertEqual(self.__datedetector.getTime(log), date) self.assertEqual(self.__datedetector.getUnixTime(log), dateUnix) def testGetTime(self):...
"""Call after every test case."""
identifier_body
datedetectortestcase.py
# This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban is distributed in the hope t...
(self): """Call after every test case.""" def testGetEpochTime(self): log = "1138049999 [sshd] error: PAM: Authentication failure" date = [2006, 1, 23, 21, 59, 59, 0, 23, 0] dateUnix = 1138049999.0 self.assertEqual(self.__datedetector.getTime(log), date) self.assertEqual(self.__datedetector.getUnixTim...
tearDown
identifier_name
datedetectortestcase.py
# This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. #
# Fail2Ban 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with...
random_line_split
test_torchserve.py
# Copyright 2019 kubeflow.org. # # 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,...
(): service_name = "mnist" predictor = V1beta1PredictorSpec( min_replicas=1, pytorch=V1beta1TorchServeSpec( storage_uri="gs://kfserving-examples/models/torchserve/image_classifier", protocol_version="v1", resources=V1ResourceRequirements( reque...
test_torchserve_kfserving
identifier_name
test_torchserve.py
# Copyright 2019 kubeflow.org. # # 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,...
service_name = "mnist" predictor = V1beta1PredictorSpec( min_replicas=1, pytorch=V1beta1TorchServeSpec( storage_uri="gs://kfserving-examples/models/torchserve/image_classifier", protocol_version="v1", resources=V1ResourceRequirements( requests={"cp...
identifier_body
test_torchserve.py
# Copyright 2019 kubeflow.org. # # 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,...
def test_torchserve_kfserving(): service_name = "mnist" predictor = V1beta1PredictorSpec( min_replicas=1, pytorch=V1beta1TorchServeSpec( storage_uri="gs://kfserving-examples/models/torchserve/image_classifier", protocol_version="v1", resources=V1ResourceRequ...
from ..common.utils import predict from ..common.utils import KFSERVING_TEST_NAMESPACE KFServing = KFServingClient(config_file=os.environ.get("KUBECONFIG", "~/.kube/config"))
random_line_split
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that...
#[allow(missing_docs)] #[derive( Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss, )] pub enum GeometryBox { FillBox, StrokeBox, ViewBox, ShapeBox(ShapeBox), } /// A float area shape, for `shape-outside`. pub type FloatAreaShape<BasicShape, Image> = S...
pub type ClippingShape<BasicShape, Url> = ShapeSource<BasicShape, GeometryBox, Url>; /// <https://drafts.fxtf.org/css-masking-1/#typedef-geometry-box>
random_line_split
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that...
{ /// The filling rule for the svg path. #[css(skip_if = "fill_is_default")] #[animation(constant)] pub fill: FillRule, /// The svg path data. pub path: SVGPathData, } // FIXME(nox): Implement ComputeSquaredDistance for T types and stop // using PartialEq here, this will let us derive this imp...
Path
identifier_name
basic_shape.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! CSS handling for the [`basic-shape`](https://drafts.csswg.org/css-shapes/#typedef-basic-shape) //! types that...
, (&ShapeSource::Path(ref this), &ShapeSource::Path(ref other)) if this.fill == other.fill => { this.path.compute_squared_distance(&other.path) }, _ => Err(()), } } } impl<B, T, U> ToAnimatedZero for ShapeSource<B, T, U> { ...
{ this.compute_squared_distance(other) }
conditional_block
knx.py
""" Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ from enum import Enum import logging import voluptuous as vol from homeassistant.const import ( CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM, CONF_TYPE, TEMP_CELSIUS ...
def convert_percent(raw_value): """Conversion for scaled byte values. 1byte percentage scaled KNX Telegram. Defined in KNX 3.7.2 - 3.10. """ value = 0 try: value = raw_value[0] except (IndexError, ValueError): # pknx returns a non-iterable type for unsuccessful reads ...
"""Conversion for 2 byte floating point values. 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10 """ from knxip.conversion import knx2_to_float from knxip.core import KNXException try: return knx2_to_float(raw_value) except KNXException as exception: _LOGGER.e...
identifier_body
knx.py
""" Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ from enum import Enum import logging import voluptuous as vol from homeassistant.const import ( CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM, CONF_TYPE, TEMP_CELSIUS ...
(Enum): """Enum to indicate conversion type for the KNX address.""" FLOAT = 1 PERCENT = 2 # define the fixed settings required for each sensor type FIXED_SETTINGS_MAP = { # Temperature as defined in KNX Standard 3.10 - 9.001 DPT_Value_Temp CONF_TEMPERATURE: { 'unit': TEMP_CELSIUS, ...
KNXAddressType
identifier_name
knx.py
""" Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ from enum import Enum import logging import voluptuous as vol from homeassistant.const import ( CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM, CONF_TYPE, TEMP_CELSIUS ...
'default_maximum': 670760, 'address_type': KNXAddressType.FLOAT }, # Speed m/s as defined in KNX Standard 3.10 - 9.005 DPT_Value_Wsp CONF_SPEED_MS: { 'unit': 'm/s', 'default_minimum': 0, 'default_maximum': 670760, 'address_type': KNXAddressType.FLOAT }, ...
CONF_TEMPERATURE: { 'unit': TEMP_CELSIUS, 'default_minimum': -273,
random_line_split
knx.py
""" Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ from enum import Enum import logging import voluptuous as vol from homeassistant.const import ( CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM, CONF_TYPE, TEMP_CELSIUS ...
else: value = self.convert(self._data) if self._minimum_value <= value <= self._maximum_value: self._value = value @property def cache(self): """We don't want to cache any Sensor Value.""" return False def convert_float(raw_value): ...
value = 0
conditional_block
Todo.py
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today()) def is_overdue(self): """ Returns True ...
is_active
identifier_name
Todo.py
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
return 0 def length(self): """ Returns the length (in days) of the task, by considering the start date and the due date. When there is no start date, its creation date is used. Returns 0 when one of these dates is missing. """ start = self.start_date() or se...
diff = due - date.today() return diff.days
conditional_block
Todo.py
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
class Todo(TodoBase): """ This class adds common functionality with respect to dates to the Todo base class, mainly by interpreting the start and due dates of task. """ def __init__(self, p_str): TodoBase.__init__(self, p_str) self.attributes = {} def get_date(self, p_tag): ...
from topydo.lib.Utils import date_string_to_date
random_line_split
Todo.py
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
def length(self): """ Returns the length (in days) of the task, by considering the start date and the due date. When there is no start date, its creation date is used. Returns 0 when one of these dates is missing. """ start = self.start_date() or self.creation_date(...
""" Returns the number of days till the due date. Returns a negative number of days when the due date is in the past. Returns 0 when the task has no due date. """ due = self.due_date() if due: diff = due - date.today() return diff.days retu...
identifier_body
cvedbsync.py
"""Update vulnerability sources.""" from selinon import StoragePool from f8a_worker.base import BaseTask from f8a_worker.enums import EcosystemBackend from f8a_worker.models import Ecosystem from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser from f8a_worker.workers import CVEcheckerTask clas...
def execute(self, arguments): """Start the task. :param arguments: optional argument 'only_already_scanned' to run only on already analysed packages :return: EPV dict describing which packages should be analysed """ only_already_scanned = arguments.pop('only_alread...
"""Get EPV that were recently updated in OSS Index, so they can contain new vulnerabilities. Get components (e:p:v) that were recently (since previous_sync_timestamp) updated in OSS Index, which means that they can contain new vulnerabilities. :param previous_sync_timestamp: timestamp of previ...
identifier_body
cvedbsync.py
"""Update vulnerability sources.""" from selinon import StoragePool from f8a_worker.base import BaseTask from f8a_worker.enums import EcosystemBackend from f8a_worker.models import Ecosystem from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser from f8a_worker.workers import CVEcheckerTask clas...
ignore_modification_time = (arguments.pop('ignore_modification_time', False) if arguments else False) CVEcheckerTask.update_victims_cve_db_on_s3() self.log.debug('Updating sync associated metadata') s3 = StoragePool.get_connected_storage('S3VulnDB') ...
random_line_split
cvedbsync.py
"""Update vulnerability sources.""" from selinon import StoragePool from f8a_worker.base import BaseTask from f8a_worker.enums import EcosystemBackend from f8a_worker.models import Ecosystem from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser from f8a_worker.workers import CVEcheckerTask clas...
# get components which might have new vulnerabilities since previous sync to_scan = self.components_to_scan(previous_sync_timestamp, only_already_scanned) return {'modified': to_scan}
previous_sync_timestamp = 0
conditional_block
cvedbsync.py
"""Update vulnerability sources.""" from selinon import StoragePool from f8a_worker.base import BaseTask from f8a_worker.enums import EcosystemBackend from f8a_worker.models import Ecosystem from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser from f8a_worker.workers import CVEcheckerTask clas...
(self, previous_sync_timestamp, only_already_scanned): """Get EPV that were recently updated in OSS Index, so they can contain new vulnerabilities. Get components (e:p:v) that were recently (since previous_sync_timestamp) updated in OSS Index, which means that they can contain new vulnerabiliti...
components_to_scan
identifier_name
marker.ts
import {RenderOne} from "./defs" import {XYGlyph, XYGlyphView, XYGlyphData} from "../glyphs/xy_glyph" import type {MarkerGLGlyph} from "../glyphs/webgl/markers" import {PointGeometry, SpanGeometry, RectGeometry, PolyGeometry} from "core/geometry" import {LineVector, FillVector} from "core/property_mixins" import {Line,...
angle: [ p.AngleSpec, 0 ], }) } }
random_line_split
marker.ts
import {RenderOne} from "./defs" import {XYGlyph, XYGlyphView, XYGlyphData} from "../glyphs/xy_glyph" import type {MarkerGLGlyph} from "../glyphs/webgl/markers" import {PointGeometry, SpanGeometry, RectGeometry, PolyGeometry} from "core/geometry" import {LineVector, FillVector} from "core/property_mixins" import {Line,...
protected _hit_poly(geometry: PolyGeometry): Selection { const {sx, sy} = geometry // TODO (bev) use spatial index to pare candidate list const candidates = range(0, this.sx.length) const indices = [] for (let i = 0, end = candidates.length; i < end; i++) { const index = candidates[i] ...
{ const {sx0, sx1, sy0, sy1} = geometry const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1) const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1) const indices = this.index.indices({x0, x1, y0, y1}) return new Selection({indices}) }
identifier_body
marker.ts
import {RenderOne} from "./defs" import {XYGlyph, XYGlyphView, XYGlyphData} from "../glyphs/xy_glyph" import type {MarkerGLGlyph} from "../glyphs/webgl/markers" import {PointGeometry, SpanGeometry, RectGeometry, PolyGeometry} from "core/geometry" import {LineVector, FillVector} from "core/property_mixins" import {Line,...
(geometry: PolyGeometry): Selection { const {sx, sy} = geometry // TODO (bev) use spatial index to pare candidate list const candidates = range(0, this.sx.length) const indices = [] for (let i = 0, end = candidates.length; i < end; i++) { const index = candidates[i] if (hittest.point_i...
_hit_poly
identifier_name
options.js
var optionsApp = angular.module('twBlockchain', ['ngRoute','kcd.directives','datatables']) optionsApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/receipts', { templateUrl: 'partial_receipts.html', controller: 'ReceiptsController' }). when('/protected', { ...
}); function filterDataset() { $scope.receipts = originalDataset.filter((item) => { return item.username.toLowerCase().indexOf($scope.data.search.toLowerCase()) > -1 || item.connection.toLowerCase().indexOf($scope.data.search.toLowerCase()) > -1; }); } function s...
{ filterDataset(); sliceReceipts(); makePageArray(); }
conditional_block
options.js
var optionsApp = angular.module('twBlockchain', ['ngRoute','kcd.directives','datatables']) optionsApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/receipts', { templateUrl: 'partial_receipts.html', controller: 'ReceiptsController' }). when('/protected', { ...
function makePageArray() { $scope.pages = []; for (var i = 0; i < getNumOfPages(); i++) { $scope.pages.push(i); } } function setPage(num) { if (num >= 0 && num < getNumOfPages()) $scope.currentPage = num; sliceReceipts(); } }]); optionsApp.co...
{ return Math.floor($scope.receipts.length / amount) + 1; }
identifier_body
options.js
var optionsApp = angular.module('twBlockchain', ['ngRoute','kcd.directives','datatables']) optionsApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/receipts', { templateUrl: 'partial_receipts.html', controller: 'ReceiptsController' }). when('/protected', { ...
if (originalDataset) { filterDataset(); sliceReceipts(); makePageArray(); } }); function filterDataset() { $scope.receipts = originalDataset.filter((item) => { return item.username.toLowerCase().indexOf($scope.data.search.toLowerCase()) > -...
$scope.$watch('data.search', function() {
random_line_split
options.js
var optionsApp = angular.module('twBlockchain', ['ngRoute','kcd.directives','datatables']) optionsApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/receipts', { templateUrl: 'partial_receipts.html', controller: 'ReceiptsController' }). when('/protected', { ...
() { $scope.slicedReceipts = $scope.receipts.slice($scope.currentPage * amount, ($scope.currentPage + 1) * amount); } function getNumOfPages() { return Math.floor($scope.receipts.length / amount) + 1; } function makePageArray() { $scope.pages = []; for (var i = 0; i < get...
sliceReceipts
identifier_name
build_project.py
#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg():
def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argpars...
parser.add_argument('--host', required=True, help='the url for the Materials Commons server')
identifier_body
build_project.py
#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', ...
print 'Error: ', err
random_line_split
build_project.py
#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def
(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(desc...
set_datapath_arg
identifier_name
build_project.py
#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', ...
else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err
print "Refreshed project with name = " + project.name
conditional_block
languages.js
/*! * js-file-browser * Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file. * * With components from: Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /*!
* licensing@sencha.com * http://www.sencha.com/license */ /* This file is automaticly generated by create_language_js.py */ // some data used in the examples Ext.namespace('Ext.exampledata'); // TODO: complete and sort the list Ext.exampledata.languages = [ ['af', 'Afrikaans', 'ISO-8859-2'], ['bg', 'Bulgarian', ...
* Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc.
random_line_split
ChatOutput.py
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # #...
self._append_to_chat(text, scroll) def _append_to_chat(self, html_string, scroll): '''Method that appends an html string to the chat view''' vert_scroll_bar = self.verticalScrollBar() position = vert_scroll_bar.value() self._chat_text.append(html_string) self.setTex...
msg.alias = Plus.msnplus_strip(msg.alias) msg.display_name = Plus.msnplus_strip(msg.display_name) text = self.formatter.format(msg)
conditional_block
ChatOutput.py
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # #...
(self, msg, scroll): if msg.type == "status": msg.message = Plus.msnplus_strip(msg.message) text = self.formatter.format_information(msg.message) else: msg.alias = Plus.msnplus_strip(msg.alias) msg.display_name = Plus.msnplus_strip(msg.display_name) ...
add_message
identifier_name
ChatOutput.py
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # #...
from gui.base import Desktop log = logging.getLogger('qt4ui.widgets.ChatOutput') class ChatOutput (gui.base.OutputText, QtGui.QTextBrowser): '''A widget which displays various messages of a conversation''' NAME = 'Output Text' DESCRIPTION = _('A widget to display the conversation messages') AUTHOR = '...
random_line_split
ChatOutput.py
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # #...
def _on_link_clicked(self, url): href = unicode(url.toString()) if href.startswith("search://"): self.search_request.emit(href) return if not href.startswith("file://"): Desktop.open(href) return def clear(self, source="", target="", ta...
'''Constructor''' QtGui.QTextBrowser.__init__(self, parent) gui.base.OutputText.__init__(self, config) self.formatter = MessageFormatter() self._chat_text = QtCore.QString('') self.setOpenLinks(False) self.anchorClicked.connect(self._on_link_clicked) self.clear()
identifier_body
oracle.rs
use aes; use rand; pub struct Oracle { key: [u8; 16], iv: [u8; 16], } impl Oracle { pub fn new() -> Oracle { Oracle { key: random_block(), iv: random_block() } } #[cfg(test)] pub fn controlled(key : &[u8; 16], iv: &[u8; 16]) -> Oracle { Oracle {...
use super::contains; #[test] fn contains_pass() { let container = vec![0,1,2,3,4]; let containee = vec![2,3]; assert_eq!(contains(&container[..], &containee[..]), true); } #[test] fn contains_fail() { let container = vec![0,1,2,3,4]; let containee = ve...
{ let key = [0x79, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x61, 0x72, 0x69, 0x6e, 0x65]; //"yellow submarine" let iv = [0x74, 0x68, 0x65, 0x20, 0x31, 0x73, 0x74, 0x20, 0x31, 0x36, 0x20, 0x62, 0x79, 0x74, 0x65, 0x73]; //"the 1st 16 bytes" ...
identifier_body
oracle.rs
use aes; use rand; pub struct Oracle { key: [u8; 16], iv: [u8; 16], } impl Oracle { pub fn new() -> Oracle { Oracle { key: random_block(), iv: random_block() } } #[cfg(test)] pub fn controlled(key : &[u8; 16], iv: &[u8; 16]) -> Oracle { Oracle {...
0xeb, 0xac, 0x3b, 0x47, 0x7a, 0xd1, 0x3d, 0x92, 0x2b, 0x40, 0x8a, 0x39, 0xd0, 0x34, 0xf9, 0x9e, 0x5b, 0x18, 0x3a, 0xbe, 0x51, 0x64, 0x6f, 0x21, 0x90, 0xc1, 0x64, 0x6b, 0xbe, 0x8a, 0x16, 0x2b, 0x41, 0x1c, 0x35...
let output = oracle.encrypt(""); let expected = vec![0x5f, 0x42, 0xc3, 0xdd, 0x32, 0xfe, 0x04, 0x86, 0x21, 0xc0, 0xea, 0xc1, 0x96, 0xbd, 0x01, 0xe4, 0x79, 0xdb, 0x1c, 0x4d, 0xd9, 0x78, 0x9a, 0x41, 0xac, 0xfd, 0x0a,
random_line_split
oracle.rs
use aes; use rand; pub struct Oracle { key: [u8; 16], iv: [u8; 16], } impl Oracle { pub fn new() -> Oracle { Oracle { key: random_block(), iv: random_block() } } #[cfg(test)] pub fn controlled(key : &[u8; 16], iv: &[u8; 16]) -> Oracle { Oracle {...
() -> [u8; 16] { use rand::Rng; let mut rng = rand::thread_rng(); let mut block = [0u8; 16]; for el in block.iter_mut() { *el = rng.gen::<u8>(); } block } fn contains(container: &[u8], containee: &[u8]) -> bool { for idx in 0..(container.len()-containee.len()) { if containe...
random_block
identifier_name
oracle.rs
use aes; use rand; pub struct Oracle { key: [u8; 16], iv: [u8; 16], } impl Oracle { pub fn new() -> Oracle { Oracle { key: random_block(), iv: random_block() } } #[cfg(test)] pub fn controlled(key : &[u8; 16], iv: &[u8; 16]) -> Oracle { Oracle {...
else { false } } } fn random_block() -> [u8; 16] { use rand::Rng; let mut rng = rand::thread_rng(); let mut block = [0u8; 16]; for el in block.iter_mut() { *el = rng.gen::<u8>(); } block } fn contains(container: &[u8], containee: &[u8]) -> bool { fo...
{ contains(&decoded, "user=admin".as_bytes()) }
conditional_block
index.ts
import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import 'rxjs/add/operator/toPromise'; import {Album} from '../../models/album'; @Injectable() export class AlbumService { private albumsUrl = location.protocol + '//jsonplaceholder.typicode.com/albums';
getAlbums(): Promise<Album[]> { return this.http.get(this.albumsUrl) .toPromise() .then(response => response.json().map((v) => new Album(v))) .catch(this.handleError); } getAlbum(id: number): Promise<Album> { const url = `${this.albumsUrl}/${id}`; return this.http.get(url) .toPromise...
constructor(private http: Http) { }
random_line_split
index.ts
import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import 'rxjs/add/operator/toPromise'; import {Album} from '../../models/album'; @Injectable() export class AlbumService { private albumsUrl = location.protocol + '//jsonplaceholder.typicode.com/albums'; constructor(private http: Http...
(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
handleError
identifier_name
CreateGroup.react.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw n...
_possibleConstructorReturn
identifier_name
CreateGroup.react.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
_inherits(CreateGroup, _Component); CreateGroup.getStores = function getStores() { return [_CreateGroupStore2.default]; }; CreateGroup.calculateState = function calculateState() { return { name: _CreateGroupStore2.default.getGroupName(), search: _CreateGroupStore2.default.getGroupSearch(),...
var CreateGroup = function (_Component) {
random_line_split
CreateGroup.react.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "functi...
{ if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
identifier_body
TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.ts
//@filename: part1.ts module A { export interface Point { x: number; y: number; } export module Utils { export function mirror<T extends Point>(p: T) { return { x: p.y, y: p.x }; }
//@filename: part2.ts module A { // not a collision, since we don't export var Origin: string = "0,0"; export module Utils { export class Plane { constructor(public tl: Point, public br: Point) { } } } } //@filename: part3.ts // test the merging actually worked...
} export var Origin: Point = { x: 0, y: 0 }; }
random_line_split
TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.ts
//@filename: part1.ts module A { export interface Point { x: number; y: number; } export module Utils { export function
<T extends Point>(p: T) { return { x: p.y, y: p.x }; } } export var Origin: Point = { x: 0, y: 0 }; } //@filename: part2.ts module A { // not a collision, since we don't export var Origin: string = "0,0"; export module Utils { export class Plane { ...
mirror
identifier_name
0002_dispensed.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('stats', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dispensed', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ...
Migration
identifier_name
0002_dispensed.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('stats', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dispensed', fields=[ ...
('dispensed_others', models.IntegerField(help_text='All other projects dispensed, and those with no specific reason.')), ], options={ }, bases=(models.Model,), ), ]
('dispensed_by_spokesmen', models.IntegerField(help_text='Those projects dispensed due to `junta de portavoces`.')),
random_line_split
0002_dispensed.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('stats', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dispensed', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('total_approved', models.In...
identifier_body
test_forked_green_actors.py
import sys if '' not in sys.path: sys.path.append('') import time import unittest from pyactors.logs import file_logger from pyactors.exceptions import EmptyInboxException from tests import ForkedGreActor as TestActor from multiprocessing import Manager class ForkedGreenletActorTest(unittest.TestCase): de...
while True: try: result.append(actor.inbox.get()) except EmptyInboxException: break self.assertEqual(len(result), 10) self.assertEqual(actor.processing, False) self.assertEqual(actor.waiting, False) if __name__ == '__main__': ...
result = []
random_line_split
test_forked_green_actors.py
import sys if '' not in sys.path: sys.path.append('') import time import unittest from pyactors.logs import file_logger from pyactors.exceptions import EmptyInboxException from tests import ForkedGreActor as TestActor from multiprocessing import Manager class ForkedGreenletActorTest(unittest.TestCase): de...
actor.stop() result = [] while True: try: result.append(actor.inbox.get()) except EmptyInboxException: break self.assertEqual(len(result), 10) self.assertEqual(actor.processing, False) self.assertEqual(act...
time.sleep(0.1)
conditional_block
test_forked_green_actors.py
import sys if '' not in sys.path: sys.path.append('') import time import unittest from pyactors.logs import file_logger from pyactors.exceptions import EmptyInboxException from tests import ForkedGreActor as TestActor from multiprocessing import Manager class ForkedGreenletActorTest(unittest.TestCase):
if __name__ == '__main__': unittest.main()
def test_run(self): ''' test_forked_green_actors.test_run ''' test_name = 'test_forked_gen_actors.test_run' logger = file_logger(test_name, filename='logs/%s.log' % test_name) actor = TestActor() actor.start() while actor.processing: time.sleep(0.1) ...
identifier_body
test_forked_green_actors.py
import sys if '' not in sys.path: sys.path.append('') import time import unittest from pyactors.logs import file_logger from pyactors.exceptions import EmptyInboxException from tests import ForkedGreActor as TestActor from multiprocessing import Manager class ForkedGreenletActorTest(unittest.TestCase): de...
(self): ''' test_forked_green_actors.test_run ''' test_name = 'test_forked_gen_actors.test_run' logger = file_logger(test_name, filename='logs/%s.log' % test_name) actor = TestActor() actor.start() while actor.processing: time.sleep(0.1) acto...
test_run
identifier_name
__init__.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
( owner_name: str, project_name: str, project_uuid: str, run_name: str, run_uuid: str, run_path: str, compiled_operation: V1CompiledOperation, params: Optional[Dict], default_sa: str = None, internal_auth: bool = False, default_auth: bool = False, converters: Dict[str, An...
make
identifier_name
__init__.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
def make( owner_name: str, project_name: str, project_uuid: str, run_name: str, run_uuid: str, run_path: str, compiled_operation: V1CompiledOperation, params: Optional[Dict], default_sa: str = None, internal_auth: bool = False, default_auth: bool = False, converters: Dict...
from polyaxon.polyflow import V1CompiledOperation from polyaxon.polypod.compiler import converter, resolver
random_line_split
__init__.py
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # 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 ...
resolver_obj, compiled_operation = resolver.resolve( compiled_operation=compiled_operation, owner_name=owner_name, project_name=project_name, project_uuid=project_uuid, run_name=run_name, run_path=run_path, run_uuid=run_uuid, params=params, ) retur...
identifier_body
async.d.ts
export { PromiseWrapper, Promise, PromiseCompleter } from 'angular2/src/core/facade/promise'; export declare namespace NodeJS { interface Timer { } } export declare class TimerWrapper { static setTimeout(fn: (...args: any[]) => void, millis: number): NodeJS.Timer; static clearTimeout(id: NodeJS.Timer): ...
extends Observable { observer(generator: any): any; toRx(): any; next(value: any): void; throw(error: any): void; return(value?: any): void; }
EventEmitter
identifier_name
async.d.ts
export { PromiseWrapper, Promise, PromiseCompleter } from 'angular2/src/core/facade/promise'; export declare namespace NodeJS { interface Timer { } } export declare class TimerWrapper { static setTimeout(fn: (...args: any[]) => void, millis: number): NodeJS.Timer; static clearTimeout(id: NodeJS.Timer): ...
export declare class EventEmitter extends Observable { observer(generator: any): any; toRx(): any; next(value: any): void; throw(error: any): void; return(value?: any): void; }
* Once a reference implementation of the spec is available, switch to it. */
random_line_split
app.component.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R...
(breadCrumbSvc, _router) { this.breadCrumbSvc = breadCrumbSvc; this._router = _router; this.breadCrumbSvc.setBreadCrumb('Project Dashboard'); } AppComponent.prototype.navigateHome = function () { this._router.navigate(['home']); ; }; AppComponent = __deco...
AppComponent
identifier_name
app.component.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R...
AppComponent.prototype.navigateHome = function () { this._router.navigate(['home']); ; }; AppComponent = __decorate([ core_1.Component({ selector: 'ts-app', templateUrl: '/app/app-component.html' }), __metadata('design:paramtypes', ...
{ this.breadCrumbSvc = breadCrumbSvc; this._router = _router; this.breadCrumbSvc.setBreadCrumb('Project Dashboard'); }
identifier_body
app.component.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = R...
selector: 'ts-app', templateUrl: '/app/app-component.html' }), __metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router]) ], AppComponent); return AppComponent; }()); exports.AppComponent = AppComponent;
}; AppComponent = __decorate([ core_1.Component({
random_line_split
CommentActionButton.tsx
/* Copyright 2017 Google Inc. 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 dis...
extends React.PureComponent<ICommentActionProps, ICommentActionState> { state = { isFocused: false, isHovered: false, }; render() { const { style, disabled, label, icon, iconHovered, hideLabel, buttonRef, isActive, onClick, } = this.props...
random_line_split
index.tsx
import React, { useState } from 'react'; import { StyleSheet, ImageStyle, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; import {...
({ value, bottom, top, }: { value: number; bottom: number; top: number; }) { 'worklet'; return Math.max(bottom, Math.min(value, top)); } const Example = () => { const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); const panOffset = useOffsetAnimatedValue(); const mainChatHeadPos...
clampToValues
identifier_name
index.tsx
import React, { useState } from 'react'; import { StyleSheet, ImageStyle, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; import {...
<FollowingChatHead key={imageUrl} imageUri={imageUrl} style={{ marginLeft: idx * 5, marginTop: idx * 5, }} offset={headOffset} offsetToFollow={chatHeadsOffsets[idx - 1]} /> ); }); return ( <SafeAreaView style={styles.container}...
</GestureDetector> ); } return (
random_line_split
index.tsx
import React, { useState } from 'react'; import { StyleSheet, ImageStyle, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; import {...
return ( <FollowingChatHead key={imageUrl} imageUri={imageUrl} style={{ marginLeft: idx * 5, marginTop: idx * 5, }} offset={headOffset} offsetToFollow={chatHeadsOffsets[idx - 1]} /> ); }); return ( <SafeAreaView style={st...
{ return ( <GestureDetector gesture={panHandler} key={imageUrl}> <FollowingChatHead offsetToFollow={panOffset} imageUri={imageUrl} offset={headOffset} /> </GestureDetector> ); }
conditional_block
index.tsx
import React, { useState } from 'react'; import { StyleSheet, ImageStyle, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; import {...
const Example = () => { const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); const panOffset = useOffsetAnimatedValue(); const mainChatHeadPosition = useOffsetAnimatedValue(); const chatHeadsOffsets = CHAT_HEADS.map(useOffsetAnimatedValue); const headerHeight = useHeaderHeight(); const ...
{ 'worklet'; return Math.max(bottom, Math.min(value, top)); }
identifier_body
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; us...
} } // Step 5, 6 self.0.remove(index); Ok(()) } } /// A trait to implement helpers for `Arc<Locked<CssRules>>`. pub trait CssRulesHelpers { /// <https://drafts.csswg.org/cssom/#insert-a-css-rule> /// /// Written in this funky way because parsing an @import ...
{ return Err(RulesMutateError::InvalidState); }
conditional_block
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; us...
(&self) -> bool { self.0.is_empty() } } impl DeepCloneWithLock for CssRules { fn deep_clone_with_lock( &self, lock: &SharedRwLock, guard: &SharedRwLockReadGuard, params: &DeepCloneParams, ) -> Self { CssRules(self.0.iter().map(|x| { x.deep_clone_w...
is_empty
identifier_name
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; us...
}
{ let state = { let read_guard = lock.read(); let rules = self.read_with(&read_guard); // Step 1, 2 if index > rules.0.len() { return Err(RulesMutateError::IndexSize); } // Computes the parser state at the given index ...
identifier_body
rule_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A list of CSS rules. #[cfg(feature = "gecko")] use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; us...
pub fn size_of(&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize { let mut n = self.0.shallow_size_of(ops); for rule in self.0.iter() { n += rule.size_of(guard, ops); } n } /// Trivially construct a new set of CSS rules. pub fn new(rul...
impl CssRules { /// Measure heap usage. #[cfg(feature = "gecko")]
random_line_split
digitalocean.rs
use super::command; use super::chain; fn get_subdomain_from_name(name: &str) -> &str { // For subdomains, we only take the first element when split by ".", this allows // us to create naked domain names or use the same subdomain across domains. let components: Vec<&str> = name.split(".").collect(); if ...
(name: &str) { // By default, always attempt to add a new key with [name] mapping to ~/.ssh/id_rsa.pub let create_key_str = format!("doctl compute ssh-key create {} --public-key=\"$(cat ~/.ssh/id_rsa.pub)\"", name); println!("Running command:\n\t\t{}", create_key_str); // Create the actual droplet l...
create_sshkey
identifier_name
digitalocean.rs
use super::command; use super::chain; fn get_subdomain_from_name(name: &str) -> &str { // For subdomains, we only take the first element when split by ".", this allows // us to create naked domain names or use the same subdomain across domains. let components: Vec<&str> = name.split(".").collect(); if ...
} pub fn create_droplet_by_name(name: &str, region: Option<&str>, size: Option<&str>, domain: Option<&str>, enable_backups: Option<&str>) { let ssh_key_mapping_func = |res: &command::Result, cmd_str: String| -> String { let ids : Vec<&str> = res.stdout.lines().collect(); ...
{ &"@" }
conditional_block
digitalocean.rs
use super::command; use super::chain; fn get_subdomain_from_name(name: &str) -> &str { // For subdomains, we only take the first element when split by ".", this allows // us to create naked domain names or use the same subdomain across domains. let components: Vec<&str> = name.split(".").collect(); if ...
let list_records_cmd = format!("doctl compute domain records list {} --format Name,ID --no-header", domain_name); let delete_record_cmd = format!("doctl compute domain records delete -f {} %record_id%", domain_name); // TODO: check the result heh let _ = chain::CommandChain::new() .cmd_nonfatal...
let delete_droplet_cmd = format!("doctl compute droplet delete -f {}", name);
random_line_split
digitalocean.rs
use super::command; use super::chain; fn get_subdomain_from_name(name: &str) -> &str
pub fn create_droplet_by_name(name: &str, region: Option<&str>, size: Option<&str>, domain: Option<&str>, enable_backups: Option<&str>) { let ssh_key_mapping_func = |res: &command::Result, cmd_str: String| -> String { let ids : Vec<&str> = res.stdout.lines().collect(); ...
{ // For subdomains, we only take the first element when split by ".", this allows // us to create naked domain names or use the same subdomain across domains. let components: Vec<&str> = name.split(".").collect(); if components.len() > 2 { // If first throws an error after we've checked length,...
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(dead_code)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(unused_variables)] #![deny(un...
fn layout<'a>( &'a self, containing_block: &ContainingBlock, tree_rank: usize, absolutely_positioned_fragments: &mut Vec<AbsolutelyPositionedFragment<'a>>, ) -> FlowChildren { match self.as_replaced() { Ok(replaced) => match *replaced {}, Err(ifc...
{ match self { IndependentFormattingContext::Replaced(r) => Ok(r), IndependentFormattingContext::Flow(f) => Err(NonReplacedIFC::Flow(f)), } }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(dead_code)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(unused_variables)] #![deny(un...
{ inline_size: Length, block_size: LengthOrAuto, mode: (WritingMode, Direction), } struct DefiniteContainingBlock { size: Vec2<Length>, mode: (WritingMode, Direction), } /// https://drafts.csswg.org/css2/visuren.html#relative-positioning fn relative_adjustement( style: &ComputedValues, in...
ContainingBlock
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(dead_code)] #![allow(unreachable_code)] #![allow(unused_imports)] #![allow(unused_variables)] #![deny(un...
// https://github.com/rust-lang/rust/issues/61129 fn take<T>(x: &mut T) -> T where T: Default, { std::mem::replace(x, Default::default()) }
block: adjust(box_offsets.block_start, box_offsets.block_end), } } // FIXME: use std::mem::take when it’s stable.
random_line_split
tree_sortable.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use SortType; use ffi; use glib::object::{Cast, IsA}; use glib::translate::*; use std::mem::{...
<T, F: Fn(&T, &TreeIter, &TreeIter) -> Ordering>(this: *mut GtkTreeModel, iter: *mut GtkTreeIter, iter2: *mut GtkTreeIter, f: gpointer) -> i32 where T: IsA<TreeSortable> { let f: &F = transmute(f); f(&TreeModel::from_glib_none(this).unsafe_cast(), &from_glib_borrow(iter), ...
trampoline
identifier_name
tree_sortable.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use SortType; use ffi; use glib::object::{Cast, IsA}; use glib::translate::*; use std::mem::{...
where F: Fn(&Self, &TreeIter, &TreeIter) -> Ordering + 'static { unsafe { ffi::gtk_tree_sortable_set_default_sort_func(self.as_ref().to_glib_none().0, Some(trampoline::<Self, F>), in...
fn set_default_sort_func<F>(&self, sort_func: F)
random_line_split
tree_sortable.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use SortType; use ffi; use glib::object::{Cast, IsA}; use glib::translate::*; use std::mem::{...
fn into_raw<F, T>(func: F) -> gpointer where F: Fn(&T, &TreeIter, &TreeIter) -> Ordering + 'static { skip_assert_initialized!(); let func: Box<F> = Box::new(func); Box::into_raw(func) as gpointer } impl<O: IsA<TreeSortable>> TreeSortableExtManual for O { #[inline] fn get_sort_column_id(&self)...
{ Box::<F>::from_raw(ptr as *mut _); }
identifier_body
sto.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from pyquery import PyQuery from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文...
'keywords' ).attr('content') return re.match(r'(.*?),(.*?),.*', st).groups() @property def chapter_list(self): st = re.search( r'ANP_goToPage\("Page_select",(\d+),(\d+),1\);', self.doc.html()) if st.group(1) == self.tid: page_num = int(st.group(2)) ...
def get_title_and_author(self): st = self.doc('meta').filter( lambda i, e: PyQuery(e).attr('name') ==
identifier_body
sto.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from pyquery import PyQuery
from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文s檔s下s載s與s在s線s閱s讀s', 's本s作s品s由s思s兔s網s提s供s下s載s與s在s線s閱s讀s', 's本s作s...
random_line_split
sto.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from pyquery import PyQuery from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文...
self.tool = StoTool def get_title_and_author(self): st = self.doc('meta').filter( lambda i, e: PyQuery(e).attr('name') == 'keywords' ).attr('content') return re.match(r'(.*?),(.*?),.*', st).groups() @property def chapter_list(self): st = re.search( ...
)
identifier_name
sto.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from pyquery import PyQuery from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文...
i + 1), '第{:d}頁'.format(i + 1)) for i in range(page_num)] def get_intro(self): intro = self.doc('meta').filter( lambda i, e: PyQuery(e).attr('name') == 'description' ).attr('content') return intro
PAGE_URL.format(self.tid,
conditional_block
index.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * This module provides a set of common Pipes. */ import {AsyncPipe} from './async_p...
I18nSelectPipe, KeyValuePipe, ];
DatePipe, I18nPluralPipe,
random_line_split
lib.rs
//! Support code for rustc's built in unit-test and micro-benchmarking //! framework. //! //! Almost all user code will only be interested in `Bencher` and //! `black_box`. All other interactions (such as writing tests and //! benchmarks themselves) should be done via the `#[test]` and //! `#[bench]` attributes. //! //...
id: TestId, desc: TestDesc, timeout: Instant, } let tests_len = tests.len(); let mut filtered_tests = filter_tests(opts, tests); if !opts.bench_benchmarks { filtered_tests = convert_benchmarks_to_tests(filtered_tests); } let filtered_tests = { let mut f...
struct TimeoutEntry {
random_line_split
lib.rs
//! Support code for rustc's built in unit-test and micro-benchmarking //! framework. //! //! Almost all user code will only be interested in `Bencher` and //! `black_box`. All other interactions (such as writing tests and //! benchmarks themselves) should be done via the `#[test]` and //! `#[bench]` attributes. //! //...
/// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`. #[inline(never)] fn __rust_begin_short_backtrace<F: FnOnce()>(f: F) { f(); // prevent this frame from being tail-call optimised away black_box(()); } fn run_test_in_process( id: TestId, desc: TestDesc, nocapture: bool, ...
{ let TestDescAndFn { desc, testfn } = test; // Emscripten can catch panics but other wasm targets cannot let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No && cfg!(target_arch = "wasm32") && !cfg!(target_os = "emscripten"); if force_ignore || desc.ignore || i...
identifier_body
lib.rs
//! Support code for rustc's built in unit-test and micro-benchmarking //! framework. //! //! Almost all user code will only be interested in `Bencher` and //! `black_box`. All other interactions (such as writing tests and //! benchmarks themselves) should be done via the `#[test]` and //! `#[bench]` attributes. //! //...
if opts.bench_benchmarks { // All benchmarks run at the end, in serial. for (id, b) in filtered_benchs { let event = TestEvent::TeWait(b.desc.clone()); notify_about_test_event(event)?; run_test(opts, false, id, b, run_strategy, tx.clone(), Concurrent::No); ...
{ while pending > 0 || !remaining.is_empty() { while pending < concurrency && !remaining.is_empty() { let (id, test) = remaining.pop().unwrap(); let timeout = time::get_default_test_timeout(); let desc = test.desc.clone(); let event = ...
conditional_block
lib.rs
//! Support code for rustc's built in unit-test and micro-benchmarking //! framework. //! //! Almost all user code will only be interested in `Bencher` and //! `black_box`. All other interactions (such as writing tests and //! benchmarks themselves) should be done via the `#[test]` and //! `#[bench]` attributes. //! //...
( running_tests: &TestMap, timeout_queue: &mut VecDeque<TimeoutEntry>, ) -> Vec<TestDesc> { let now = Instant::now(); let mut timed_out = Vec::new(); while let Some(timeout_entry) = timeout_queue.front() { if now < timeout_entry.timeout { break; ...
get_timed_out_tests
identifier_name
signals.js
// This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't ...
'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) }
random_line_split
signals.js
// This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't ...
{ module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) }
conditional_block
payloads.py
import logging import plistlib from django.http import HttpResponse from django.urls import reverse from zentral.conf import settings from zentral.utils.certificates import split_certificate_chain from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier from zentral.utils.payloads import sign_pa...
(ota_obj): if isinstance(ota_obj, OTAEnrollmentSession): url_path = reverse("mdm:ota_session_enroll") elif isinstance(ota_obj, OTAEnrollment): url_path = reverse("mdm:ota_enroll") else: raise ValueError("ota_obj not an OTAEnrollment nor an OTAEnrollmentSession") return build_prof...
build_profile_service_configuration_profile
identifier_name
payloads.py
import logging import plistlib from django.http import HttpResponse from django.urls import reverse from zentral.conf import settings from zentral.utils.certificates import split_certificate_chain from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier from zentral.utils.payloads import sign_pa...
scep_payload = build_scep_payload(enrollment_session) payloads = build_root_ca_payloads() mdm_config = { "IdentityCertificateUUID": scep_payload["PayloadUUID"], "Topic": push_certificate.topic, "ServerURL": "{}{}".format( settings["api"]["tls_hostname_for_client_cert_auth"], ...
identifier_body
payloads.py
import logging import plistlib from django.http import HttpResponse from django.urls import reverse from zentral.conf import settings from zentral.utils.certificates import split_certificate_chain from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier from zentral.utils.payloads import sign_pa...
else: payload.update(content) return payload # TODO: BAD. Must check if this is really a root CA before building returning anything def build_root_ca_payloads(): root_certificate = split_certificate_chain(settings["api"]["tls_fullchain"])[-1] return [ build_payload("com.apple.security...
payload["PayloadContent"] = content
conditional_block
payloads.py
import logging import plistlib from django.http import HttpResponse from django.urls import reverse from zentral.conf import settings from zentral.utils.certificates import split_certificate_chain from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier from zentral.utils.payloads import sign_pa...
"Challenge": enrollment_session.get_challenge(), "Keysize": 2048, "KeyType": "RSA", "Key Usage": 5, # 1 is signing, 4 is encryption, 5 is both signing and encryption }, ...
return build_payload("com.apple.security.scep", enrollment_session.get_payload_name(), "scep", {"URL": "{}/scep".format(settings["api"]["tls_hostname"]), # TODO: hardcoded scep url "Subject": subject,
random_line_split