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
bn.js
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.lang['bn'] = { "dir": "ltr", "editor": "Rich Text Editor", "common": { "editorHelp": "Press ALT 0 for help", "browseServer": "ব্রাউজ স...
"alignTop": "উপর", "alignMiddle": "মধ্য", "alignBottom": "নীচে", "invalidValue": "Invalid value.", "invalidHeight": "Height must be a number.", "invalidWidth": "Width must be a number.", "invalidCssLength": "Value specified for the \"%1\" field must be a positive ...
"align": "এলাইন", "alignLeft": "বামে", "alignRight": "ডানে", "alignCenter": "মাঝখানে",
random_line_split
models.py
import logging from django.db.models import DateTimeField, Model, Manager from django.db.models.query import QuerySet from django.db.models.fields.related import \ OneToOneField, ManyToManyField, ManyToManyRel from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now from django...
(self): """Soft delete this object. """ _unset_related_objects_relations(self) self.deleted = now() self.save() return self def undelete(self): """Undelete this soft-deleted object. """ if self.deleted is not None: LOGGER.debug('S...
delete
identifier_name
models.py
import logging from django.db.models import DateTimeField, Model, Manager from django.db.models.query import QuerySet from django.db.models.fields.related import \ OneToOneField, ManyToManyField, ManyToManyRel from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now from django...
class SoftDeleteModel(Model): """Simply inherit this class to enable soft deletion on a model. """ class Meta: abstract = True objects = SoftDeleteManager() deleted = DateTimeField(verbose_name=_('deleted'), null=True, blank=True) def delete(self): """Soft delete this object. ...
"""Return ALL objects. """ return self._get_base_queryset()
random_line_split
models.py
import logging from django.db.models import DateTimeField, Model, Manager from django.db.models.query import QuerySet from django.db.models.fields.related import \ OneToOneField, ManyToManyField, ManyToManyRel from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now from django...
class SoftDeleteModel(Model): """Simply inherit this class to enable soft deletion on a model. """ class Meta: abstract = True objects = SoftDeleteManager() deleted = DateTimeField(verbose_name=_('deleted'), null=True, blank=True) def delete(self): """Soft delete this object...
"""Return ALL objects. """ return self._get_base_queryset()
identifier_body
models.py
import logging from django.db.models import DateTimeField, Model, Manager from django.db.models.query import QuerySet from django.db.models.fields.related import \ OneToOneField, ManyToManyField, ManyToManyRel from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now from django...
for related in obj._meta.get_all_related_objects(): # Unset related objects' relation rel_name = related.get_accessor_name() if related.one_to_one: # Handle one-to-one relations. try: related_object = getattr(obj, rel_name) except Object...
_unset_related_many_to_many(obj, field)
conditional_block
__init__.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 Intel # # Author: Shuangtai Tian <shuangtai.tian@intel.com> # # 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/licen...
plugin.NotificationBase): @staticmethod def get_targets(conf): """Return a sequence of oslo.messaging.Target defining the exchange and topics to be connected for this plugin. """ return [oslo.messaging.Target(topic=topic, exchange=conf.nova_c...
omputeNotificationBase(
identifier_name
__init__.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 Intel # # Author: Shuangtai Tian <shuangtai.tian@intel.com> # # 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/licen...
""Return a sequence of oslo.messaging.Target defining the exchange and topics to be connected for this plugin. """ return [oslo.messaging.Target(topic=topic, exchange=conf.nova_control_exchange) for topic in conf.notification_topics]
identifier_body
__init__.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 Intel # # Author: Shuangtai Tian <shuangtai.tian@intel.com> # # 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/licen...
cfg.CONF.register_opts(OPTS) class ComputeNotificationBase(plugin.NotificationBase): @staticmethod def get_targets(conf): """Return a sequence of oslo.messaging.Target defining the exchange and topics to be connected for this plugin. """ return [oslo.messaging.Target(topic=topi...
random_line_split
testapp_spec.js
/*global jasmine*/ var excludes = [ "map_events.html", "map_lazy_init.html", "map-lazy-load.html", "marker_with_dynamic_position.html", "marker_with_dynamic_address.html", "marker_with_info_window.html", "places-auto-complete.html" ]; function using(values, func)
describe('testapp directory', function() { 'use strict'; //var urls = ["aerial-rotate.html", "aerial-simple.html", "hello_map.html", "map_control.html"]; var files = require('fs').readdirSync(__dirname + "/../../testapp"); var urls = files.filter(function(filename) { return filename.match(/\.html$/) && e...
{ for (var i = 0, count = values.length; i < count; i++) { if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')'; } }
identifier_body
testapp_spec.js
/*global jasmine*/ var excludes = [ "map_events.html", "map_lazy_init.html", "map-lazy-load.html", "marker_with_dynamic_position.html", "marker_with_dynamic_address.html", "marker_with_info_window.html", "places-auto-complete.html" ];
if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')'; } } describe('testapp directory', function() { 'use strict'; //var urls ...
function using(values, func){ for (var i = 0, count = values.length; i < count; i++) {
random_line_split
testapp_spec.js
/*global jasmine*/ var excludes = [ "map_events.html", "map_lazy_init.html", "map-lazy-load.html", "marker_with_dynamic_position.html", "marker_with_dynamic_address.html", "marker_with_info_window.html", "places-auto-complete.html" ]; function
(values, func){ for (var i = 0, count = values.length; i < count; i++) { if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')'; } ...
using
identifier_name
testapp_spec.js
/*global jasmine*/ var excludes = [ "map_events.html", "map_lazy_init.html", "map-lazy-load.html", "marker_with_dynamic_position.html", "marker_with_dynamic_address.html", "marker_with_info_window.html", "places-auto-complete.html" ]; function using(values, func){ for (var i = 0, cou...
} describe('testapp directory', function() { 'use strict'; //var urls = ["aerial-rotate.html", "aerial-simple.html", "hello_map.html", "map_control.html"]; var files = require('fs').readdirSync(__dirname + "/../../testapp"); var urls = files.filter(function(filename) { return filename.match(/\.html$/) &&...
{ if (Object.prototype.toString.call(values[i]) !== '[object Array]') { values[i] = [values[i]]; } func.apply(this, values[i]); jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')'; }
conditional_block
home.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/debounceTime'; import { Observable } from 'rxjs'; import { DPostList } from '../services/post/post.dto'; import { select, Store } from '@ngrx/store'; import { IA...
implements OnInit, OnDestroy { postList$: Observable<DPostList>; authenticated$: Observable<boolean>; websocketConnected$: Observable<boolean>; page: number; hashtags = [ { name: 'eve', posts: 3415, }, { name: 'mining', posts: 1482, }, { name: 'isk', ...
HomeComponent
identifier_name
home.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/debounceTime'; import { Observable } from 'rxjs'; import { DPostList } from '../services/post/post.dto'; import { select, Store } from '@ngrx/store'; import { IA...
ngOnDestroy() { this.websocketConnected$.pipe( filter(connected => connected) ).subscribe(() => { this.store.dispatch(new UnSubscribeFromLatestWall()); }); } ngOnInit() { this.page = 0; this.authenticated$.pipe( filter(authenticated => authenticated) ).subscribe(() =>...
{ this.postList$ = this.store.pipe(select('post', 'list', 'latest')); this.authenticated$ = this.store.pipe(select('authentication', 'authenticated')); this.websocketConnected$ = this.store.pipe(select('websocket', 'connected')) }
identifier_body
home.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/debounceTime'; import { Observable } from 'rxjs'; import { DPostList } from '../services/post/post.dto'; import { select, Store } from '@ngrx/store'; import { IA...
websocketConnected$: Observable<boolean>; page: number; hashtags = [ { name: 'eve', posts: 3415, }, { name: 'mining', posts: 1482, }, { name: 'isk', posts: 1023, }, { name: 'test', posts: 939, }, { name: 'bees', post...
authenticated$: Observable<boolean>;
random_line_split
toPromise-spec.ts
/** @prettier */ import { expect } from 'chai'; import { of, EMPTY, throwError, config } from 'rxjs'; /** @test {toPromise} */ describe('Observable.toPromise', () => { it('should convert an Observable to a promise of its last value', (done) => { of(1, 2, 3) .toPromise(Promise) .then((x) => { ...
done(); }); }); it('should handle errors properly', (done) => { throwError(() => 'bad') .toPromise(Promise) .then( () => { done(new Error('should not be called')); }, (err: any) => { expect(err).to.equal('bad'); done(); } ...
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::...
}
{ let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); let client = Client::new(rocket).unwrap(); assert_path(&client, "/first/some/path"); assert_path(&client, "/second/some/path"); assert_path(&client, "/firs...
identifier_body
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route;
fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::local::Client; fn assert_path(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_stri...
#[get("/<path..>")]
random_line_split
route_guard.rs
#![feature(plugin, custom_derive)] #![plugin(rocket_codegen)] extern crate rocket; use std::path::PathBuf; use rocket::Route; #[get("/<path..>")] fn files(route: &Route, path: PathBuf) -> String { format!("{}/{}", route.base(), path.to_string_lossy()) } mod route_guard_tests { use super::*; use rocket::...
(client: &Client, path: &str) { let mut res = client.get(path).dispatch(); assert_eq!(res.body_string(), Some(path.into())); } #[test] fn check_mount_path() { let rocket = rocket::ignite() .mount("/first", routes![files]) .mount("/second", routes![files]); ...
assert_path
identifier_name
index.tsx
/** * Copyright 2019 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 applicable law ...
(index: number) { const path = this.props.path === '/' ? '' : this.props.path; fetchJSON('/admin/patch', { method: 'PATCH', body: [ { op: 'replace', path: `/results${path}/winningIndex`, value: index, }, ], }); } private _onWinnerSelect =...
_setWinner
identifier_name
index.tsx
/** * Copyright 2019 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 applicable law ...
private _onWinnerSelect = (event: Event) => { const el = event.currentTarget as HTMLSelectElement; const container = el.closest('.admin-form-item') as HTMLElement; this._setWinner(Number(container.dataset.itemIndex)); }; private _onShowSlides = (event: Event) => { const el = event.currentTarget...
{ const path = this.props.path === '/' ? '' : this.props.path; fetchJSON('/admin/patch', { method: 'PATCH', body: [ { op: 'replace', path: `/results${path}/winningIndex`, value: index, }, ], }); }
identifier_body
index.tsx
/** * Copyright 2019 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 applicable law ...
else { const parentPath = this.props.path .split('/items/') .slice(1) .join('-'); toHighlight = [parentPath, parentPath + '-0', parentPath + '-1']; } fetchJSON('/admin/patch', { method: 'PATCH', body: [ { op: 'replace', path: `/brack...
{ toHighlight = ['0', '1']; }
conditional_block
index.tsx
/** * Copyright 2019 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 applicable law ...
.split('/items/') .slice(1) .join('-'); toHighlight = [parentPath, parentPath + '-0', parentPath + '-1']; } fetchJSON('/admin/patch', { method: 'PATCH', body: [ { op: 'replace', path: `/bracketZoom`, value: toHighlight, },...
if (this.props.path === '/') { toHighlight = ['0', '1']; } else { const parentPath = this.props.path
random_line_split
FileScanner.py
# scan a set of file from __future__ import print_function import os import fnmatch import tempfile from ScanFile import ScanFile class FileScanner: def __init__(self, handler=None, ignore_filters=None, scanners=None, error_handler=None, ram_bytes=10 * 1024 * 1024, skip_handler=None...
def error_handler(scan_file, error): print("FAILED:", scan_file, error) raise error fs = FileScanner(handler, ignore_filters=ifs, error_handler=error_handler) for a in sys.argv[1:]: fs.scan(a)
print(scan_file) return True
identifier_body
FileScanner.py
# scan a set of file from __future__ import print_function import os import fnmatch import tempfile from ScanFile import ScanFile class FileScanner: def __init__(self, handler=None, ignore_filters=None, scanners=None, error_handler=None, ram_bytes=10 * 1024 * 1024, skip_handler=None...
fs = FileScanner(handler, ignore_filters=ifs, error_handler=error_handler) for a in sys.argv[1:]: fs.scan(a)
random_line_split
FileScanner.py
# scan a set of file from __future__ import print_function import os import fnmatch import tempfile from ScanFile import ScanFile class FileScanner: def __init__(self, handler=None, ignore_filters=None, scanners=None, error_handler=None, ram_bytes=10 * 1024 * 1024, skip_handler=None...
return True def _scan_file(self, path): if self._is_ignored(path): return True # build a scan file try: size = os.path.getsize(path) with open(path, "rb") as fobj: sf = ScanFile(path, fobj, size, True, True) return self.scan_obj(sf, False) except IOError as e: ...
for name in files: if not self._scan_file(os.path.join(root,name)): return False for name in dirs: if not self._scan_dir(os.path.join(root,name)): return False
conditional_block
FileScanner.py
# scan a set of file from __future__ import print_function import os import fnmatch import tempfile from ScanFile import ScanFile class FileScanner: def __init__(self, handler=None, ignore_filters=None, scanners=None, error_handler=None, ram_bytes=10 * 1024 * 1024, skip_handler=None...
(self, scan_file, seekable=False, file_based=False): if not seekable and not file_base: return scan_file fb = file_based if not fb and seekable and scan_file.size > self.ram_bytes: fb = True sf = scan_file.create_clone(seekable, fb) scan_file.close() return sf # mini test if __name...
promote_scan_file
identifier_name
rcvr-borrowed-to-region.rs
// Copyright 2012 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!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
pub fn main() { let x = @mut 6; let y = x.get();
random_line_split
rcvr-borrowed-to-region.rs
// Copyright 2012 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 ...
{ let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); }
identifier_body
rcvr-borrowed-to-region.rs
// Copyright 2012 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 ...
(self) -> int { return *self; } } pub fn main() { let x = @mut 6; let y = x.get(); assert_eq!(y, 6); let x = @6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = ~6; let y = x.get(); info2!("y={}", y); assert_eq!(y, 6); let x = &6; let y =...
get
identifier_name
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &st...
) } }
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("{}", op) }; let repr: ~[~str] = ops.iter().map(display).collect(); f.buf.write(format!("{}", repr.concat()).as_bytes()
random_line_split
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct Ast(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &st...
} impl FromStr for Ast { fn from_str(source: &str) -> Option<Ast> { Ast::parse_str(source).ok() } } impl fmt::Show for Ast { /** Parses a string into the matching operator. */ fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result { let &Ast(ref ops) = self; let display = |op: &Operator| -> ~str { format!("...
{ /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, we push the previous one onto a stack. After the nest has been collected, we pop the context and replace it with the subprocess operator. */ let mut stack:~[ ~[Operator] ]...
identifier_body
ast.rs
use std::fmt; use std::from_str::FromStr; use operators::{Operator, Sub, Skip, Loop}; /** The internal parsed representation of a program source. */ pub struct
(~[Operator]); impl Ast { /** Produce an AST from a source string. This is the most commod method to generate an Ast. */ pub fn parse_str(source: &str) -> Result<Ast, ~str> { /* We parse loops by making a context to group its operators, pushing on it until the matching loop end. As we create the context, ...
Ast
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
(scale: &Scale, value: f32) -> f32 { match scale { &Scale::Linear{min, max} => { if value < min { 0. } else if value > max { 1. } else { (value - min) / (max - min) } }, &Scale::Log{min, max} => {...
normalize
identifier_name
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
, } }
{ value }
conditional_block
scale.rs
/// Enum that describes how the /// transcription from a value to a color is done. pub enum Scale { /// Linearly translate a value range to a color range Linear { min: f32, max: f32}, /// Log (ish) translation from a value range to a color range Log { min: f32, max: f32}, /// Exponantial (ish) trans...
} }
}, &Scale::Equal => { value },
random_line_split
RESOURCE_TYPES.ts
import indexById from 'common/indexById'; import { ClassResources } from 'parser/core/Events'; export interface Resource { id: number; name: string; icon: string; url: string; } const RESOURCE_TYPES: { [key: string]: Resource } = { MANA: { // Paladin, Priest, Shaman, Mage, Warlock, Monk, Druid id: 0...
return classResources.find((resource) => resource.type === type); }
{ return undefined; }
conditional_block
RESOURCE_TYPES.ts
import indexById from 'common/indexById'; import { ClassResources } from 'parser/core/Events'; export interface Resource { id: number; name: string; icon: string; url: string; } const RESOURCE_TYPES: { [key: string]: Resource } = { MANA: { // Paladin, Priest, Shaman, Mage, Warlock, Monk, Druid id: 0...
{ if (!classResources) { return undefined; } return classResources.find((resource) => resource.type === type); }
identifier_body
RESOURCE_TYPES.ts
import indexById from 'common/indexById'; import { ClassResources } from 'parser/core/Events'; export interface Resource { id: number; name: string; icon: string; url: string; } const RESOURCE_TYPES: { [key: string]: Resource } = { MANA: { // Paladin, Priest, Shaman, Mage, Warlock, Monk, Druid id: 0...
(classResources: ClassResources[] | undefined, type: number) { if (!classResources) { return undefined; } return classResources.find((resource) => resource.type === type); }
getResource
identifier_name
RESOURCE_TYPES.ts
import indexById from 'common/indexById'; import { ClassResources } from 'parser/core/Events'; export interface Resource { id: number; name: string; icon: string; url: string; } const RESOURCE_TYPES: { [key: string]: Resource } = { MANA: { // Paladin, Priest, Shaman, Mage, Warlock, Monk, Druid id: 0...
MAELSTROM: { // Shaman id: 11, name: 'Maelstrom', icon: 'spell_fire_masterofelements', url: 'maelstrom', }, CHI: { // Monk id: 12, name: 'Chi', icon: 'ability_monk_healthsphere', url: 'chi', }, INSANITY: { // Priest id: 13, name: 'Insanity', icon: 'spell...
},
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""xgc is an X11 graphics demo that shows various features of the X11 core protocol graphics primitives.""" homepage = "http://cgit.freedesktop.org/xorg/app/xgc" url = "https://www.x.org/archive/individual/app/xgc-1.0.5.tar.gz" version('1.0.5', '605557a9c138f6dc848c87a21bc7c7fc') depends_on(...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(AutotoolsPackage): """xgc is an X11 graphics demo that shows various features of the X11 core protocol graphics primitives.""" homepage = "http://cgit.freedesktop.org/xorg/app/xgc" url = "https://www.x.org/archive/individual/app/xgc-1.0.5.tar.gz" version('1.0.5', '605557a9c138f6dc848c87a21bc...
Xgc
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program 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 PU...
random_line_split
__init__.py
# -*- Mode: Python; py-indent-offset: 4 -*- # pygobject - Python bindings for the GObject library # Copyright (C) 2006-2012 Johan Dahlin # # glib/__init__.py: initialisation file for glib module # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
SPAWN_STDERR_TO_DEV_NULL = _glib.SPAWN_STDERR_TO_DEV_NULL SPAWN_STDOUT_TO_DEV_NULL = _glib.SPAWN_STDOUT_TO_DEV_NULL USER_DIRECTORY_DESKTOP = _glib.USER_DIRECTORY_DESKTOP USER_DIRECTORY_DOCUMENTS = _glib.USER_DIRECTORY_DOCUMENTS USER_DIRECTORY_DOWNLOAD = _glib.USER_DIRECTORY_DOWNLOAD USER_DIRECTORY_MUSIC = _glib.USER_DI...
SPAWN_DO_NOT_REAP_CHILD = _glib.SPAWN_DO_NOT_REAP_CHILD SPAWN_FILE_AND_ARGV_ZERO = _glib.SPAWN_FILE_AND_ARGV_ZERO SPAWN_LEAVE_DESCRIPTORS_OPEN = _glib.SPAWN_LEAVE_DESCRIPTORS_OPEN SPAWN_SEARCH_PATH = _glib.SPAWN_SEARCH_PATH
random_line_split
macRes.py
""" Tools for reading Mac resource forks. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import struct from fontTools.misc import sstruct from collections import OrderedDict try: from collections.abc import MutableMapping except ImportError: from UserDict import...
@staticmethod def openResourceFork(path): with open(path + '/..namedfork/rsrc', 'rb') as resfork: data = resfork.read() infile = BytesIO(data) infile.name = path return infile @staticmethod def openDataFork(path): with open(path, 'rb') as datafork: data = datafork.read() infile = BytesIO(data) ...
self._resources = OrderedDict() if hasattr(fileOrPath, 'read'): self.file = fileOrPath else: try: # try reading from the resource fork (only works on OS X) self.file = self.openResourceFork(fileOrPath) self._readFile() return except (ResourceError, IOError): # if it fails, use the data ...
identifier_body
macRes.py
""" Tools for reading Mac resource forks. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import struct from fontTools.misc import sstruct from collections import OrderedDict try: from collections.abc import MutableMapping except ImportError: from UserDict import...
raise ResourceError('Failed to seek offset (reached EOF)') try: data = self.file.read(numBytes) except OverflowError: raise ResourceError("Cannot read resource ('numBytes' is too large)") if len(data) != numBytes: raise ResourceError('Cannot read resource (not enough data)') return data def _read...
random_line_split
macRes.py
""" Tools for reading Mac resource forks. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import struct from fontTools.misc import sstruct from collections import OrderedDict try: from collections.abc import MutableMapping except ImportError: from UserDict import...
else: try: # try reading from the resource fork (only works on OS X) self.file = self.openResourceFork(fileOrPath) self._readFile() return except (ResourceError, IOError): # if it fails, use the data fork self.file = self.openDataFork(fileOrPath) self._readFile() @staticmethod def ...
self.file = fileOrPath
conditional_block
macRes.py
""" Tools for reading Mac resource forks. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import struct from fontTools.misc import sstruct from collections import OrderedDict try: from collections.abc import MutableMapping except ImportError: from UserDict import...
(self): if not self.file.closed: self.file.close() class Resource(object): def __init__(self, resType=None, resData=None, resID=None, resName=None, resAttr=None): self.type = resType self.data = resData self.id = resID self.name = resName self.attr = resAttr def decompile(self, refData, rea...
close
identifier_name
pages.tsx
import Layout from 'components/layout'; import {Table} from 'components/table'; import * as API from 'lib/api'; import * as Page from 'lib/page'; import * as React from 'react'; import {Link} from 'react-router-dom'; interface State { pages: API.Page[]; viewOption: API.ListPageRequest_ListPageFilter; loading: bo...
else { status = <div className="label label--gray small">draft</div>; klass = 'page--draft'; } return ( <Link key={page.uuid} className="tr tr--center" to={`/pages/${page.uuid}`}> <div className={`tr__expand ${klass}`}>{page.title || 'u...
{ status = <div className="label small">published</div>; }
conditional_block
pages.tsx
import Layout from 'components/layout'; import {Table} from 'components/table'; import * as API from 'lib/api'; import * as Page from 'lib/page'; import * as React from 'react'; import {Link} from 'react-router-dom'; interface State { pages: API.Page[]; viewOption: API.ListPageRequest_ListPageFilter; loading: bo...
(props: any) { super(props); this.state = { pages: [], loading: true, viewOption: 'all', }; } componentDidMount() { this.fetch(this.state.viewOption); } fetch = (val: API.ListPageRequest_ListPageFilter) => { return Page.list(val).then((pages) => { this.setState({ ...
constructor
identifier_name
pages.tsx
import Layout from 'components/layout'; import {Table} from 'components/table'; import * as API from 'lib/api'; import * as Page from 'lib/page'; import * as React from 'react'; import {Link} from 'react-router-dom'; interface State { pages: API.Page[]; viewOption: API.ListPageRequest_ListPageFilter; loading: bo...
</span> ); }; return ( <Layout className="pages"> <header> <Link className="button button--green button--center" to="/compose"> Compose </Link> <h1>Pages</h1> </header> <h2 className="tabs"> {tab('all')} <...
{ let tab = (v: API.ListPageRequest_ListPageFilter, desc?: string) => { let classes = 'tab-el'; if (this.state.viewOption == v) { classes += ' tab-selected'; } return ( <span className={classes} onClick={() => this.fetch(v)}> {desc || v}
identifier_body
pages.tsx
import Layout from 'components/layout'; import {Table} from 'components/table'; import * as API from 'lib/api'; import * as Page from 'lib/page'; import * as React from 'react'; import {Link} from 'react-router-dom'; interface State { pages: API.Page[]; viewOption: API.ListPageRequest_ListPageFilter; loading: bo...
}
</Table> </Layout> ); }
random_line_split
1395_count-number-of-teams.py
# 1395. Count Number of Teams - LeetCode # https://leetcode.com/problems/count-number-of-teams/ from typing import List # 暴力搜索都 AC 了 # 其实有两次筛选的算法 class Solution: def numTeams(self, rating: List[int]) -> int: if len(rating) <= 2:
= [1,2,3,4] s = Solution() ret = s.numTeams(rating) print(ret)
return 0 count = 0 for i in range(len(rating)): for j in range(i+1,len(rating)): for k in range(j+1,len(rating)): if rating[i] < rating[j] and rating[j] < rating[k]: count += 1 if rating[i] > rating[j] and ratin...
identifier_body
1395_count-number-of-teams.py
# 1395. Count Number of Teams - LeetCode # https://leetcode.com/problems/count-number-of-teams/ from typing import List
# 其实有两次筛选的算法 class Solution: def numTeams(self, rating: List[int]) -> int: if len(rating) <= 2: return 0 count = 0 for i in range(len(rating)): for j in range(i+1,len(rating)): for k in range(j+1,len(rating)): if rating[i] < rating...
# 暴力搜索都 AC 了
random_line_split
1395_count-number-of-teams.py
# 1395. Count Number of Teams - LeetCode # https://leetcode.com/problems/count-number-of-teams/ from typing import List # 暴力搜索都 AC 了 # 其实有两次筛选的算法 class Solution: def numTeams(self, rating: List[int]
: if len(rating) <= 2: return 0 count = 0 for i in range(len(rating)): for j in range(i+1,len(rating)): for k in range(j+1,len(rating)): if rating[i] < rating[j] and rating[j] < rating[k]: count += 1 ...
) -> int
identifier_name
1395_count-number-of-teams.py
# 1395. Count Number of Teams - LeetCode # https://leetcode.com/problems/count-number-of-teams/ from typing import List # 暴力搜索都 AC 了 # 其实有两次筛选的算法 class Solution: def numTeams(self, rating: List[int]) -> int: if len(rating) <= 2: return 0 count = 0 for i in range(len(rating)): ...
= [2,5,3,4,1] rating = [1,2,3,4] s = Solution() ret = s.numTeams(rating) print(ret)
# rating
conditional_block
forms.py
from django import forms from order.models import Pizza, Bread, Customer class PizzaForm(forms.ModelForm): class Meta: model = Pizza fields = ('size', 'toppings', 'crust') widgets = { 'size': forms.RadioSelect(), 'crust': forms.RadioSelect(), 'toppings': forms.C...
pizza.save() order.pizzas.add(pizza) order.save() class BreadForm(forms.ModelForm): class Meta: model = Bread fields = ('flavor',) widgets = { 'type': forms.RadioSelect(), } def process(self, order): data = self.cleaned_data flavor = data...
pizza.toppings.add(topping)
conditional_block
forms.py
from django import forms from order.models import Pizza, Bread, Customer class PizzaForm(forms.ModelForm): class Meta: model = Pizza
fields = ('size', 'toppings', 'crust') widgets = { 'size': forms.RadioSelect(), 'crust': forms.RadioSelect(), 'toppings': forms.CheckboxSelectMultiple(), } def process(self, order): data = self.cleaned_data size = data['size'] crust = data['crus...
random_line_split
forms.py
from django import forms from order.models import Pizza, Bread, Customer class PizzaForm(forms.ModelForm): class Meta: model = Pizza fields = ('size', 'toppings', 'crust') widgets = { 'size': forms.RadioSelect(), 'crust': forms.RadioSelect(), 'toppings': forms.C...
data = self.cleaned_data name = str(data['name']) number = str(data['number']) customer = Customer.objects.create(name=name, number=number) order.customer = customer order.save()
identifier_body
forms.py
from django import forms from order.models import Pizza, Bread, Customer class PizzaForm(forms.ModelForm): class Meta: model = Pizza fields = ('size', 'toppings', 'crust') widgets = { 'size': forms.RadioSelect(), 'crust': forms.RadioSelect(), 'toppings': forms.C...
(forms.ModelForm): class Meta: model = Customer def process(self, order): data = self.cleaned_data name = str(data['name']) number = str(data['number']) customer = Customer.objects.create(name=name, number=number) order.customer = customer order.save()
CustomerForm
identifier_name
url_mappings.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os class URLMappings(object): def __init__(self, src_root, build_dir):
@property def as_args(self): return map(lambda item: '--url-mapping=%s,%s' % item, self.mappings.items())
self.mappings = { 'dart:mojo.internal': os.path.join(src_root, 'mojo/public/dart/sdk_ext/internal.dart'), 'dart:sky': os.path.join(build_dir, 'gen/sky/bindings/dart_sky.dart'), 'dart:sky.internals': os.path.join(src_root, 'sky/engine/bindings/sky_internals.dart'), 'dart:s...
identifier_body
url_mappings.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os class URLMappings(object): def
(self, src_root, build_dir): self.mappings = { 'dart:mojo.internal': os.path.join(src_root, 'mojo/public/dart/sdk_ext/internal.dart'), 'dart:sky': os.path.join(build_dir, 'gen/sky/bindings/dart_sky.dart'), 'dart:sky.internals': os.path.join(src_root, 'sky/engine/bindings/sky_...
__init__
identifier_name
url_mappings.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os class URLMappings(object): def __init__(self, src_root, build_dir): self.mappings = { 'dart:mojo.internal': os.path.join(s...
def as_args(self): return map(lambda item: '--url-mapping=%s,%s' % item, self.mappings.items())
random_line_split
res_company.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ class
(models.Model): _inherit = "res.company" @api.model def create(self, vals): new_company = super(ResCompany, self).create(vals) ProductPricelist = self.env['product.pricelist'] pricelist = ProductPricelist.search([('currency_id', '=', new_company.currency_id.id), ('company_id', '=', ...
ResCompany
identifier_name
res_company.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ class ResCompany(models.Model): _inherit = "res.company" @api.model def create(self, vals): new_company = super(ResCompany, self).create(vals) ProductPriceli...
field_id = self.env['ir.model.fields'].search([('model', '=', 'res.partner'), ('name', '=', 'property_product_pricelist')]) self.env['ir.property'].create({ 'name': 'property_product_pricelist', 'company_id': new_company.id, 'value_reference': 'product.pricelist,%s' ...
pricelist = ProductPricelist.create({ 'name': new_company.name, 'currency_id': new_company.currency_id.id, })
conditional_block
res_company.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ class ResCompany(models.Model): _inherit = "res.company" @api.model def create(self, vals):
new_company = super(ResCompany, self).create(vals) ProductPricelist = self.env['product.pricelist'] pricelist = ProductPricelist.search([('currency_id', '=', new_company.currency_id.id), ('company_id', '=', False)], limit=1) if not pricelist: pricelist = ProductPricelist.create({ ...
identifier_body
res_company.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _
@api.model def create(self, vals): new_company = super(ResCompany, self).create(vals) ProductPricelist = self.env['product.pricelist'] pricelist = ProductPricelist.search([('currency_id', '=', new_company.currency_id.id), ('company_id', '=', False)], limit=1) if not pricelist: ...
class ResCompany(models.Model): _inherit = "res.company"
random_line_split
fs.rs
// Copyright 2013-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-MI...
// times are in milliseconds (currently) fn mktime(&self, secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 } } impl AsInner<raw::stat> for FileAttr { fn as_inner(&self) -> &raw::stat { &self.stat } } #[unstable(feature = "metadata_ext", reason = "recently added API")] pub trait ...
{ &self.stat }
identifier_body
fs.rs
// Copyright 2013-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-MI...
(&mut self, create: bool) { self.flag(libc::O_CREAT, create); } pub fn mode(&mut self, mode: raw::mode_t) { self.mode = mode as mode_t; } fn flag(&mut self, bit: c_int, on: bool) { if on { self.flags |= bit; } else { self.flags &= !bit; }...
create
identifier_name
fs.rs
// Copyright 2013-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-MI...
let entry = DirEntry { buf: buf, root: self.root.clone() }; if entry.name_bytes() == b"." || entry.name_bytes() == b".." { buf = entry.buf; } else { return Some(Ok(entry)) } } } } i...
{ return None }
conditional_block
fs.rs
// Copyright 2013-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-MI...
pub fn path(&self) -> PathBuf { self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes())) } pub fn file_name(&self) -> OsString { OsStr::from_bytes(self.name_bytes()).to_os_string() } pub fn metadata(&self) -> io::Result<FileAttr> { lstat(&self.path()) } p...
} } impl DirEntry {
random_line_split
mod.rs
// Copyright 2013 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 ...
match action(addr) { Ok(r) => return Ok(r), Err(e) => err = e } } Err(err) }
for addr in addresses.into_iter() {
random_line_split
_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date:...
# commit: short hex revision ID
random_line_split
_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # e...
"""Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces...
identifier_body
_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] ...
render_pep440_old
identifier_name
_version.py
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains t...
# no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date"...
r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date}
conditional_block
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
<'a, G: Rng + ?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(feature = "arbitrary")] impl<N: Scalar + Arbitrary, D: DimName> Arbitrary for Translation<N, D> where DefaultAllocator: Allocator<N, D>, Owned<N, D>: Send, { #[inline] ...
sample
identifier_name
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")]
use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimName, U1, U2, U3, U4, U5, U6}; use crate::base::{DefaultAllocator, Scalar, VectorN}; use crate::geometry::Translation; impl<N: Scalar + Zero, D: DimName> Translation<N, D> where DefaultAllocator: Allocator<N, D>...
use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng;
random_line_split
translation_construction.rs
#[cfg(feature = "arbitrary")] use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; use rand::distributions::{Distribution, Standard}; use rand::Rng; use simba::scalar::ClosedAdd; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
} impl<N: Scalar, D: DimName> Distribution<Translation<N, D>> for Standard where DefaultAllocator: Allocator<N, D>, Standard: Distribution<N>, { #[inline] fn sample<'a, G: Rng + ?Sized>(&self, rng: &'a mut G) -> Translation<N, D> { Translation::from(rng.gen::<VectorN<N, D>>()) } } #[cfg(f...
{ Self::identity() }
identifier_body
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}...
{} #[repr(C)] #[derive(Clone, Copy)] pub struct cubeb_stream_params { pub format: cubeb_sample_format, pub rate: c_uint, pub channels: c_uint, pub layout: cubeb_channel_layout, pub prefs: cubeb_stream_prefs, } impl Default for cubeb_stream_params { fn default() -> Self { unsafe { mem::...
ubeb_stream
identifier_name
stream.rs
// Copyright © 2017-2018 Mozilla Foundation // // This program is made available under an ISC-style license. See the // accompanying file LICENSE for details. use callbacks::cubeb_device_changed_callback; use channel::cubeb_channel_layout; use device::cubeb_device; use format::cubeb_sample_format; use std::{fmt, mem}...
CUBEB_STREAM_PREF_NONE = 0x00, CUBEB_STREAM_PREF_LOOPBACK = 0x01, CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING = 0x02, CUBEB_STREAM_PREF_VOICE = 0x04, } } cubeb_enum! { pub enum cubeb_state { CUBEB_STATE_STARTED, CUBEB_STATE_STOPPED, CUBEB_STATE_DRAINED, ...
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
} }
{ let mut mod_file = File::create(mod_file_str).unwrap(); mod_file.write(MOD_FILE.as_bytes()).unwrap(); }
conditional_block
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata};
use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] mod bindings; "#; fn ma...
use std::path::Path;
random_line_split
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() .header(HEADER_BASE.to_string() + header + ".h") .link("mb...
{ for header in HEADERS.iter() { gen(header); } }
identifier_body
build.rs
extern crate bindgen; use std::fs::{File, create_dir_all, metadata}; use std::path::Path; use std::io::{ErrorKind, Write}; const HEADERS : &'static [&'static str] = &["ssl", "entropy", "ctr_drbg"]; const HEADER_BASE : &'static str = "/usr/local/include/mbedtls/"; const MOD_FILE : &'static str = r#" #[allow(dead_co...
() { for header in HEADERS.iter() { gen(header); } } fn gen(header: &str) { let dir = "src/mbed/".to_string() + header + "/"; let file = dir.clone() + "bindings.rs"; create_dir_all(&dir).unwrap(); let bindings_file = File::create(file).unwrap(); bindgen::Builder::default() ...
main
identifier_name
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree {
let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { ...
random_line_split
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum ParseTree { Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree
struct Generator<'grammar> { grammar: &'grammar Grammar, rng: rand::rngs::ThreadRng, depth: u32, } const MAX_DEPTH: u32 = 10000; impl<'grammar> Generator<'grammar> { fn nonterminal(&mut self, nt: NonterminalString) -> Option<ParseTree> { if self.depth > MAX_DEPTH { return None; ...
{ let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes, the random walk overflows the stack, so we have a max, and if // it is exceeded, we just try again if let Some(result) = gen.nonterminal(symbol.clone()) { ...
identifier_body
generate.rs
//! Generate valid parse trees. use grammar::repr::*; use rand::{self, Rng}; use std::iter::Iterator; #[derive(PartialEq, Eq)] pub enum
{ Nonterminal(NonterminalString, Vec<ParseTree>), Terminal(TerminalString), } pub fn random_parse_tree(grammar: &Grammar, symbol: NonterminalString) -> ParseTree { let mut gen = Generator { grammar: grammar, rng: rand::thread_rng(), depth: 0, }; loop { // sometimes,...
ParseTree
identifier_name
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * 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 ...
fn create_socket(id: &ConnectionId) -> io::Result<UdpSocket> { let autobind_addr = SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0); let udp_socket = UdpSocket::bind(&autobind_addr)?; udp_socket.connect(id.rewritten_destination().into())?; Ok(udp_socket) } fn remove_fr...
{ cx_info!(target: TAG, id, "Open"); let socket = Self::create_socket(&id)?; let packetizer = Packetizer::new(&ipv4_header, &transport_header); let interests = Ready::readable(); let rc = Rc::new(RefCell::new(Self { id: id, client: client, sock...
identifier_body
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * 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 ...
Err(err) => { cx_warn!( target: TAG, self.id, "Cannot send to network, drop packet: {}", err ) } } } fn close(&mut self, selector: &mut Selector) { cx_info!(ta...
) { Ok(_) => { self.update_interests(selector); }
random_line_split
udp_connection.rs
/* * Copyright (C) 2017 Genymobile * * 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 ...
(&self) -> bool { self.closed } }
is_closed
identifier_name
ListDescription.js
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * A list item can contain a description. ...
ListDescription.handledProps = ['as', 'children', 'className', 'content']; ListDescription._meta = { name: 'ListDescription', parent: 'List', type: META.TYPES.ELEMENT }; ListDescription.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: custo...
{ var children = props.children, className = props.className, content = props.content; var classes = cx(className, 'description'); var rest = getUnhandledProps(ListDescription, props); var ElementType = getElementType(ListDescription, props); return React.createElement( ElementType, _ext...
identifier_body
ListDescription.js
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * A list item can contain a description. ...
(props) { var children = props.children, className = props.className, content = props.content; var classes = cx(className, 'description'); var rest = getUnhandledProps(ListDescription, props); var ElementType = getElementType(ListDescription, props); return React.createElement( ElementType, ...
ListDescription
identifier_name
ListDescription.js
import _extends from 'babel-runtime/helpers/extends'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * A list item can contain a description. ...
} ListDescription.handledProps = ['as', 'children', 'className', 'content']; ListDescription._meta = { name: 'ListDescription', parent: 'List', type: META.TYPES.ELEMENT }; ListDescription.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: cust...
);
random_line_split
scatter.py
from __future__ import division import numpy as np from bokeh.plotting import figure, HBox, output_file, show, VBox from bokeh.models import Range1d # create some data using python lists x1 = [1, 2, 5, 7, -8, 5, 2, 7, 1, -3, -5, 1.7, 5.4, -5] y1 = [5, 6, -3, 1.5, 2, 1, 1, 9, 2.4, -3, 6, 8, 2, 4] # creat...
show(VBox(HBox(p1, p2, p3), p4))
random_line_split
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } ...
}
}
random_line_split
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct
{ params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } impl Pan { pub fn new(params: PanParams) -> Pan { Pan { params: params } } } impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample {...
Pan
identifier_name
pan.rs
use traits::{SoundSample, SampleValue, stereo_value}; use params::*; use super::Efx; // 0. => all right 1. => all left declare_params!(PanParams { pan: 0.5 }); pub struct Pan { params: PanParams, } impl Parametrized for Pan { fn get_parameters(&mut self) -> &mut Parameters { &mut self.params } } ...
} impl Efx for Pan { fn sample(&mut self, sample: SampleValue) -> SoundSample { let right_v = self.params.pan.value(); let left_v = 1. - right_v; match sample { SampleValue::Mono(x) => stereo_value(x * right_v, x * left_v), SampleValue::Stereo(r, l) => stereo_valu...
{ Pan { params: params } }
identifier_body
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OP...
hostname = self.last_results[device].get("hostname") or None return hostname def update_info(self): """Ensure the information from the OPNSense router is up to date. Return boolean if scanning successful. """ devices = self.client.get_arp() self.last_resul...
return None
conditional_block
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None):
class OPNSenseDeviceScanner(DeviceScanner): """This class queries a router running OPNsense.""" def __init__(self, client, interfaces): """Initialize the scanner.""" self.last_results = {} self.client = client self.interfaces = interfaces def _get_mac_addrs(self, devices...
"""Configure the OPNSense device_tracker.""" interface_client = hass.data[OPNSENSE_DATA]["interfaces"] scanner = OPNSenseDeviceScanner( interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE] ) return scanner
identifier_body