file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mod.rs | /// Chapter 4.23 - Closures
/// [Chapter 4.23] https://doc.rust-lang.org/book/closures.html
pub use self::closures::*;
pub mod closures {
pub fn main() {
println!("====\nClosure:\n");
// We did not need to annotate the
// types of arguments the closure
// takes or the values it retu... | (x: i32) -> i32 { x + 1 }
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
plus_one_v1(10) == plus_one_v2(10) &&
plus_one_v2(10) == plus_one_v3(10)
}
fn move_closures() {
let mut num = 5;
// `num` will be changed
... | plus_one_v1 | identifier_name |
update_common.rs | use rmpv::Value;
use utils::serialize;
use request_type_key::RequestTypeKey;
use code::Code;
use common_operation::CommonOperation;
use FIX_STR_PREFIX;
use action::Action;
use rmpv::decode::read_value;
#[derive(Debug)]
pub struct UpdateCommon {
pub space: u64,
pub index: u64,
pub operation_type: CommonOper... |
}
| {
(RequestTypeKey::Update,
serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)),
(Value::from(Code::IndexId as u8), Value::from(self.index)),
(Value::from(Code::Key as u8),
... | identifier_body |
update_common.rs | use rmpv::Value;
use utils::serialize;
use request_type_key::RequestTypeKey;
use code::Code;
use common_operation::CommonOperation;
use FIX_STR_PREFIX;
use action::Action;
use rmpv::decode::read_value;
#[derive(Debug)]
pub struct | {
pub space: u64,
pub index: u64,
pub operation_type: CommonOperation,
pub field_number: u8,
pub argument: Value,
pub keys: Vec<Value>,
}
impl Action for UpdateCommon {
fn get(&self) -> (RequestTypeKey, Vec<u8>) {
(RequestTypeKey::Update,
serialize(Value::Map(vec![(Value::... | UpdateCommon | identifier_name |
update_common.rs | use rmpv::Value;
use utils::serialize;
use request_type_key::RequestTypeKey;
use code::Code;
use common_operation::CommonOperation;
use FIX_STR_PREFIX;
use action::Action;
use rmpv::decode::read_value;
#[derive(Debug)]
pub struct UpdateCommon {
pub space: u64,
pub index: u64,
pub operation_type: CommonOper... | pub field_number: u8,
pub argument: Value,
pub keys: Vec<Value>,
}
impl Action for UpdateCommon {
fn get(&self) -> (RequestTypeKey, Vec<u8>) {
(RequestTypeKey::Update,
serialize(Value::Map(vec![(Value::from(Code::SpaceId as u8), Value::from(self.space)),
... | random_line_split | |
size.js | const amino = require('../main.js');
const gfx = new amino.AminoGfx();
gfx.start(function (err) {
if (err) |
//size (100x100)
this.w(100);
this.h(100);
//see opacity.js
//root
const root = this.createGroup();
this.setRoot(root);
//rect
const rect = this.createRect().fill('#00ff00').opacity(1.0);
root.add(rect);
rect.opacity.anim().from(1.0).to(0.0).dur(1000).loop(-1).start();... | {
console.log('Start failed: ' + err.message);
return;
} | conditional_block |
size.js | const amino = require('../main.js');
const gfx = new amino.AminoGfx(); | return;
}
//size (100x100)
this.w(100);
this.h(100);
//see opacity.js
//root
const root = this.createGroup();
this.setRoot(root);
//rect
const rect = this.createRect().fill('#00ff00').opacity(1.0);
root.add(rect);
rect.opacity.anim().from(1.0).to(0.0).dur(10... |
gfx.start(function (err) {
if (err) {
console.log('Start failed: ' + err.message); | random_line_split |
encoding.py | quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args... |
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, bytes):
... | """
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettext_lazy() call.
return s
return force_bytes(s, encoding, strings_onl... | identifier_body |
encoding.py | quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args... |
if isinstance(s, Promise):
return six.text_type(s).encode(encoding, errors)
if not isinstance(s, six.string_types):
try:
if six.PY3:
return six.text_type(s).encode(encoding)
else:
return bytes(s)
except UnicodeEncodeError:
... | return s | conditional_block |
encoding.py | quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args... | (obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, six.integer_types + (type(None), float, Decimal,
datetime.datetime, datetime.date, datetime.time))
def ... | is_protected_type | identifier_name |
encoding.py | quote
except ImportError: # Python 2
from urllib import quote
import warnings
from django.utils.functional import Promise
from django.utils import six
class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
self.obj = obj
UnicodeDecodeError.__init__(self, *args... | return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, six.string_types):
if hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
if six.PY3:
if isinstance(s, bytes):
... | if isinstance(s, six.text_type): | random_line_split |
play.component.ts | var _ = require('underscore');
import { Component, OnInit } from '@angular/core';
import { AppState } from '../app.service';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LetterCheckingService } from '../LetterChecking... | implements OnInit {
private results = [];
private intervalId;
private checkLetterTimer;
constructor(
private appState: AppState,
public loginService: LoginService,
private router: Router,
public authService: AuthService,
private letterCheckingService: LetterCheckingService ) {
}
conne... | Play | identifier_name |
play.component.ts | var _ = require('underscore');
import { Component, OnInit } from '@angular/core';
import { AppState } from '../app.service';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LetterCheckingService } from '../LetterChecking... |
connected = false;
deviceStopped_CB() {
this.connected = false;
}
deviceStreaming_CB() {
this.connected = true;
}
private eraser = 0;
private throttledEraser = _.throttle(() => {
this.results.pop()
}, 2000, true);
ngOnInit() {
this.authService.authenticate('play');
... | {
} | identifier_body |
play.component.ts | var _ = require('underscore');
import { Component, OnInit } from '@angular/core';
import { AppState } from '../app.service';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LetterCheckingService } from '../LetterChecking... | else {
this.eraser = 0;
}
if (this.eraser >= 3) {
// console.log('erasing...')
//throttled eraser is not as sensitive
this.throttledEraser();
// this.results.pop();
this.eraser = 0;
clearInterval(this.checkLetterTimer);
this.letterCheckingS... | {
this.eraser++;
} | conditional_block |
play.component.ts | var _ = require('underscore');
import { Component, OnInit } from '@angular/core';
import { AppState } from '../app.service';
import { LoginService } from '../login.service'; | selector: 'play',
providers: [ LoginService, AuthService, AppState, LetterCheckingService ],
template: require('./play.component.html'),
styles: [ require('./play.component.css') ]
})
export class Play implements OnInit {
private results = [];
private intervalId;
private checkLetterTimer;
constructor(... | import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { LetterCheckingService } from '../LetterCheckingService.service';
@Component({ | random_line_split |
product.service.ts | import { Injectable } from "@angular/core";
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProductService {
public products: any = [];
public allProducts:any =[];
storeUrl = "https://storewebservice.herokuapp.com/products";
constructor(private... | this.allProducts = data
console.log(`the data ${data}`);
},
err => console.log(`error happened getting products ${err}`)
);
};
getproductbycategory(idcategory,idcategory1){
return this.http.get(this.storeUrl+"/"+idcategory+"/"+idcategor... | return this.http.get(this.storeUrl).map((response: Response) => response.json())
.subscribe(data => { | random_line_split |
product.service.ts |
import { Injectable } from "@angular/core";
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProductService {
public products: any = [];
public allProducts:any =[];
storeUrl = "https://storewebservice.herokuapp.com/products";
constructor(privat... | (removeid: any) {
console.log(removeid);
this.products = this.products.filter((product: any) => product.id != removeid)
};
editProduct(productNameEdit, productBarcodeEdit, productPriceEdit, productQuantityEdit, productImageEdit, productDescriptionEdit, id, status: any) {
console.log("in... | removeProduct | identifier_name |
product.service.ts |
import { Injectable } from "@angular/core";
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProductService {
public products: any = [];
public allProducts:any =[];
storeUrl = "https://storewebservice.herokuapp.com/products";
constructor(privat... | ;
editProduct(productNameEdit, productBarcodeEdit, productPriceEdit, productQuantityEdit, productImageEdit, productDescriptionEdit, id, status: any) {
console.log("in service");
console.log(productNameEdit)
if (productNameEdit != "") {
let body = {
"id": id,
... | {
console.log(removeid);
this.products = this.products.filter((product: any) => product.id != removeid)
} | identifier_body |
azure-arm-resource.d.ts | import { AzureEndpoint } from './azureModels';
import msRestAzure = require('./azure-arm-common');
import azureServiceClient = require('./AzureServiceClient');
export declare class ResourceManagementClient extends azureServiceClient.ServiceClient {
deployments: Deployments;
resourceGroups: ResourceGroups;
c... | {
private _client;
constructor(endpoint: AzureEndpoint);
getResources(resourceType: string, resourceName: string): Promise<any[]>;
}
export declare class ResourceGroups {
private client;
constructor(armClient: ResourceManagementClient);
checkExistence(resourceGroupName: string, callback: azureS... | Resources | identifier_name |
azure-arm-resource.d.ts | import { AzureEndpoint } from './azureModels';
import msRestAzure = require('./azure-arm-common');
import azureServiceClient = require('./AzureServiceClient');
export declare class ResourceManagementClient extends azureServiceClient.ServiceClient {
deployments: Deployments; | constructor(credentials: msRestAzure.ApplicationTokenCredentials, subscriptionId: string, options?: any);
}
export declare class Resources {
private _client;
constructor(endpoint: AzureEndpoint);
getResources(resourceType: string, resourceName: string): Promise<any[]>;
}
export declare class ResourceGro... | resourceGroups: ResourceGroups; | random_line_split |
scoping_rules_borrowing_aliasing.rs | struct Point { x: i32, y: i32, z: i32 }
pub fn main() {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references and the original owner
println!("Point has coordinates: ({}, {}, {})",
... | // Change data via mutable reference
mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// Error! Can't borrow `point` as immutable because it's currently
// borrowed as mutable.
//let mutable_borrow = &point;
// Error! Can't borrow `point... | }
{
let mutable_borrow = &mut point;
| random_line_split |
scoping_rules_borrowing_aliasing.rs | struct | { x: i32, y: i32, z: i32 }
pub fn main() {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references and the original owner
println!("Point has coordinates: ({}, {}, {})",
... | Point | identifier_name |
replwrap.py | """Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
"""
import os.path
import signal
import sys
import re
import pexpect
PY3 = (sys.version_info[0] >= 3)
if PY3:
def u(s): return s
basestring = str
else:
def u(s): return s.decode('utf-8')
PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')
PEXPEC... |
def _expect_prompt(self, timeout=-1):
return self.child.expect_exact([self.prompt, self.continuation_prompt],
timeout=timeout)
def run_command(self, command, timeout=-1):
"""Send a command to the REPL, wait for and return output.
:param str comm... | self.child.expect(orig_prompt)
self.child.sendline(prompt_change) | identifier_body |
replwrap.py | """Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
"""
import os.path
import signal
import sys
import re
import pexpect
PY3 = (sys.version_info[0] >= 3)
if PY3:
def u(s): return s
basestring = str
else:
def u(s): return s.decode('utf-8')
PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')
PEXPEC... |
else:
self.set_prompt(orig_prompt,
prompt_change.format(new_prompt, continuation_prompt))
self.prompt = new_prompt
self.continuation_prompt = continuation_prompt
self._expect_prompt()
if extra_init_cmd is not None:
self.run_c... | self.prompt = orig_prompt | conditional_block |
replwrap.py | """Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
"""
import os.path
import signal
import sys
import re
import pexpect
PY3 = (sys.version_info[0] >= 3)
if PY3:
def u(s): return s
basestring = str
else:
def u(s): return s.decode('utf-8')
PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')
PEXPEC... | :param str new_prompt: The more unique prompt to expect after the change.
:param str extra_init_cmd: Commands to do extra initialisation, such as
disabling pagers.
"""
def __init__(self, cmd_or_spawn, orig_prompt, prompt_change,
new_prompt=PEXPECT_PROMPT,
continua... | parameters, so you can use ``{}`` style formatting to insert them into
the command. | random_line_split |
replwrap.py | """Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
"""
import os.path
import signal
import sys
import re
import pexpect
PY3 = (sys.version_info[0] >= 3)
if PY3:
def u(s): return s
basestring = str
else:
def u(s): return s.decode('utf-8')
PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')
PEXPEC... | (self, cmd_or_spawn, orig_prompt, prompt_change,
new_prompt=PEXPECT_PROMPT,
continuation_prompt=PEXPECT_CONTINUATION_PROMPT,
extra_init_cmd=None):
if isinstance(cmd_or_spawn, basestring):
self.child = pexpect.spawnu(cmd_or_spawn, echo=False)
... | __init__ | identifier_name |
Inner.js | import PropTypes from 'prop-types';
import React from 'react';
import moment from 'moment';
import { withStyles } from 'material-ui/styles';
import IconButton from 'material-ui/IconButton';
import CloseIcon from 'material-ui-icons/Close';
import InfoIcon from 'material-ui-icons/Info';
import TimelineIcon from 'material... | <div>
<UserAvatar
src={avatar}
role="presentation"
onClick={onAvatarClick}
/>
<ImageDetail>
<span>
{image.user}
</span>
<span>
{moment(image.createdAt).format('YYYY-MM-DD HH:mm')}
... | random_line_split | |
cm_placement_group.py | ###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... | 'tab': 'CM Accounts',
'header':False,
'range': 'A2:A'
}}
):
if row:
account_id = lookup_id(row[0])
is_superuser, profile_id = get_profile_for_api(config, task['auth_cm'], account_id)
kwargs = { 'profileId': profile_id, 'campaignIds':campaigns, 'archived':... | random_line_split | |
cm_placement_group.py | ###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... |
yield from API_DCM(
config,
task['auth_cm'],
iterate=True,
internal=is_superuser
).placementGroups().list( **kwargs).execute()
cm_placement_group_clear(config, task)
# write placement_groups to database
put_rows(
config,
task['auth_bigquery'],
... | kwargs['accountId'] = account_id | conditional_block |
cm_placement_group.py | ###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... | ():
campaigns = [str(lookup_id(r)) for r in set(get_rows(
config,
task['auth_cm'],
{ 'sheets': {
'sheet': task['sheet'],
'tab': 'CM Campaigns',
'header':False,
'range': 'A2:A'
}},
unnest=True
))]
for row in get_rows(
config,
task['a... | load_multiple | identifier_name |
cm_placement_group.py | ###########################################################################
#
# Copyright 2020 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
#
# https://www.apache.org/l... |
def cm_placement_group_load(config, task):
# load multiple partners from user defined sheet
def load_multiple():
campaigns = [str(lookup_id(r)) for r in set(get_rows(
config,
task['auth_cm'],
{ 'sheets': {
'sheet': task['sheet'],
'tab': 'CM Campaigns',
'header':Fals... | table_create(
config,
task['auth_bigquery'],
config.project,
task['dataset'],
'CM_PlacementGroups',
Discovery_To_BigQuery(
'dfareporting',
'v3.4'
).method_schema(
'placementGroups.list',
iterate=True
)
) | identifier_body |
use-get-thumbnail.js | // @flow
import React from 'react';
import { generateStreamUrl } from 'util/web';
export default function | (
uri: string,
claim: ?Claim,
streamingUrl: ?string,
getFile: string => void,
shouldHide: boolean
) {
let thumbnailToUse;
// $FlowFixMe
const isImage = claim && claim.value && claim.value.stream_type === 'image';
// $FlowFixMe
const isFree = claim && claim.value && (!claim.value.fee || Number(claim... | useGetThumbnail | identifier_name |
use-get-thumbnail.js | // @flow
import React from 'react';
import { generateStreamUrl } from 'util/web';
export default function useGetThumbnail(
uri: string,
claim: ?Claim,
streamingUrl: ?string,
getFile: string => void,
shouldHide: boolean
) {
let thumbnailToUse;
// $FlowFixMe
const isImage = claim && claim.value && claim... | else if (claim && isImage && isFree) {
thumbnailToUse = generateStreamUrl(claim.name, claim.claim_id);
}
// @endif
// @if TARGET='app'
thumbnailToUse = thumbnailInClaim;
//
// Temporarily disabled until we can call get with "save_blobs: off"
//
// React.useEffect(() => {
// if (hasClaim && is... | {
thumbnailToUse = thumbnailInClaim;
} | conditional_block |
use-get-thumbnail.js | // @flow
import React from 'react';
import { generateStreamUrl } from 'util/web';
export default function useGetThumbnail(
uri: string,
claim: ?Claim,
streamingUrl: ?string,
getFile: string => void,
shouldHide: boolean
) | //
// Temporarily disabled until we can call get with "save_blobs: off"
//
// React.useEffect(() => {
// if (hasClaim && isImage && isFree) {
// if (streamingUrl) {
// setThumbnail(streamingUrl);
// } else if (!shouldHide) {
// getFile(uri);
// }
// }
// }, [hasClaim,... | {
let thumbnailToUse;
// $FlowFixMe
const isImage = claim && claim.value && claim.value.stream_type === 'image';
// $FlowFixMe
const isFree = claim && claim.value && (!claim.value.fee || Number(claim.value.fee.amount) <= 0);
const thumbnailInClaim = claim && claim.value && claim.value.thumbnail && claim.va... | identifier_body |
use-get-thumbnail.js | // @flow
import React from 'react';
import { generateStreamUrl } from 'util/web';
export default function useGetThumbnail(
uri: string,
claim: ?Claim,
streamingUrl: ?string,
getFile: string => void,
shouldHide: boolean
) {
let thumbnailToUse;
// $FlowFixMe
const isImage = claim && claim.value && claim... |
//
// Temporarily disabled until we can call get with "save_blobs: off"
//
// React.useEffect(() => {
// if (hasClaim && isImage && isFree) {
// if (streamingUrl) {
// setThumbnail(streamingUrl);
// } else if (!shouldHide) {
// getFile(uri);
// }
// }
// }, [hasClaim... |
// @if TARGET='app'
thumbnailToUse = thumbnailInClaim; | random_line_split |
lockfile_metadata.py | _dataclass_params.frozen:
raise ValueError(
"Classes registered with `_lockfile_metadata_version` may only be "
"frozen dataclasses"
)
_concrete_metadata_classes[version] = cls
return cls
return _dec
class InvalidLockfileError(Exception):
... |
return LockfileMetadataValidation(failure_reasons)
@_lockfile_metadata_version(2)
@dataclass(frozen=True)
class LockfileMetadataV2(LockfileMetadata):
"""Lockfile version that permits specifying a requirements as a set rather than a digest.
Validity is tested by the set of requirements strings being... | failure_reasons.add(InvalidLockfileReason.INTERPRETER_CONSTRAINTS_MISMATCH) | conditional_block |
lockfile_metadata.py | only be "
"frozen dataclasses"
)
_concrete_metadata_classes[version] = cls
return cls
return _dec
class InvalidLockfileError(Exception):
pass
@dataclass(frozen=True)
class LockfileMetadata:
"""Base class for metadata that is attached to a given lockfiles.
... | random_line_split | ||
lockfile_metadata.py | _dataclass_params.frozen:
raise ValueError(
"Classes registered with `_lockfile_metadata_version` may only be "
"frozen dataclasses"
)
_concrete_metadata_classes[version] = cls
return cls
return _dec
class InvalidLockfileError(Exception):
... | lambda l: {Requirement.parse(i) for i in l},
)
interpreter_constraints = metadata(
"valid_for_interpreter_constraints", InterpreterConstraints, InterpreterConstraints
)
return LockfileMetadataV2(interpreter_constraints, requirements)
def _header_dict(self) -... | """Lockfile version that permits specifying a requirements as a set rather than a digest.
Validity is tested by the set of requirements strings being the same in the user requirements as
those in the stored requirements.
"""
requirements: set[Requirement]
@classmethod
def _from_json_dict(
... | identifier_body |
lockfile_metadata.py | _dataclass_params.frozen:
raise ValueError(
"Classes registered with `_lockfile_metadata_version` may only be "
"frozen dataclasses"
)
_concrete_metadata_classes[version] = cls
return cls
return _dec
class InvalidLockfileError(Exception):
... | :
"""Base class for metadata that is attached to a given lockfiles.
This class, and provides the external API for serializing, deserializing, and validating the
contents of individual lockfiles. New versions of metadata implement a concrete subclass and
provide deserialization and validation logic, alo... | LockfileMetadata | identifier_name |
conf.py | contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master t... | # Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author, | random_line_split | |
account_balance_reporting_template.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account balance reporting engine
# Copyright (C) 2009 Pexego Sistemas Informáticos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | cr, uid, [
('template_id', '=', new_id),
('code', '=', line.parent_id.code),
], context=context)[0]
# Set the parent
line_obj.write(cr, uid, new_line_id,
{'parent_id': n... | # Search for the copied parent line
new_parent_id = line_obj.search( | random_line_split |
account_balance_reporting_template.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account balance reporting engine
# Copyright (C) 2009 Pexego Sistemas Informáticos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | 'line_ids': fields.one2many('account.balance.reporting.template.line',
'template_id', 'Lines'),
}
_defaults = {
'type': 'user',
'balance_mode': '0',
}
def copy(self, cr, uid, rec_id, default=None, context=None):
"""Redefine the copy m... | ""Account balance report template.
It stores the header fields of an account balance report template,
and the linked lines of detail with the formulas to calculate
the accounting concepts of the report.
"""
_name = "account.balance.reporting.template"
_columns = {
'name': fields.char('N... | identifier_body |
account_balance_reporting_template.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account balance reporting engine
# Copyright (C) 2009 Pexego Sistemas Informáticos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | self, cr, uid, rec_id, default=None, context=None):
"""Redefine the copy method to perform it correctly as the line
structure is a graph.
"""
line_obj = self.pool['account.balance.reporting.template.line']
# Read the current item data:
template = self.browse(cr, uid, rec_... | opy( | identifier_name |
account_balance_reporting_template.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account balance reporting engine
# Copyright (C) 2009 Pexego Sistemas Informáticos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Ge... | ids = []
if name:
ids = self.search(cr, uid, [('code', 'ilike', name)] + args,
limit=limit, context=context)
if not ids:
ids = self.search(cr, uid, [('name', operator, name)] + args,
limit=limit, cont... | rgs = []
| conditional_block |
subscriber.rs | // Copyright (C) 2015 <Rick Richardson r@12sidedtech.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
use std::fmt::Display;
use reactive::{Subscriber};
use sendable::Sendable;
pub struct StdoutSubscriber<A> where A : Display {
inde... | Decoupler {
index: None,
data_tx: tx,
}
}
}
impl<Q, I> Subscriber for Decoupler<Q, I>
where I : Send,
Q : Sendable<Item=I>
{
type Input = I;
fn on_next(&mut self, t: I) -> bool {
//TODO better handle queue failure, maybe put the returned buf
//... |
pub fn new(tx: Q) -> Decoupler<Q,I> { | random_line_split |
subscriber.rs | // Copyright (C) 2015 <Rick Richardson r@12sidedtech.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
use std::fmt::Display;
use reactive::{Subscriber};
use sendable::Sendable;
pub struct StdoutSubscriber<A> where A : Display {
inde... |
}
pub struct Decoupler<Q, I> where I : Send, Q : Sendable {
index: Option<usize>,
data_tx: Q,
}
impl<Q, I> Decoupler<Q, I> where I : Send, Q : Sendable {
pub fn new(tx: Q) -> Decoupler<Q,I> {
Decoupler {
index: None,
data_tx: tx,
}
}
}
impl<Q, I> Subscriber f... | {
println!("{}", t);
true
} | identifier_body |
subscriber.rs | // Copyright (C) 2015 <Rick Richardson r@12sidedtech.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
use std::fmt::Display;
use reactive::{Subscriber};
use sendable::Sendable;
pub struct StdoutSubscriber<A> where A : Display {
inde... | (v : &'a mut Box<Vec<I>>) -> Collect<'a, I> {
Collect {
index: None,
val: v
}
}
}
impl<'a, I> Subscriber for Collect<'a, I> where I : 'a {
type Input = I;
fn on_next(&mut self, t: I) -> bool {
self.val.push(t);
true
}
}
| new | identifier_name |
datapub.py | """Publishing native (typically pickled) objects.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from traitlets.config import Configurable
from ipykernel.inprocess.socket import SocketABC
from traitlets import Instance, Dict, CBytes
from ipykernel.jsonutil imp... |
def publish_data(data):
"""publish a data_message on the IOPub channel
Parameters
----------
data : dict
The data to be published. Think of it as a namespace.
"""
from ipykernel.zmqshell import ZMQInteractiveShell
ZMQInteractiveShell.instance().data_pub.publish_data(data)
| """publish a data_message on the IOPub channel
Parameters
----------
data : dict
The data to be published. Think of it as a namespace.
"""
session = self.session
buffers = serialize_object(data,
buffer_threshold=session.buffer_threshold,
... | identifier_body |
datapub.py | """Publishing native (typically pickled) objects.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from traitlets.config import Configurable
from ipykernel.inprocess.socket import SocketABC
from traitlets import Instance, Dict, CBytes
from ipykernel.jsonutil imp... |
def publish_data(data):
"""publish a data_message on the IOPub channel
Parameters
----------
data : dict
The data to be published. Think of it as a namespace.
"""
from ipykernel.zmqshell import ZMQInteractiveShell
ZMQInteractiveShell.instance().data_pub.publish_data(data) | parent=self.parent_header,
buffers=buffers,
ident=self.topic,
) | random_line_split |
datapub.py | """Publishing native (typically pickled) objects.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from traitlets.config import Configurable
from ipykernel.inprocess.socket import SocketABC
from traitlets import Instance, Dict, CBytes
from ipykernel.jsonutil imp... | (Configurable):
topic = topic = CBytes(b'datapub')
session = Instance(Session, allow_none=True)
pub_socket = Instance(SocketABC, allow_none=True)
parent_header = Dict({})
def set_parent(self, parent):
"""Set the parent for outbound messages."""
self.parent_header = extract_header(p... | ZMQDataPublisher | identifier_name |
test.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/te... | platformBrowserDynamicTesting(),
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context); | };
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule, | random_line_split |
issue_234.rs | use zip::result::ZipError;
const BUF: &[u8] = &[
0, 80, 75, 1, 2, 127, 120, 0, 3, 3, 75, 80, 232, 3, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 7, 0, 0, 0,
0, 65, 0, 1, 0, 0, 0, 4, 0, 0, 224, 255, 0, 255, 255, 255, 255, 255, 255, 20, 39, 221, 221,
221, 221, 221, 221, 205, 221, 221, 221, 42, 221, 221, 221, 221, 221, 221... | () {
let reader = std::io::Cursor::new(&BUF);
let archive = zip::ZipArchive::new(reader);
match archive {
Err(ZipError::InvalidArchive(_)) => {}
value => panic!("Unexpected value: {:?}", value),
}
}
| invalid_header | identifier_name |
issue_234.rs | use zip::result::ZipError;
const BUF: &[u8] = &[
0, 80, 75, 1, 2, 127, 120, 0, 3, 3, 75, 80, 232, 3, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 7, 0, 0, 0,
0, 65, 0, 1, 0, 0, 0, 4, 0, 0, 224, 255, 0, 255, 255, 255, 255, 255, 255, 20, 39, 221, 221,
221, 221, 221, 221, 205, 221, 221, 221, 42, 221, 221, 221, 221, 221, 221... | 120, 0, 99, 99, 99, 99, 99, 99, 94, 7, 0, 0, 0, 0, 0, 0, 213, 213, 213, 213, 213, 213, 213,
213, 213, 7, 0, 0, 211, 211, 211, 211, 124, 236, 99, 99, 99, 94, 7, 0, 0, 0, 0, 0, 0, 213, 213,
213, 213, 213, 213, 213, 213, 213, 7, 0, 0, 211, 211, 211, 211, 124, 236, 234, 0, 0, 0, 3, 8,
0, 0, 0, 12, 0, 0, 0, ... | random_line_split | |
issue_234.rs | use zip::result::ZipError;
const BUF: &[u8] = &[
0, 80, 75, 1, 2, 127, 120, 0, 3, 3, 75, 80, 232, 3, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 7, 0, 0, 0,
0, 65, 0, 1, 0, 0, 0, 4, 0, 0, 224, 255, 0, 255, 255, 255, 255, 255, 255, 20, 39, 221, 221,
221, 221, 221, 221, 205, 221, 221, 221, 42, 221, 221, 221, 221, 221, 221... |
value => panic!("Unexpected value: {:?}", value),
}
}
| {} | conditional_block |
issue_234.rs | use zip::result::ZipError;
const BUF: &[u8] = &[
0, 80, 75, 1, 2, 127, 120, 0, 3, 3, 75, 80, 232, 3, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 7, 0, 0, 0,
0, 65, 0, 1, 0, 0, 0, 4, 0, 0, 224, 255, 0, 255, 255, 255, 255, 255, 255, 20, 39, 221, 221,
221, 221, 221, 221, 205, 221, 221, 221, 42, 221, 221, 221, 221, 221, 221... | {
let reader = std::io::Cursor::new(&BUF);
let archive = zip::ZipArchive::new(reader);
match archive {
Err(ZipError::InvalidArchive(_)) => {}
value => panic!("Unexpected value: {:?}", value),
}
} | identifier_body | |
adt-tuple-struct.rs | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c);
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_>(&c);
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_... | };
}
fn main() { } | random_line_split | |
adt-tuple-struct.rs | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c);
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_>(&c);
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_... | <'a>(c: &'a u32) {
SomeStruct::<&'a u32>(c);
}
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) {
let _closure = || {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) {
let _closure = || {
SomeStru... | annot_reference_named_lifetime_ok | identifier_name |
adt-tuple-struct.rs | // Unit test for the "user substitutions" that are annotated on each
// node.
struct SomeStruct<T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c);
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_>(&c);
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_... |
fn main() { }
| {
let _closure = || {
SomeStruct::<&'a u32>(c);
};
} | identifier_body |
iterator_utils.rs |
pub(crate) struct CartesianProductIterator<'a, I1, I2> {
v1: &'a [I1],
v2: &'a [I2],
v1_idx: usize,
v2_idx: usize
}
impl <'a, I1, I2> CartesianProductIterator<'a, I1, I2> {
pub fn new(v1: &'a [I1], v2: &'a [I2]) -> Self {
CartesianProductIterator { v1, v2, v1_idx: 0, v2_idx: 0 }
}
}
impl <'a, I1: 'a,... | else {
self.v2_idx += 1;
Some((self.v1.get(self.v1_idx).unwrap(), self.v2.get(self.v2_idx - 1).unwrap()))
}
}
}
#[cfg(test)]
mod tests {
use expectest::prelude::*;
use super::CartesianProductIterator;
#[test]
fn cartesian_product_iterator_empty_array_tests() {
expect!(CartesianProductIt... | {
self.v2_idx = 1;
self.v1_idx += 1;
if self.v1_idx == self.v1.len() {
None
} else {
Some((self.v1.get(self.v1_idx).unwrap(), self.v2.get(self.v2_idx - 1).unwrap()))
}
} | conditional_block |
iterator_utils.rs | pub(crate) struct CartesianProductIterator<'a, I1, I2> {
v1: &'a [I1],
v2: &'a [I2],
v1_idx: usize,
v2_idx: usize
}
impl <'a, I1, I2> CartesianProductIterator<'a, I1, I2> {
pub fn new(v1: &'a [I1], v2: &'a [I2]) -> Self {
CartesianProductIterator { v1, v2, v1_idx: 0, v2_idx: 0 }
}
}
impl <'a, I1: 'a, ... | expect!(i1.next()).to(be_some().value((&1, &2)));
expect!(i1.next()).to(be_none());
let vec3 = vec![1, 2];
let mut i2 = CartesianProductIterator::new(&vec3, &vec2);
expect!(i2.next()).to(be_some().value((&1, &2)));
expect!(i2.next()).to(be_some().value((&2, &2)));
expect!(i2.next()).to(be_n... | fn cartesian_product_iterator_tests() {
let vec1 = vec![1];
let vec2 = vec![2];
let mut i1 = CartesianProductIterator::new(&vec1, &vec2); | random_line_split |
iterator_utils.rs |
pub(crate) struct CartesianProductIterator<'a, I1, I2> {
v1: &'a [I1],
v2: &'a [I2],
v1_idx: usize,
v2_idx: usize
}
impl <'a, I1, I2> CartesianProductIterator<'a, I1, I2> {
pub fn new(v1: &'a [I1], v2: &'a [I2]) -> Self {
CartesianProductIterator { v1, v2, v1_idx: 0, v2_idx: 0 }
}
}
impl <'a, I1: 'a,... | (&mut self) -> Option<Self::Item> {
if self.v1.is_empty() || self.v2.is_empty() || self.v1_idx == self.v1.len() &&
self.v2_idx == self.v2.len() {
None
} else if self.v2_idx == self.v2.len() {
self.v2_idx = 1;
self.v1_idx += 1;
if self.v1_idx == self.v1.len() {
None
} ... | next | identifier_name |
app.ts | /**
* @license
* Copyright 2020 Google LLC. 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 ... | import './components/mobile_view/components/mobile_modal.js';
import './components/mobile_view/components/mobile_expandable_section.js';
import './components/best_practices/best_practices.js'; | import './components/mobile_view/mobile_view.js';
import './components/mobile_view/open_mobile_view.js'; | random_line_split |
font.rs | use std::fmt;
use crossfont::Size as FontSize;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};
use alacritty_config_derive::ConfigDeserialize;
use crate::config::ui_config::Delta;
/// Font config.
///
/// Defaults are provided at the level of this struct per platform, but not per
/// field i... | Font { size: Size(size), ..self }
}
#[inline]
pub fn size(&self) -> FontSize {
self.size.0
}
/// Get normal font description.
pub fn normal(&self) -> &FontDescription {
&self.normal
}
/// Get bold font description.
pub fn bold(&self) -> FontDescription {
... | pub fn with_size(self, size: FontSize) -> Font { | random_line_split |
font.rs | use std::fmt;
use crossfont::Size as FontSize;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};
use alacritty_config_derive::ConfigDeserialize;
use crate::config::ui_config::Delta;
/// Font config.
///
/// Defaults are provided at the level of this struct per platform, but not per
/// field i... |
}
impl<'de> Deserialize<'de> for Size {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct NumVisitor;
impl<'v> Visitor<'v> for NumVisitor {
type Value = Size;
fn expecting(&self, f: &mut fmt::Formatter<'_>) ->... | {
Self(FontSize::new(11.))
} | identifier_body |
font.rs | use std::fmt;
use crossfont::Size as FontSize;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};
use alacritty_config_derive::ConfigDeserialize;
use crate::config::ui_config::Delta;
/// Font config.
///
/// Defaults are provided at the level of this struct per platform, but not per
/// field i... | <E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
Ok(Size(FontSize::new(value as f32)))
}
fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
Ok(Size(FontSize::new(value as f32)))
}
}
deserializer.deser... | visit_f64 | identifier_name |
util.rs | use std::ffi::{CString, CStr};
use std::str;
use libc::{c_char, c_int};
use err::HdfsErr;
use native::*;
use dfs::HdfsFs;
pub fn str_to_chars(s: &str) -> *const c_char {
CString::new(s.as_bytes()).unwrap().as_ptr()
}
pub fn chars_to_str<'a>(chars: *const c_char) -> &'a str {
let slice = unsafe { CStr::from_ptr(c... | else { 0 }
}
/// Hdfs Utility
pub struct HdfsUtil;
/// HDFS Utility
impl HdfsUtil {
/// Copy file from one filesystem to another.
///
/// #### Params
/// * ```srcFS``` - The handle to source filesystem.
/// * ```src``` - The path of source file.
/// * ```dstFS``` - The handle to destination filesystem.
... | { 1 } | conditional_block |
util.rs | use std::ffi::{CString, CStr};
use std::str;
use libc::{c_char, c_int};
use err::HdfsErr;
use native::*;
use dfs::HdfsFs;
pub fn str_to_chars(s: &str) -> *const c_char {
CString::new(s.as_bytes()).unwrap().as_ptr()
}
pub fn chars_to_str<'a>(chars: *const c_char) -> &'a str {
let slice = unsafe { CStr::from_ptr(c... | (src_fs: &HdfsFs, src: &str, dst_fs: &HdfsFs, dst: &str)
-> Result<bool, HdfsErr> {
let res = unsafe {
hdfsMove(src_fs.raw(), str_to_chars(src), dst_fs.raw(), str_to_chars(dst))
};
if res == 0 {
Ok(true)
} else {
Err(HdfsErr::Unknown)
}
}
} | mv | identifier_name |
util.rs | use std::ffi::{CString, CStr};
use std::str;
use libc::{c_char, c_int};
use err::HdfsErr;
use native::*;
use dfs::HdfsFs;
| pub fn str_to_chars(s: &str) -> *const c_char {
CString::new(s.as_bytes()).unwrap().as_ptr()
}
pub fn chars_to_str<'a>(chars: *const c_char) -> &'a str {
let slice = unsafe { CStr::from_ptr(chars) }.to_bytes();
str::from_utf8(slice).unwrap()
}
pub fn bool_to_c_int(val: bool) -> c_int {
if val { 1 } else { 0 }... | random_line_split | |
util.rs | use std::ffi::{CString, CStr};
use std::str;
use libc::{c_char, c_int};
use err::HdfsErr;
use native::*;
use dfs::HdfsFs;
pub fn str_to_chars(s: &str) -> *const c_char |
pub fn chars_to_str<'a>(chars: *const c_char) -> &'a str {
let slice = unsafe { CStr::from_ptr(chars) }.to_bytes();
str::from_utf8(slice).unwrap()
}
pub fn bool_to_c_int(val: bool) -> c_int {
if val { 1 } else { 0 }
}
/// Hdfs Utility
pub struct HdfsUtil;
/// HDFS Utility
impl HdfsUtil {
/// Copy file fro... | {
CString::new(s.as_bytes()).unwrap().as_ptr()
} | identifier_body |
peers.ts | /*
* Copyright © 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated... | ipAddress: '192.28.138.1',
wsPort: 5006,
height: 645982,
isDiscoveredPeer: false,
version: '1.2.1',
};
const peerOption5: P2PDiscoveredPeerInfo = {
ipAddress: '178.21.90.199',
wsPort: 5001,
height: 645980,
isDiscoveredPeer: false,
version: '1.1.1',
};
return [peerOption1, peerOption2, peerOpti... | version: '1.3.1',
};
const peerOption4: P2PDiscoveredPeerInfo = { | random_line_split |
alias_ok.rs | extern crate crucible;
use std::cell::Cell;
use std::mem;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(x: &Cell<u8>, y: &Cell<u8>) {
x.swap(y);
}
#[crux_test]
fn f_test() {
clobber_globals();
let x = Cell::new(u8::symbolic("x"));
let y = Cell::new(... | msb.gather_assumes();
// Call happens here
crucible_assert!(y.get() > 0);
msb.set_return(&());
msb.gather_asserts();
msb.finish()
}
#[crux_test]
fn use_f() {
f_spec().enable();
let a = Cell::new(u8::symbolic("a"));
let b = Cell::new(u8::symbolic("b"));
crucible_assume!(0 < a.... | msb.add_arg(& &y); | random_line_split |
alias_ok.rs | extern crate crucible;
use std::cell::Cell;
use std::mem;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(x: &Cell<u8>, y: &Cell<u8>) {
x.swap(y);
}
#[crux_test]
fn f_test() {
clobber_globals();
let x = Cell::new(u8::symbolic("x"));
let y = Cell::new(... | {
f_spec().enable();
let a = Cell::new(u8::symbolic("a"));
let b = Cell::new(u8::symbolic("b"));
crucible_assume!(0 < a.get() && a.get() < 10);
crucible_assume!(b.get() == 0);
f(&a, &b);
crucible_assert!(0 < b.get());
crucible_assert!(b.get() < 10);
} | identifier_body | |
alias_ok.rs | extern crate crucible;
use std::cell::Cell;
use std::mem;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn | (x: &Cell<u8>, y: &Cell<u8>) {
x.swap(y);
}
#[crux_test]
fn f_test() {
clobber_globals();
let x = Cell::new(u8::symbolic("x"));
let y = Cell::new(u8::symbolic("y"));
crucible_assume!(x.get() > 0);
f(&x, &y);
crucible_assert!(y.get() > 0);
}
fn f_spec() -> MethodSpec {
let x = Cell::new... | f | identifier_name |
serve.js | 'use strict';
var errorPage = require('../../lib/serve/error_page'),
extend = require('extend'),
sharedOptions = require('./shared_options'), | var build = require('./build').handler;
module.exports.command = 'serve [input..]';
module.exports.description = 'generate, update, and display HTML documentation';
/**
* Add yargs parsing for the serve command
* @param {Object} yargs module instance
* @returns {Object} yargs with options
* @private
*/
module.exp... | Server = require('../../lib/serve/server');
| random_line_split |
serve.js | 'use strict';
var errorPage = require('../../lib/serve/error_page'),
extend = require('extend'),
sharedOptions = require('./shared_options'),
Server = require('../../lib/serve/server');
var build = require('./build').handler;
module.exports.command = 'serve [input..]';
module.exports.description = 'generate, u... |
server.setFiles(output).start();
});
};
| {
return server.setFiles([errorPage(err)]).start();
} | conditional_block |
util.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | Some(1),
])
.data();
assert_eq!(data, indexed.data());
}
}
| {
let value_data = Int32Array::from((0..10).collect::<Vec<i32>>()).data();
let value_offsets = Buffer::from(&[0, 2, 5, 10].to_byte_slice());
let list_data_type = DataType::List(Box::new(DataType::Int32));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
... | identifier_body |
util.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | () {
let value_data = Int32Array::from((0..10).collect::<Vec<i32>>()).data();
let value_offsets = Buffer::from(&[0, 2, 5, 10].to_byte_slice());
let list_data_type = DataType::List(Box::new(DataType::Int32));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
... | test_take_value_index_from_list | identifier_name |
util.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | }
}
(UInt32Array::from(values), new_offsets)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use crate::array::ArrayData;
use crate::datatypes::{DataType, ToByteSlice};
#[test]
fn test_apply_bin_op_to_option_bitmap() {
assert_eq!(
Ok(None),
... | }
} else {
new_offsets.push(current_offset); | random_line_split |
backend.py | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Kevin Pouget
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your optio... | def iter_accounts(self):
with self.browser:
return self.browser.get_accounts_list()
def get_account(self, _id):
with self.browser:
account = self.browser.get_account(_id)
if account:
return account
else:
raise AccountNotFound()
... | lf.BROWSER = CreditCooperatifPro
return self.create_browser(self.config['login'].get(),
self.config['password'].get(),
strong_auth=self.config['auth_type'].get() == "strong")
| conditional_block |
backend.py | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Kevin Pouget
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your optio... | return self.create_browser(self.config['login'].get(),
self.config['password'].get(),
strong_auth=self.config['auth_type'].get() == "strong")
def iter_accounts(self):
with self.browser:
return self.browser... | NAME = 'creditcooperatif'
MAINTAINER = u'Kevin Pouget'
EMAIL = 'weboob@kevin.pouget.me'
VERSION = '0.i'
DESCRIPTION = u'Crédit Coopératif'
LICENSE = 'AGPLv3+'
auth_type = {'particular': "Interface Particuliers",
'weak' : "Code confidentiel (pro)",
'strong': "Ses... | identifier_body |
backend.py | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Kevin Pouget
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your optio... | def iter_history(self, account):
with self.browser:
return self.browser.get_history(account)
def iter_coming(self, account):
with self.browser:
return self.browser.get_coming(account) | else:
raise AccountNotFound()
| random_line_split |
backend.py | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Kevin Pouget
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your optio... | (BaseBackend, ICapBank):
NAME = 'creditcooperatif'
MAINTAINER = u'Kevin Pouget'
EMAIL = 'weboob@kevin.pouget.me'
VERSION = '0.i'
DESCRIPTION = u'Crédit Coopératif'
LICENSE = 'AGPLv3+'
auth_type = {'particular': "Interface Particuliers",
'weak' : "Code confidentiel (pro)",
... | CreditCooperatifBackend | identifier_name |
admin.py | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Stock, StockHistory, StockSelection, SectorHistory, StockNews
class | (admin.ModelAdmin):
date_hierarchy = 'pub_date'
class SectorAdmin(CommonAdmin):
list_display = ('Symbol', 'Sector', 'pub_date')
search_fields = ['Symbol', 'Sector']
class StockAdmin(CommonAdmin):
list_display = ('Symbol', 'Name','MarketCap', 'Catagory', 'pub_date')
search_fields = ['Symbol']
clas... | CommonAdmin | identifier_name |
admin.py | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Stock, StockHistory, StockSelection, SectorHistory, StockNews
class CommonAdmin(admin.ModelAdmin):
|
class SectorAdmin(CommonAdmin):
list_display = ('Symbol', 'Sector', 'pub_date')
search_fields = ['Symbol', 'Sector']
class StockAdmin(CommonAdmin):
list_display = ('Symbol', 'Name','MarketCap', 'Catagory', 'pub_date')
search_fields = ['Symbol']
class StockRelativeAdmin(CommonAdmin):
def stock_in... | date_hierarchy = 'pub_date' | identifier_body |
admin.py | from django.contrib import admin
from django.contrib.auth.models import User
from .models import Stock, StockHistory, StockSelection, SectorHistory, StockNews
class CommonAdmin(admin.ModelAdmin):
date_hierarchy = 'pub_date'
class SectorAdmin(CommonAdmin):
list_display = ('Symbol', 'Sector', 'pub_date') |
class StockAdmin(CommonAdmin):
list_display = ('Symbol', 'Name','MarketCap', 'Catagory', 'pub_date')
search_fields = ['Symbol']
class StockRelativeAdmin(CommonAdmin):
def stock_info(obj):
return '{}, {}, {}, {}'.format(
obj.stock.Symbol,
obj.stock.Name,
obj.stoc... | search_fields = ['Symbol', 'Sector'] | random_line_split |
serverlocal.js | // Init express server
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server = require('http').Server(app);
server.listen(3000);
console.log("started listenning on port 3000");
// Subscribe to lexa's router stream and update the LED accordingly
// var onoff = requir... |
})
var name = "BLAH";
name = name.toLowerCase();
name = name.charAt(0).toUpperCase() + name.slice(1);
res.send(name);
});
// Monitor process termination and do cleanups
// process.on('SIGINT', function () {
// led.writeSync(0);
// led.unexport();
// process.exit();
// });
// db.ref('... | {
var userData = snap.child("users/Mike/led")
console.log(parseInt(userData.val()));
} | conditional_block |
serverlocal.js | // Init express server
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server = require('http').Server(app);
server.listen(3000);
console.log("started listenning on port 3000");
// Subscribe to lexa's router stream and update the LED accordingly
// var onoff = requir... | res.send(name);
});
// Monitor process termination and do cleanups
// process.on('SIGINT', function () {
// led.writeSync(0);
// led.unexport();
// process.exit();
// });
// db.ref('authed').once('value', function (snap) {
// var lastScannedTagOwner = snap.val();
// if (lastS... | var name = "BLAH";
name = name.toLowerCase();
name = name.charAt(0).toUpperCase() + name.slice(1); | random_line_split |
search.py | import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
... |
def make_matcher(pattern, case_sensitive=True, is_regexp=False):
if not is_regexp:
pattern = "^.*" + re.escape(pattern)
flags = re.UNICODE
if not case_sensitive:
flags |= re.IGNORECASE
return re.compile(pattern, flags).search
if __name__ == "__main__":
import sys
Search(".", m... | pass | identifier_body |
search.py | import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
... |
except OSError:
pass
def search(self):
self.quit = False
try:
self._search(*os.path.split(self.path))
except SearchAborted:
self.output.abort_find(self)
except Exception as e:
self.output.end_find(self)
if not isin... | self._search_dir(info.path) | conditional_block |
search.py | import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
... | (self, finder):
pass
def make_matcher(pattern, case_sensitive=True, is_regexp=False):
if not is_regexp:
pattern = "^.*" + re.escape(pattern)
flags = re.UNICODE
if not case_sensitive:
flags |= re.IGNORECASE
return re.compile(pattern, flags).search
if __name__ == "__main__":
... | end_find | identifier_name |
search.py | import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
... | pass
def search(self):
self.quit = False
try:
self._search(*os.path.split(self.path))
except SearchAborted:
self.output.abort_find(self)
except Exception as e:
self.output.end_find(self)
if not isinstance(e, (OSError, IOErr... | except OSError: | random_line_split |
two.component.spec.ts | import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TwoComponent } from ... | {
}
| TwoComponentTestController | identifier_name |
two.component.spec.ts | import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TwoComponent } from ... | `,
directives: [TwoComponent]
})
class TwoComponentTestController {
} | selector: 'test',
template: `
<app-two></app-two> | random_line_split |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use std::fmt;
/// The real `ToCss... |
}
impl ToCss for Au {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}px", self.to_f64_px())
}
}
macro_rules! impl_to_css_for_predefined_type {
($name: ty) => {
impl<'a> ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result w... | {
let mut iter = self.iter();
iter.next().unwrap().to_css(dest)?;
for item in iter {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
} | identifier_body |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use std::fmt;
/// The real `ToCss... | (&self, value: f32) -> bool {
match *self {
AllowedNumericType::All => true,
AllowedNumericType::NonNegative => value >= 0.,
}
}
/// Clamp the value following the rules of this numeric type.
#[inline]
pub fn clamp(&self, val: Au) -... | is_ok | identifier_name |
values.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/. */
//! Helper types and traits for the handling of CSS values.
use app_units::Au;
use std::fmt;
/// The real `ToCss... | }
}
}
impl ToCss for $name {
fn to_css<W>(&self, dest: &mut W) -> ::std::fmt::Result
where W: ::std::fmt::Write
{
match *self {
$( $name::$variant => dest.write_str($css) ),+
}
... | pub fn parse(input: &mut ::cssparser::Parser) -> Result<$name, ()> {
match_ignore_ascii_case! { try!(input.expect_ident()),
$( $css => Ok($name::$variant), )+
_ => Err(()) | random_line_split |
union.rs | @gmail.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/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
... | (cx: &ExtCtxt, n: Spanned<u64>) -> P<ast::Expr> {
cx.expr_lit(n.span, ast::LitInt(n.node as u64, ast::UnsignedIntLit(ast::TyUs)))
}
/// Returns the type of the field representing the given register
/// within a `RegGroup` struct
fn reg_struct_type(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg)
... | expr_usize | identifier_name |
union.rs | @gmail.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/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
... | },
)
},
}
}
/// Build the type associated with a register group
fn build_union_type(&self, path: &Vec<String>, reg: &node::Reg,
regs: &Vec<node::Reg>) -> Vec<P<ast::Item>> {
let name = utils::path_ident(self.cx, path);
// Registers are already sorted by ... | {
match reg_or_pad {
RegOrPadding::Reg(reg) => self.build_reg_union_field(path, reg),
RegOrPadding::Pad(length) => {
let u8_path = self.cx.path_ident(
DUMMY_SP,
self.cx.ident_of("u8"));
let u8_ty: P<ast::Ty> = self.cx.ty_path(u8_path);
let ty: P<ast::Ty> =
... | identifier_body |
union.rs | .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/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// dis... |
}
}
}
/// Build types for `RegUnions`
pub struct BuildUnionTypes<'a> {
builder: &'a mut Builder,
cx: &'a ExtCtxt<'a>
}
impl<'a> BuildUnionTypes<'a> {
pub fn new(builder: &'a mut Builder, cx: &'a ExtCtxt<'a>)
-> BuildUnionTypes<'a> {
BuildUnionTypes { builder: builder, cx: cx }
}
}
fn expr_us... | {
self.index += 1;
self.last_offset += reg.size();
Some(RegOrPadding::Reg(reg))
} | conditional_block |
union.rs | @gmail.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/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
... | self.cx.ident_of(reg.name.node.as_str()),
ast::Public),
id: ast::DUMMY_NODE_ID,
ty: reg_struct_type(self.cx, &field_path, reg),
attrs: attrs,
}
)
}
/// Build field for padding or a register
// Dummy spans allowed here because u8 doesn't come from anywhere
#... | kind: ast::NamedField( | random_line_split |
reftypes.py | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEO... | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.