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 |
|---|---|---|---|---|
source.rs | use std::fmt::{self, Debug, Formatter};
use url::Url;
use core::source::{Source, SourceId};
use core::GitReference;
use core::{Dependency, Package, PackageId, Summary};
use util::Config;
use util::errors::CargoResult;
use util::hex::short_hash;
use sources::PathSource;
use sources::git::utils::{GitRemote, GitRevision... | s.to_url().unwrap()
}
} | identifier_body | |
source.rs | use std::fmt::{self, Debug, Formatter};
use url::Url;
use core::source::{Source, SourceId};
use core::GitReference;
use core::{Dependency, Package, PackageId, Summary};
use util::Config;
use util::errors::CargoResult;
use util::hex::short_hash;
use sources::PathSource;
use sources::git::utils::{GitRemote, GitRevision... | (&self) -> &SourceId {
&self.source_id
}
fn update(&mut self) -> CargoResult<()> {
let lock =
self.config
.git_path()
.open_rw(".cargo-lock-git", self.config, "the git checkouts")?;
let db_path = lock.parent().join("db").join(&self.ident);
... | source_id | identifier_name |
win_service_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_service_object as win_service_binding
from cybox.common import HashList
from cybox.objects.win_process_object import WinProcess
from c... | _binding_class = win_service_binding.ServiceDescriptionListType
_namespace = "http://cybox.mitre.org/objects#WinServiceObject-2"
description = fields.TypedField("Description", String, multiple=True)
class WinService(WinProcess):
_binding = win_service_binding
_binding_class = win_service_binding.... | class ServiceDescriptionList(entities.EntityList):
_binding = win_service_binding | random_line_split |
win_service_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_service_object as win_service_binding
from cybox.common import HashList
from cybox.objects.win_process_object import WinProcess
from c... | (WinProcess):
_binding = win_service_binding
_binding_class = win_service_binding.WindowsServiceObjectType
_namespace = "http://cybox.mitre.org/objects#WinServiceObject-2"
_XSI_NS = "WinServiceObj"
_XSI_TYPE = "WindowsServiceObjectType"
service_dll_signature_exists = fields.TypedField("service_... | WinService | identifier_name |
win_service_object.py | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_service_object as win_service_binding
from cybox.common import HashList
from cybox.objects.win_process_object import WinProcess
from c... | _binding = win_service_binding
_binding_class = win_service_binding.WindowsServiceObjectType
_namespace = "http://cybox.mitre.org/objects#WinServiceObject-2"
_XSI_NS = "WinServiceObj"
_XSI_TYPE = "WindowsServiceObjectType"
service_dll_signature_exists = fields.TypedField("service_dll_signature_exis... | identifier_body | |
bin.py | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... | try:
stdout = sys.stdout.buffer
except AttributeError:
stdout = sys.stdout
stdout.write(f.getvalue()) | random_line_split | |
bin.py | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... | f = BytesIO()
new_image.save(f, image.format)
try:
stdout = sys.stdout.buffer
except AttributeError:
stdout = sys.stdout
stdout.write(f.getvalue()) | conditional_block | |
bin.py | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... | parsed_args = parser.parse_args()
image = Image.open(parsed_args.image)
size = (parsed_args.width, parsed_args.height)
new_image = crop_resize(image, size, parsed_args.force)
if parsed_args.display:
new_image.show()
elif parsed_args.output:
new_image.save(parsed_args.output)
else... | identifier_body | |
bin.py | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... | ():
parsed_args = parser.parse_args()
image = Image.open(parsed_args.image)
size = (parsed_args.width, parsed_args.height)
new_image = crop_resize(image, size, parsed_args.force)
if parsed_args.display:
new_image.show()
elif parsed_args.output:
new_image.save(parsed_args.output)
... | main | identifier_name |
index.d.ts | // Type definitions for h2o2 5.4
// Project: https://github.com/hapijs/catbox
// Definitions by: Jason Swearingen <http://github.com/jasonswearingen>, AJP <https://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
im... | }
declare module 'hapi' {
/**
* As one of the handlers for hapi, it is used through the route configuration object.
* [see docs](https://github.com/hapijs/h2o2#usage)
*/
interface RouteHandlerPlugins {
proxy?: H2o2.ProxyHandlerOptions;
}
interface Base_Reply {
/**
... | agent?: http.Agent;
/** maxSockets - sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity. */
maxSockets?: false | number;
} | random_line_split |
index.ts | import produce from 'immer';
import assignIn from 'lodash.assignin';
import {action as createAction, ActionType} from 'typesafe-actions';
import {NodeContextPath} from '@neos-project/neos-ts-interfaces';
import {actionTypes as system, InitAction} from '@neos-project/neos-ui-redux-store/src/System';
import {WorkspaceNa... | case actionTypes.DISCARD_CONFIRMED: {
draft.toBeDiscarded = [];
break;
}
}
});
//
// Export the selectors
//
export {selectors}; | random_line_split | |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
... | unsafe { | random_line_split |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... |
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn... | {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
} | identifier_body |
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writ... | (&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for... | script_chan | identifier_name |
day07-pt1.py | #!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def | (seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
... | window | identifier_name |
day07-pt1.py | #!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(i... |
if __name__ == '__main__':
sys.exit(main(sys.argv)) | random_line_split | |
day07-pt1.py | #!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def window(seq, n=2):
|
def has_abba(string):
for s in window(string, 4):
if s[:2] == s[:1:-1] and s[0] != s[1]:
return True
return False
def main(argv):
if len(argv) < 2:
print("Usage: day07-pt1.py puzzle.txt")
return 1
valid = 0
with open(argv[1]) as f:
for line in ... | "Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield resul... | identifier_body |
day07-pt1.py | #!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(i... |
return False
def main(argv):
if len(argv) < 2:
print("Usage: day07-pt1.py puzzle.txt")
return 1
valid = 0
with open(argv[1]) as f:
for line in f:
nets = re.split('[\[\]]', line.strip())
if any(has_abba(s) for s in nets[::2]) \
and not an... | if s[:2] == s[:1:-1] and s[0] != s[1]:
return True | conditional_block |
generic-impl-more-params-with-defaults.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
struct Vec<T, A = Heap>;
impl<T, A = Heap> Vec<T, A> {
fn new() -> Vec<T, A> {Vec}
}
fn main() {
Vec::<int, Heap, bool>::new();
//~^ ERROR the impl referenced by this path needs at most 2 type parameters,
// but 3 were supplied
//~^^^ ERROR too many type parameters provided: expected at... | Heap | identifier_name |
generic-impl-more-params-with-defaults.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // but 3 were supplied
//~^^^ ERROR too many type parameters provided: expected at most 2, found 3
} | //~^ ERROR the impl referenced by this path needs at most 2 type parameters, | random_line_split |
common.py | # -*- coding: utf-8 -*-
import os
SECRET_KEY = os.environ["SECRET_KEY"]
LANGUAGES = {"en": "English", "es": "Español"}
BABEL_TRANSLATION_DIRECTORIES = "translations"
HASHEDASSETS_CATALOG = "/srv/www/hashedassets.yml"
HASHEDASSETS_SRC_DIR = "static/build"
HASHEDASSETS_OUT_DIR = "/srv/www/site/static"
HASHEDASSETS_... | SENTRY_USER_ATTRS = ["email"]
STARTERKIT_HOMEPAGE_BLUEPRINT_URL_PREFIX = "/" | random_line_split | |
conf.py | # -*- coding: utf-8 -*-
#
# pysaml2 documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 24 08:13:41 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relat... |
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
| random_line_split |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... | extern crate tiny_keccak;
extern crate rlp;
extern crate regex;
#[macro_use]
extern crate heapsize;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate itertools;
#[macro_use]
extern crate log as rlog;
pub extern crate using_queue;
pub extern crate table;
pub mod bloom;
pub mod standard;
#[macro_use]
pu... | extern crate target_info;
extern crate ethcore_bigint as bigint;
extern crate parking_lot;
extern crate ansi_term; | random_line_split |
playlists.py | import mutagen
import os
import re
import sys
from optparse import OptionParser
music_file_exts = ['.mp3', '.wav', '.ogg']
seconds_re = re.compile('(\d+)(\.\d+)? seconds')
def main(argv):
(options, args) = build_parser().parse_args(argv)
validate_options(options)
print('playlist(s) will be written to ', ... | )
if regex:
r = re.compile(regex)
predicates.append(
lambda x: re.search(r, os.path.basename(x['path'])) or re.search(r, x['title']) or re.search(r, x['artist'])
)
return predicates
def build_parser():
parser = OptionParser()
parser.add_option('-n', '--name'... | random_line_split | |
playlists.py | import mutagen
import os
import re
import sys
from optparse import OptionParser
music_file_exts = ['.mp3', '.wav', '.ogg']
seconds_re = re.compile('(\d+)(\.\d+)? seconds')
def main(argv):
(options, args) = build_parser().parse_args(argv)
validate_options(options)
print('playlist(s) will be written to ', ... |
else:
f = {}
meta['title'] = f.get('title',
[os.path.basename(path)])[0]
meta['artist'] = f.get('artist',
[path.split(os.path.sep)[-2]])[0]
return meta
def build_top_10_playlists(root_path, predicates, extended, abso... | match = re.search(seconds_re, f.info.pprint())
meta['seconds'] = match.group(1) if match else '0' | conditional_block |
playlists.py | import mutagen
import os
import re
import sys
from optparse import OptionParser
music_file_exts = ['.mp3', '.wav', '.ogg']
seconds_re = re.compile('(\d+)(\.\d+)? seconds')
def main(argv):
(options, args) = build_parser().parse_args(argv)
validate_options(options)
print('playlist(s) will be written to ', ... |
def validate_options(options):
if not os.path.isdir(options.outdir):
print('output directory does not exist!')
sys.exit(1)
if not os.path.isdir(options.start_at):
print('starting directory does not exist!')
sys.exit(1)
if options.depth != -1:
print('invalid depth: ... | parser = OptionParser()
parser.add_option('-n', '--name', dest='name', default=os.path.basename(os.getcwd()),
help='NAME of playlist', metavar='NAME')
parser.add_option('-s', '--start-at', dest='start_at', default=os.getcwd(),
help='DIR location to start media file se... | identifier_body |
playlists.py | import mutagen
import os
import re
import sys
from optparse import OptionParser
music_file_exts = ['.mp3', '.wav', '.ogg']
seconds_re = re.compile('(\d+)(\.\d+)? seconds')
def main(argv):
(options, args) = build_parser().parse_args(argv)
validate_options(options)
print('playlist(s) will be written to ', ... | (path, extended=False):
meta = {'path': path, 'title': '', 'artist': '', 'seconds': '0'}
if extended:
f = mutagen.File(path)
if f:
match = re.search(seconds_re, f.info.pprint())
meta['seconds'] = match.group(1) if match else '0'
else:
f = {}
me... | extract_metadata | identifier_name |
__openerp__.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the ... | 'bom_views.xml',
],
'active': False,
'installable': True,
'auto_install': False,
} | 'data': [
'security/ir.model.access.csv', | random_line_split |
series-horizontal.component.d.ts | import { EventEmitter, OnChanges, SimpleChanges, TemplateRef } from '@angular/core';
export declare class | implements OnChanges {
bars: any;
x: any;
y: any;
dims: any;
type: string;
series: any;
xScale: any;
yScale: any;
colors: any;
tooltipDisabled: boolean;
gradient: boolean;
activeEntries: any[];
seriesName: string;
tooltipTemplate: TemplateRef<any>;
roundEdges... | SeriesHorizontal | identifier_name |
series-horizontal.component.d.ts | import { EventEmitter, OnChanges, SimpleChanges, TemplateRef } from '@angular/core';
export declare class SeriesHorizontal implements OnChanges {
bars: any;
x: any;
y: any;
dims: any;
type: string;
series: any;
xScale: any;
yScale: any;
colors: any;
tooltipDisabled: boolean;
... | tooltipType: string;
ngOnChanges(changes: SimpleChanges): void;
update(): void;
updateTooltipSettings(): void;
isActive(entry: any): boolean;
trackBy(index: any, bar: any): any;
click(data: any): void;
} | tooltipPlacement: string; | random_line_split |
tims.js | import {getTims} from '../api/api';
export function loadData() {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch... |
function getChildren(element, ...names) {
const res = {};
for (let i = 0; i < element.children.length; ++i) {
const name = element.children[i].nodeName.toLowerCase();
if (names.find(n => n === name)) {
res[name] = element.children[i];
}
}
return res;
}
function getChild(element, name) {
... | {
const res = {};
for (let i = 0; i < disruptions.children.length; ++i) {
const disr = disruptions.children[i];
const idAttr = getAttr(disr, 'id');
if (!idAttr || !idAttr.value) {
continue;
}
const props = {};
for (let j = 0; j < disr.children.length; ++j) {
const propElem = disr... | identifier_body |
tims.js | import {getTims} from '../api/api';
export function loadData() {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch... |
res[idAttr.value] = props;
}
return res;
}
function getChildren(element, ...names) {
const res = {};
for (let i = 0; i < element.children.length; ++i) {
const name = element.children[i].nodeName.toLowerCase();
if (names.find(n => n === name)) {
res[name] = element.children[i];
}
}
r... | {
const propElem = disr.children[j];
if (propElem.children.length === 0) {
props[propElem.nodeName] = propElem.textContent;
} else if (propElem.nodeName.toLowerCase() === 'causearea') {
const displayPoint = getChild(propElem, 'displaypoint');
if (displayPoint) {
const... | conditional_block |
tims.js | import {getTims} from '../api/api';
export function loadData() {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch... | const disr = disruptions.children[i];
const idAttr = getAttr(disr, 'id');
if (!idAttr || !idAttr.value) {
continue;
}
const props = {};
for (let j = 0; j < disr.children.length; ++j) {
const propElem = disr.children[j];
if (propElem.children.length === 0) {
props[propEl... |
function mapDisruptions(disruptions) {
const res = {};
for (let i = 0; i < disruptions.children.length; ++i) { | random_line_split |
tims.js | import {getTims} from '../api/api';
export function | () {
return getTims().then(data => {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/xml');
if (doc.documentElement.nodeName === 'parseerror') {
throw new Error(doc);
}
return toJSON(doc);
}).catch(e => {
console.error(e);
});
}
function toJSON(doc) {... | loadData | identifier_name |
required-attr.ts | "use strict";
import { Rule } from 'template-lint';
import { Parser } from 'template-lint';
import { Issue, IssueSeverity } from 'template-lint';
/**
* Rule to ensure elements have required attributes
*/
export class RequiredAttributeRule extends Rule {
patterns: Array<{ tag: RegExp, attr: RegExp, msg: string }>;... | }
});
}
}; | } | random_line_split |
required-attr.ts | "use strict";
import { Rule } from 'template-lint';
import { Parser } from 'template-lint';
import { Issue, IssueSeverity } from 'template-lint';
/**
* Rule to ensure elements have required attributes
*/
export class RequiredAttributeRule extends Rule {
patterns: Array<{ tag: RegExp, attr: RegExp, msg: string }>;... |
}
}
});
}
};
| {
let issue = new Issue({
message: rule.msg,
severity: IssueSeverity.Error,
line: loc.line,
column: loc.col,
start: loc.startOffset,
end: loc.endOffset
});
this.reportIssue(issue);
} | conditional_block |
required-attr.ts | "use strict";
import { Rule } from 'template-lint';
import { Parser } from 'template-lint';
import { Issue, IssueSeverity } from 'template-lint';
/**
* Rule to ensure elements have required attributes
*/
export class | extends Rule {
patterns: Array<{ tag: RegExp, attr: RegExp, msg: string }>;
constructor(patterns?: Array<{ tag: RegExp, attr: RegExp, msg: string }>) {
super();
this.patterns = patterns ? patterns : [];
}
init(parser: Parser) {
parser.on("startTag", (tag, attrs, selfClosing, loc) => {
let r... | RequiredAttributeRule | identifier_name |
pool.rs | use indy::IndyError;
use indy::pool;
use indy::future::Future;
use serde_json::to_string;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
const PROTOCOL_VERSION: usize = 2;
pub fn create_and_open_po... |
let mut f = fs::File::create(txn_file_path.as_path()).unwrap();
f.write_all(txn_file_data.as_bytes()).unwrap();
f.flush().unwrap();
f.sync_all().unwrap();
txn_file_path
}
fn _open_pool_ledger(pool_name: &str, config: Option<&str>) -> Result<i32, IndyError> {
pool::open_pool_ledger(pool_name,... | {
fs::DirBuilder::new()
.recursive(true)
.create(txn_file_path.parent().unwrap()).unwrap();
} | conditional_block |
pool.rs | use indy::IndyError;
use indy::pool;
use indy::future::Future;
use serde_json::to_string;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
const PROTOCOL_VERSION: usize = 2;
pub fn create_and_open_po... |
pub fn set_protocol_version(protocol_version: usize) -> Result<(), IndyError> {
pool::set_protocol_version(protocol_version).wait()
} | random_line_split | |
pool.rs | use indy::IndyError;
use indy::pool;
use indy::future::Future;
use serde_json::to_string;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
const PROTOCOL_VERSION: usize = 2;
pub fn create_and_open_po... |
pub fn close(pool_handle: i32) -> Result<(), IndyError> {
pool::close_pool_ledger(pool_handle).wait()
}
fn _pool_config_json(txn_file_path: &Path) -> String {
to_string(&PoolConfig {
genesis_txn: txn_file_path.to_string_lossy().to_string()
}).unwrap()
}
fn _create_pool_ledger_config(pool_name: &... | {
set_protocol_version(PROTOCOL_VERSION).unwrap();
let txn_file_path = _create_genesis_txn_file_for_test_pool(pool_name, None, None);
let pool_config = _pool_config_json(txn_file_path.as_path());
_create_pool_ledger_config(pool_name, Some(pool_config.as_str()))?;
_open_pool_ledger(pool_name, None)
} | identifier_body |
pool.rs | use indy::IndyError;
use indy::pool;
use indy::future::Future;
use serde_json::to_string;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
#[derive(Serialize, Deserialize)]
pub struct PoolConfig {
pub genesis_txn: String
}
const PROTOCOL_VERSION: usize = 2;
pub fn create_and_open_po... | (pool_name: &str, config: Option<&str>) -> Result<i32, IndyError> {
pool::open_pool_ledger(pool_name, config).wait()
}
pub fn set_protocol_version(protocol_version: usize) -> Result<(), IndyError> {
pool::set_protocol_version(protocol_version).wait()
} | _open_pool_ledger | identifier_name |
register_all_kernels.ts | /**
* @license
* Copyright 2020 Google Inc. 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 a... | registerKernel(kernelConfig);
} | ];
for (const kernelConfig of kernelConfigs) { | random_line_split |
Inputs.ts | import { Aliases, TriggerContainer, CanTrigger } from "inputwritr";
import { Section } from "./Section";
import { EightBittr } from "../EightBittr";
import { GameWindow } from "../types";
/**
* User input filtering and handling.
*/
export class Inputs<Game extends EightBittr> extends Section<Game> {
/**
* ... | (gameWindow: GameWindow) {
gameWindow.document.addEventListener("visibilitychange", () => {
switch (document.visibilityState) {
case "hidden":
this.game.frameTicker.pause();
return;
case "visible":
this.game... | initializeGlobalPipes | identifier_name |
Inputs.ts | import { Aliases, TriggerContainer, CanTrigger } from "inputwritr";
import { Section } from "./Section";
import { EightBittr } from "../EightBittr";
import { GameWindow } from "../types";
/**
* User input filtering and handling.
*/
export class Inputs<Game extends EightBittr> extends Section<Game> {
/**
* ... | }
});
}
} | return;
case "visible":
this.game.frameTicker.play();
return; | random_line_split |
hero-list.component.ts | // #docregion
import {Component, OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroService} from './hero.service';
@Component({
selector: 'hero-list',
template: `
<h3>Heroes:</h3>
<ul>
<li *ngFor="#hero of heroes">
{{ hero.name }}
</li>
</ul>
New Hero:
... |
// #enddocregion getHeroes
// #docregion addHero
addHero (name: string) {
if (!name) {return;}
this._heroService.addHero(name)
.subscribe(
hero => this.heroes.push(hero),
error => this.errorMessage = <any>error);
}
// #enddocregion... | {
this._heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
} | identifier_body |
hero-list.component.ts | // #docregion
import {Component, OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroService} from './hero.service';
@Component({
selector: 'hero-list',
template: `
<h3>Heroes:</h3>
<ul>
<li *ngFor="#hero of heroes">
{{ hero.name }}
</li>
</ul>
New Hero:
... |
this._heroService.addHero(name)
.subscribe(
hero => this.heroes.push(hero),
error => this.errorMessage = <any>error);
}
// #enddocregion addHero
// #enddocregion methods
}
// #enddocregion component
| {return;} | conditional_block |
hero-list.component.ts | // #docregion
import {Component, OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroService} from './hero.service';
@Component({
selector: 'hero-list',
template: `
<h3>Heroes:</h3>
<ul>
<li *ngFor="#hero of heroes">
{{ hero.name }}
</li>
</ul>
New Hero:
... | (name: string) {
if (!name) {return;}
this._heroService.addHero(name)
.subscribe(
hero => this.heroes.push(hero),
error => this.errorMessage = <any>error);
}
// #enddocregion addHero
// #enddocregion methods
}
// #enddocregion component... | addHero | identifier_name |
hero-list.component.ts | // #docregion
import {Component, OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroService} from './hero.service';
@Component({
selector: 'hero-list',
template: `
<h3>Heroes:</h3>
<ul>
<li *ngFor="#hero of heroes">
{{ hero.name }}
</li>
</ul>
New Hero:
... | getHeroes() {
this._heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
// #enddocregion getHeroes
// #docregion addHero
addHero (name: string) {
if (!name) {return;}
th... | // #docregion getHeroes | random_line_split |
module-handler.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | * It's recommended to return the class of the component, but you can also return an instance of the component.
*
* @param {Injector} injector Injector.
* @param {any} course The course object.
* @param {any} module The module object.
* @return {any|Promise<any>} The component (or promise r... | }
/**
* Get the component to render the module. This is needed to support singleactivity course format.
* The component returned must implement CoreCourseModuleMainComponent. | random_line_split |
module-handler.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | (module: any, courseId: number, sectionId: number): CoreCourseModuleHandlerData {
return {
icon: this.courseProvider.getModuleIconSrc(this.modName, module.modicon),
title: module.name,
class: 'addon-mod_book-handler',
showDownloadButton: true,
action(e... | getData | identifier_name |
module-handler.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... |
navCtrl.push('AddonModBookIndexPage', pageParams, options);
}
};
}
/**
* Get the component to render the module. This is needed to support singleactivity course format.
* The component returned must implement CoreCourseModuleMainComponent.
* It's recommended ... | {
Object.assign(pageParams, params);
} | conditional_block |
__init__.py | from flask import render_template, g, flash, redirect, url_for, request
from flask_peewee.utils import object_list
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from peewee import fn, JOIN
from apps.forms.others import TugasForm
from apps.models import KumpulTugas, Tugas, M... | return redirect(url_for('dosen:tugas:list'))
@dosen_required
def tugas_list():
tugass = (
Tugas.select(Tugas, fn.Count(KumpulTugas.id).alias('k_tugas_count'))
.join(KumpulTugas, JOIN.LEFT_OUTER, on=(KumpulTugas.tugas == Tugas.id))
.join(MataKuliah, on=(Tugas.mata_kuliah == MataKuliah.id))
.gro... |
@dosen_required
def home(): | random_line_split |
__init__.py | from flask import render_template, g, flash, redirect, url_for, request
from flask_peewee.utils import object_list
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from peewee import fn, JOIN
from apps.forms.others import TugasForm
from apps.models import KumpulTugas, Tugas, M... | (tugas_id):
tugas = Tugas.get(Tugas.id == tugas_id)
user = g.user
form = TugasForm(request.form, obj=tugas)
form.action = url_for('dosen:tugas:update', tugas_id=tugas_id)
matkul = MataKuliah.get(MataKuliah.dosen == user)
if form.validate_on_submit():
form.populate_obj(tugas)
tuga... | tugas_update | identifier_name |
__init__.py | from flask import render_template, g, flash, redirect, url_for, request
from flask_peewee.utils import object_list
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from peewee import fn, JOIN
from apps.forms.others import TugasForm
from apps.models import KumpulTugas, Tugas, M... |
return redirect(url_for('dosen:tugas:list'))
return render_template('dosen/tugas/list.html')
@dosen_required
def tugas_update(tugas_id):
tugas = Tugas.get(Tugas.id == tugas_id)
user = g.user
form = TugasForm(request.form, obj=tugas)
form.action = url_for('dosen:tugas:update', tugas_id=tug... | tugas.delete_instance(True)
flash('Sukses menghapus tugas') | conditional_block |
__init__.py | from flask import render_template, g, flash, redirect, url_for, request
from flask_peewee.utils import object_list
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from peewee import fn, JOIN
from apps.forms.others import TugasForm
from apps.models import KumpulTugas, Tugas, M... |
@dosen_required
def tugas_detail(tugas_id):
tugas = (Tugas.select(Tugas, KumpulTugas)
.join(KumpulTugas, JOIN.LEFT_OUTER,
on=(KumpulTugas.tugas == Tugas.id))
.where(Tugas.id == tugas_id)).get()
return render_template('dosen/tugas/detail.html', tugas=tugas)
| form = TugasForm(request.form)
if form.validate_on_submit():
tugas = Tugas()
form.populate_obj(tugas)
user = g.user
matkul = MataKuliah.get(MataKuliah.dosen == user)
tugas.mata_kuliah = matkul
tugas.save()
file_list = request.files.getlist('file_pendukung')
... | identifier_body |
escape.js | YUI.add('escape', function(Y) {
/**
Provides utility methods for escaping strings.
@module escape
@class Escape
@static
@since 3.3.0
**/
var HTML_CHARS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`'
},... | // -- Public Static Methods ------------------------------------------------
/**
Returns a copy of the specified string with special HTML characters
escaped. The following characters will be converted to their
corresponding character entities:
& < > " ' / `
This implementation is base... | Escape = { | random_line_split |
re.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl<'t> Replacer for |&Captures|: 't -> String {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> MaybeOwned<'a> {
Owned((*self)(caps))
}
}
/// Yields all substrings delimited by a regular expression match.
///
/// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
/// of... | {
Owned(caps.expand(*self))
} | identifier_body |
re.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&'t self) -> SubCapturesPos<'t> {
SubCapturesPos { idx: 0, caps: self, }
}
/// Expands all instances of `$name` in `text` to the corresponding capture
/// group `name`.
///
/// `name` may be an integer corresponding to the index of the
/// capture group (counted by order of opening par... | iter_pos | identifier_name |
re.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | /// assert_eq!(caps.at(2), "1941");
/// assert_eq!(caps.at(0), "'Citizen Kane' (1941)");
/// # }
/// ```
///
/// Note that the full match is at capture group `0`. Each subsequent
/// capture group is indexed by the order of its opening `(`.
///
/// We can make this example a bit clea... | /// assert_eq!(caps.at(1), "Citizen Kane"); | random_line_split |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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 i... |
#[test]
fn test_message_roundtrip() {
let keys = KeyPair::random();
let ts = Utc::now();
let msg = Verified::from_value(
Precommit::new(
ValidatorId(123),
Height(15),
Round(25),
crypto::hash(&[1, 2, 3]),
... | {
let keys = KeyPair::random();
let msg = SignedMessage::new(vec![], keys.public_key(), keys.secret_key());
assert_eq!(SIGNED_MESSAGE_MIN_SIZE, msg.into_bytes().len());
} | identifier_body |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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 i... | () {
let keys = KeyPair::random();
let ts = Utc::now();
let msg = Verified::from_value(
Precommit::new(
ValidatorId(123),
Height(15),
Round(25),
crypto::hash(&[1, 2, 3]),
crypto::hash(&[3, 2, 1]),
... | test_message_roundtrip | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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 i... | //!
//! 1. `Vec<u8>`: raw bytes as received from the network
//! 2. `SignedMessage`: integrity and the signature of the message has been verified
//! 3. `impl IntoMessage`: the message has been completely parsed
//!
//! Graphical representation of the message processing flow:
//!
//! ```text
//! +---------+ ... | //! Tools for messages authenticated with the Ed25519 public-key crypto system.
//! These messages are used by the P2P networking and for transaction authentication by external
//! clients.
//!
//! Every message passes through three phases: | random_line_split |
vmdebootstrap.py | #
# This file is part of Freedom Maker.
#
# 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, or
# (at your option) any later version.
#
# This program is distribute... |
def _cleanup_vmdebootstrap(self, image_file):
"""Cleanup those that vmdebootstrap is supposed to have cleaned up."""
# XXX: Remove this when vmdebootstrap removes kpartx mappings properly
# after a successful build.
process = subprocess.run(['/sbin/losetup', '--json'],
... | """Create a disk image."""
if self.builder.should_skip_step(self.builder.image_file):
logger.info('Image exists, skipping build - %s',
self.builder.image_file)
return
temp_image_file = self.builder.get_temp_image_file()
logger.info('Building image... | identifier_body |
vmdebootstrap.py | #
# This file is part of Freedom Maker.
#
# 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, or
# (at your option) any later version.
#
# This program is distribute... | (self):
"""Create a disk image."""
if self.builder.should_skip_step(self.builder.image_file):
logger.info('Image exists, skipping build - %s',
self.builder.image_file)
return
temp_image_file = self.builder.get_temp_image_file()
logger.info... | make_image | identifier_name |
vmdebootstrap.py | #
# This file is part of Freedom Maker.
#
# 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, or
# (at your option) any later version.
#
# This program is distribute... |
if not loop_device:
return
partition_devices = [
'/dev/mapper/' + loop_device.split('/')[-1] + 'p' + str(number)
for number in range(1, 4)
]
# Don't log command, ignore errors, force
for device in partition_devices:
subprocess.ru... | if image_file == device_data['back-file']:
loop_device = device_data['name']
break | conditional_block |
vmdebootstrap.py | #
# This file is part of Freedom Maker.
#
# 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, or
# (at your option) any later version.
#
# This program is distribute... | else:
self.parameters += ['--custom-package', package]
def process_environment(self):
"""Add environment we wish to pass to the command wrapper: sudo."""
for key, value in self.environment.items():
self.execution_wrapper += [key + '=' + value] | self.environment['CUSTOM_SETUP'] = package | random_line_split |
joueur.component.ts | import {Component, OnInit} from '@angular/core';
import {RequestService} from "../../services/request.service";
import {Config} from "../../config/config";
import {Joueur} from "../../services/joueur.service";
import {UtilsService} from "../../services/utils.service";
import {CacheService} from "../../services/cache.se... |
}
initCache() {
if(!this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.joueurs = this.cacheService.joueurs;
}
}
clearCache() {
this.cacheService.joueurs = null;
}
// Charge la liste des joueurs et les données qui sont liés
chargerJoueurs() {
this.requestService.lis... | {
this.utilsService.log("[CHARGEMENT] joueurs /joueurs");
this.chargerJoueurs();
} | conditional_block |
joueur.component.ts | import {Component, OnInit} from '@angular/core';
import {RequestService} from "../../services/request.service";
import {Config} from "../../config/config";
import {Joueur} from "../../services/joueur.service";
import {UtilsService} from "../../services/utils.service";
import {CacheService} from "../../services/cache.se... | () {
this.initCache();
if(this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.utilsService.log("[CHARGEMENT] joueurs /joueurs");
this.chargerJoueurs();
}
}
initCache() {
if(!this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.joueurs = this.cacheServic... | ngOnInit | identifier_name |
joueur.component.ts | import {Component, OnInit} from '@angular/core';
import {RequestService} from "../../services/request.service";
import {Config} from "../../config/config";
import {Joueur} from "../../services/joueur.service";
import {UtilsService} from "../../services/utils.service";
import {CacheService} from "../../services/cache.se... | }
ngOnInit() {
this.initCache();
if(this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.utilsService.log("[CHARGEMENT] joueurs /joueurs");
this.chargerJoueurs();
}
}
initCache() {
if(!this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.joueurs = t... | random_line_split | |
joueur.component.ts | import {Component, OnInit} from '@angular/core';
import {RequestService} from "../../services/request.service";
import {Config} from "../../config/config";
import {Joueur} from "../../services/joueur.service";
import {UtilsService} from "../../services/utils.service";
import {CacheService} from "../../services/cache.se... |
clearCache() {
this.cacheService.joueurs = null;
}
// Charge la liste des joueurs et les données qui sont liés
chargerJoueurs() {
this.requestService.listJoueur().subscribe((joueurs) => {
// Local value
this.joueurs = joueurs;
// Cache
this.cacheService.joueurs = joueurs;
... | {
if(!this.utilsService.isEmptyObject(this.cacheService.joueurs)){
this.joueurs = this.cacheService.joueurs;
}
} | identifier_body |
proximity.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Proximity (raster distance)')
self.group, self.i18n_group = self.trAlgorithm('[GDAL] Analysis')
self.addParameter(ParameterRaster(self.INPUT,
self.tr('Input layer'), False))
self.addParameter... | return "gdalogr:proximity" | identifier_body |
proximity.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... | NODATA = 'NODATA'
BUF_VAL = 'BUF_VAL'
OUTPUT = 'OUTPUT'
RTYPE = 'RTYPE'
TYPE = ['Byte', 'Int16', 'UInt16', 'UInt32', 'Int32', 'Float32', 'Float64']
DISTUNITS = ['GEO', 'PIXEL']
def commandLineName(self):
return "gdalogr:proximity"
def defineCharacteristics(self):
self... | UNITS = 'UNITS'
MAX_DIST = 'MAX_DIST' | random_line_split |
proximity.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... | (self):
self.name, self.i18n_name = self.trAlgorithm('Proximity (raster distance)')
self.group, self.i18n_group = self.trAlgorithm('[GDAL] Analysis')
self.addParameter(ParameterRaster(self.INPUT,
self.tr('Input layer'), False))
self.addParameter(ParameterString(self.VALUES,
... | defineCharacteristics | identifier_name |
proximity.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
commands = []
if isWindows():
commands = ['cmd.exe', '/C ', 'gdal_proximity.bat',
GdalUtils.escapeAndJoin(arguments)]
else:
commands = ['gdal_proximity.py',
GdalUtils.escapeAndJoin(arguments)]
return commands
| arguments.append('-fixed-buf-val')
arguments.append(values) | conditional_block |
forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.Emai... |
class ProgramForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProgramForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', _('Submit')))
class Meta:
model = Program
fields = ('slide_url', 'video_url', ... | def __init__(self, *args, **kwargs):
super(SpeakerForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', _('Submit')))
class Meta:
model = Speaker
fields = ('desc', 'info', )
widgets = {
'desc': SummernoteI... | identifier_body |
forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.Emai... | (self):
cleaned_data = super(EmailLoginForm, self).clean()
return cleaned_data
class SpeakerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SpeakerForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', _('Su... | clean | identifier_name |
forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = forms.Emai... | fields = ('slide_url', 'video_url', 'is_recordable', 'desc', )
widgets = {
'desc': SummernoteInplaceWidget(),
}
labels = {
'slide_url': _('Slide URL'),
'video_url': _('Video URL'),
'is_recordable': _('Photography and recording is allowed'),... | model = Program | random_line_split |
setJobState.ts | /**
* Set the Job state data
* @param {string} id - the job id
* @param {IState} state - the state document
*/
function setJobState(id: string, state: IState) {
| let context: IContext = getContext();
let collection: ICollection = context.getCollection();
let response: IResponse = getContext().getResponse();
let collectionLink: string = collection.getAltLink();
let documentLink: string = `${collectionLink}/docs/${id}`;
// default response
response.se... | identifier_body | |
setJobState.ts | /**
* Set the Job state data
* @param {string} id - the job id
* @param {IState} state - the state document
*/
function setJobState(id: string, state: IState) {
let context: IContext = getContext();
let collection: ICollection = context.getCollection();
let response: IResponse = getContext().getRespons... | throw new Error("The call was not accepted");
}
} | conditional_block | |
setJobState.ts | /**
* Set the Job state data
* @param {string} id - the job id
* @param {IState} state - the state document
*/
function se | d: string, state: IState) {
let context: IContext = getContext();
let collection: ICollection = context.getCollection();
let response: IResponse = getContext().getResponse();
let collectionLink: string = collection.getAltLink();
let documentLink: string = `${collectionLink}/docs/${id}`;
// defa... | tJobState(i | identifier_name |
setJobState.ts | /**
* Set the Job state data
* @param {string} id - the job id
* @param {IState} state - the state document
*/
function setJobState(id: string, state: IState) {
let context: IContext = getContext();
let collection: ICollection = context.getCollection(); | let response: IResponse = getContext().getResponse();
let collectionLink: string = collection.getAltLink();
let documentLink: string = `${collectionLink}/docs/${id}`;
// default response
response.setBody(false);
let isAccepted: boolean = collection.readDocument(documentLink, (error: IRequestCa... | random_line_split | |
Rate.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import { defaultProps, prefix, getUnhandledProps, withStyleProps } from '../utils';
import { transformValueToCharacterMap, transformCharacterMapToValue } from './utils';
imp... |
addPrefix = (name: string) => prefix(this.props.classPrefix)(name);
getValue() {
const { value } = this.props;
return typeof value === 'undefined' ? this.state.prevPropsValue : value;
}
getCharacterMap = (value: number) => {
const { max, allowHalf } = this.props;
return transformValueToCharac... | characterMap: this.getCharacterMap(prevPropsValue)
};
} | random_line_split |
Rate.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import { defaultProps, prefix, getUnhandledProps, withStyleProps } from '../utils';
import { transformValueToCharacterMap, transformCharacterMapToValue } from './utils';
imp... |
constructor(props) {
super(props);
const { value } = props;
const prevPropsValue = typeof value !== 'undefined' ? value : props.defaultValue;
this.state = {
prevPropsValue,
characterMap: this.getCharacterMap(prevPropsValue)
};
}
addPrefix = (name: string) => prefix(this.props.cl... | {
const { value, max, allowHalf } = nextProps;
const characterMap = transformValueToCharacterMap(value, max, allowHalf);
if (typeof value !== 'undefined' && value !== nextState.prevPropsValue) {
return { prevPropsValue: value, characterMap };
}
return null;
} | identifier_body |
Rate.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import { defaultProps, prefix, getUnhandledProps, withStyleProps } from '../utils';
import { transformValueToCharacterMap, transformCharacterMapToValue } from './utils';
imp... |
if (nextValue !== value) {
this.setState({ prevPropsValue: nextValue, characterMap: this.getCharacterMap(nextValue) });
onChange?.(nextValue, event);
}
};
handleKeyDown = (index: number, event: React.KeyboardEvent<HTMLElement>) => {
const { keyCode } = event;
const { max, allowHalf } ... | {
nextValue = 0;
} | conditional_block |
Rate.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import compose from 'recompose/compose';
import { defaultProps, prefix, getUnhandledProps, withStyleProps } from '../utils';
import { transformValueToCharacterMap, transformCharacterMapToValue } from './utils';
imp... | (nextProps: RateProps, nextState: RateState) {
const { value, max, allowHalf } = nextProps;
const characterMap = transformValueToCharacterMap(value, max, allowHalf);
if (typeof value !== 'undefined' && value !== nextState.prevPropsValue) {
return { prevPropsValue: value, characterMap };
}
retu... | getDerivedStateFromProps | identifier_name |
datacatalog_v1beta1_generated_data_catalog_test_iam_permissions_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
# [END datacatalog_v1beta1_generated_DataCatalog_TestIamPermissions_async]
| client = datacatalog_v1beta1.DataCatalogAsyncClient()
# Initialize request argument(s)
request = datacatalog_v1beta1.TestIamPermissionsRequest(
resource="resource_value",
permissions=['permissions_value_1', 'permissions_value_2'],
)
# Make the request
response = await client.test_i... | identifier_body |
datacatalog_v1beta1_generated_data_catalog_test_iam_permissions_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
async def sample_test_iam_permissions():
# Create a client
client = datacatalog_v1beta1.DataCatalogAsyncClient()
# Initialize request argument(s)
request = datacatalog_v1beta1.TestIamPermissionsRequest(
resource="resource_value",
permissions=['permissions_value_1', 'permissions_value_2... | random_line_split | |
datacatalog_v1beta1_generated_data_catalog_test_iam_permissions_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | ():
# Create a client
client = datacatalog_v1beta1.DataCatalogAsyncClient()
# Initialize request argument(s)
request = datacatalog_v1beta1.TestIamPermissionsRequest(
resource="resource_value",
permissions=['permissions_value_1', 'permissions_value_2'],
)
# Make the request
... | sample_test_iam_permissions | identifier_name |
workflow.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model import no_value_fields
class | (Document):
def validate(self):
self.set_active()
self.create_custom_field_for_workflow_state()
self.update_default_workflow_status()
self.validate_docstatus()
def on_update(self):
self.update_doc_status()
frappe.clear_cache(doctype=self.document_type)
frappe.cache().delete_key('workflow_' + self.name)... | Workflow | identifier_name |
workflow.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model import no_value_fields
class Workflow(Document):
def validate(self):
self.set_active()
self.create_custom_field_for_wor... |
def update_default_workflow_status(self):
docstatus_map = {}
states = self.get("states")
for d in states:
if not d.doc_status in docstatus_map:
frappe.db.sql("""
UPDATE `tab{doctype}`
SET `{field}` = %s
WHERE ifnull(`{field}`, '') = ''
AND `docstatus` = %s
""".format(doctype=self... | frappe.clear_cache(doctype=self.document_type)
meta = frappe.get_meta(self.document_type)
if not meta.get_field(self.workflow_state_field):
# create custom field
frappe.get_doc({
"doctype":"Custom Field",
"dt": self.document_type,
"__islocal": 1,
"fieldname": self.workflow_state_field,
"la... | identifier_body |
workflow.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
from frappe import _ | def validate(self):
self.set_active()
self.create_custom_field_for_workflow_state()
self.update_default_workflow_status()
self.validate_docstatus()
def on_update(self):
self.update_doc_status()
frappe.clear_cache(doctype=self.document_type)
frappe.cache().delete_key('workflow_' + self.name) # clear cac... |
from frappe.model.document import Document
from frappe.model import no_value_fields
class Workflow(Document): | random_line_split |
workflow.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model import no_value_fields
class Workflow(Document):
def validate(self):
self.set_active()
self.create_custom_field_for_wor... |
def validate_docstatus(self):
def get_state(state):
for s in self.states:
if s.state==state:
return s
frappe.throw(frappe._("{0} not a valid State").format(state))
for t in self.transitions:
state = get_state(t.state)
next_state = get_state(t.next_state)
if state.doc_status=="2":
f... | frappe.db.set_value(self.document_type, {
self.workflow_state_field: before_save_states[key].state
},
'docstatus',
new_states[key].doc_status,
update_modified = False) | conditional_block |
faIntersection.js | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'intersection';
var width = 384;
var height = 512;
var ligatures = [];
var unicode = 'f668';
var svgPathData = 'M166.74 33.62C69.96 46.04 0 133.11 0 230.68V464c0 8.84 7.16 16 16 16h64c8.84 0 16-7.16 16-16V224... | exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | random_line_split | |
test_refcounts.py | import unittest
import ctypes
import gc
MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__)
class RefcountTestCase(unittest.TestCase):
def test_1(self):
fro... |
self.assertEqual(grc(callback), 2)
cb = MyCallback(callback)
self.assertTrue(grc(callback) > 2)
result = f(-10, cb)
self.assertEqual(result, -18)
cb = None
gc.collect()
self.assertEqual(grc(callback), 2)
def test_refcount(self):
from sys... | return value | identifier_body |
test_refcounts.py | import unittest
import ctypes
import gc
MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__)
class | (unittest.TestCase):
def test_1(self):
from sys import getrefcount as grc
f = dll._testfunc_callback_i_if
f.restype = ctypes.c_int
f.argtypes = [ctypes.c_int, MyCallback]
def callback(value):
#print "called back with", value
return value
se... | RefcountTestCase | identifier_name |
test_refcounts.py | import unittest
import ctypes
import gc
MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__)
class RefcountTestCase(unittest.TestCase):
def test_1(self):
fro... | unittest.main() | conditional_block | |
test_refcounts.py | import unittest
import ctypes
import gc
MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong)
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__)
class RefcountTestCase(unittest.TestCase):
def test_1(self):
fro... | gc.collect()
self.assertEqual(grc(func), 2)
f = OtherCallback(func)
# the CFuncPtr instance holds atr least one refcount on func:
self.assertTrue(grc(func) > 2)
# create a cycle
f.cycle = f
del f
gc.collect()
self.assertEqual(grc(func),... | random_line_split | |
blockdev.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/.
// Code to handle a single block device.
use std::fs::OpenOptions;
use std::path::PathBuf;
use chrono::{DateTime, T... | (&self) -> Sectors {
let size = self.used.size();
assert_eq!(self.bda.dev_size(), size);
size
}
fn state(&self) -> BlockDevState {
// TODO: Implement support for other BlockDevStates
if self.used.used() > self.bda.size() {
BlockDevState::InUse
} else ... | size | identifier_name |
blockdev.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/.
// Code to handle a single block device.
use std::fs::OpenOptions;
use std::path::PathBuf;
use chrono::{DateTime, T... |
/// Set the user info on this blockdev.
/// The user_info may be None, which unsets user info.
/// Returns true if the user info was changed, otherwise false.
pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool {
set_blockdev_user_info!(self; user_info)
}
}
impl BlockDev for ... | {
self.bda.max_data_size()
} | identifier_body |
blockdev.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/.
// Code to handle a single block device.
use std::fs::OpenOptions;
use std::path::PathBuf;
use chrono::{DateTime, T... | }
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.