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
problem_94.py
"""94. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the in-order traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively?...
ans = [] ans += self.recursive_inorder_traversal(root.left) ans.append(root.val) ans += self.recursive_inorder_traversal(root.right) return ans
return []
conditional_block
problem_94.py
"""94. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the in-order traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively?...
from common.tree_node import TreeNode class Solution: def iterative_inorder_traversal(self, root: TreeNode) -> List[int]: """ iterative traversal """ ans = [] stack = [] while root or stack: if root: stack.append(root) ro...
random_line_split
problem_94.py
"""94. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the in-order traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively?...
(self, root: TreeNode) -> List[int]: """ recursive traversal, process left if needed, then val, at last right """ if not root: return [] ans = [] ans += self.recursive_inorder_traversal(root.left) ans.append(root.val) ans += self.recursive_inor...
recursive_inorder_traversal
identifier_name
problem_94.py
"""94. Binary Tree Inorder Traversal https://leetcode.com/problems/binary-tree-inorder-traversal/ Given a binary tree, return the in-order traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively?...
def recursive_inorder_traversal(self, root: TreeNode) -> List[int]: """ recursive traversal, process left if needed, then val, at last right """ if not root: return [] ans = [] ans += self.recursive_inorder_traversal(root.left) ans.append(root.va...
""" iterative traversal """ ans = [] stack = [] while root or stack: if root: stack.append(root) root = root.left else: root = stack.pop() ans.append(root.val) root = root.righ...
identifier_body
database.py
""" Database-related functionality for Minos. """ from flask_sqlalchemy import SQLAlchemy from .app import app, cache db = SQLAlchemy() class SonosConfig(db.Model): """ Database-class that contains the configuration for Sonos funcionality. """ __tablename__ = 'sonos_config' key = db.Column(db.Stri...
(db.Model): """ A role represents a type of user in the system. Roles do no support inheritence and are simply flat permission classes instead of a hierarchy. """ __tablename__ = 'roles' # Columns. id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, ...
Role
identifier_name
database.py
""" Database-related functionality for Minos. """ from flask_sqlalchemy import SQLAlchemy from .app import app, cache db = SQLAlchemy()
__tablename__ = 'sonos_config' key = db.Column(db.String, nullable=False, primary_key=True) value = db.Column(db.String) _type = db.Column('type', db.String) class OAuthConfig(db.Model): """ Configuration of OAuth providers. """ __tablename__ = 'oauth_settings' id = db.Column(db.Intege...
class SonosConfig(db.Model): """ Database-class that contains the configuration for Sonos funcionality. """
random_line_split
database.py
""" Database-related functionality for Minos. """ from flask_sqlalchemy import SQLAlchemy from .app import app, cache db = SQLAlchemy() class SonosConfig(db.Model): """ Database-class that contains the configuration for Sonos funcionality. """ __tablename__ = 'sonos_config' key = db.Column(db.Stri...
except: pass # If any of the role names match ours then we have that role. return any(map(lambda r: r.name == role_name, self.roles)) class UserVote(db.Model): __tablename__ = 'votes' __table_args__ = (db.PrimaryKeyConstraint('uid', 'uri', name='uservotes_pk'),) uid ...
return False
conditional_block
database.py
""" Database-related functionality for Minos. """ from flask_sqlalchemy import SQLAlchemy from .app import app, cache db = SQLAlchemy() class SonosConfig(db.Model): """ Database-class that contains the configuration for Sonos funcionality. """ __tablename__ = 'sonos_config' key = db.Column(db.Stri...
class UserVote(db.Model): __tablename__ = 'votes' __table_args__ = (db.PrimaryKeyConstraint('uid', 'uri', name='uservotes_pk'),) uid = db.Column(db.ForeignKey('users.id')) uri = db.Column(db.String(), nullable=False, index=True) speaker = db.Column(db.String, nullable=False) direction = db.C...
""" Check if a user has a role. """ try: from flask import session # If the user is not logged in, bail out right away. if not session.get('logged_in', False): return False except: pass # If any of the role names match ours then w...
identifier_body
limits.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
(self): request = pecan.request context = pecan.request.environ['context'] absolute_limits = central_api.get_absolute_limits(context) return self._view.show(context, request, absolute_limits)
get_all
identifier_name
limits.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> #
random_line_split
limits.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
_view = limits_view.LimitsView() @pecan.expose(template='json:', content_type='application/json') def get_all(self): request = pecan.request context = pecan.request.environ['context'] absolute_limits = central_api.get_absolute_limits(context) return self._view.show(context, re...
identifier_body
test_injector.ts
import {provide, Provider} from 'angular2/src/core/di'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {Reflector, reflector} fro...
provide(KeyValueDiffers, {useValue: defaultKeyValueDiffers}), Log, provide(DynamicComponentLoader, {useClass: DynamicComponentLoader_}), PipeResolver, provide(ExceptionHandler, {useValue: new ExceptionHandler(DOM)}), provide(LocationStrategy, {useClass: MockLocationStrategy}), provide(XHR, {...
ProtoViewFactory, provide(DirectiveResolver, {useClass: MockDirectiveResolver}), provide(ViewResolver, {useClass: MockViewResolver}), provide(IterableDiffers, {useValue: defaultIterableDiffers}),
random_line_split
test_injector.ts
import {provide, Provider} from 'angular2/src/core/di'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {Reflector, reflector} fro...
/** * Allows injecting dependencies in `beforeEach()` and `it()`. When using with the * `angular2/testing` library, the test function will be run within a zone and will * automatically complete when all asynchronous tests have finished. * * Example: * * ``` * beforeEach(inject([Dependency, AClass], (dep, obje...
{ return createTestInjector(ListWrapper.concat(_runtimeCompilerBindings(), providers)); }
identifier_body
test_injector.ts
import {provide, Provider} from 'angular2/src/core/di'; import {AnimationBuilder} from 'angular2/src/animate/animation_builder'; import {MockAnimationBuilder} from 'angular2/src/mock/animation_builder_mock'; import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory'; import {Reflector, reflector} fro...
(providers: Array<Type | Provider | any[]>): Injector { var rootInjector = Injector.resolveAndCreate(_getRootProviders()); return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), providers)); } export function createTestInjectorWithRuntimeCompiler( providers: Array<Type | Provider | any...
createTestInjector
identifier_name
getPath_test.js
/*globals Foo:true $foo:true */ var obj, moduleOpts = { setup: function() { obj = { foo: { bar: { baz: { biff: 'BIFF' } } } }; Foo = { bar: { baz: { biff: 'FooBiff' } } }; $foo = { bar: { baz: { biff: '$FOOBIFF' } } ...
teardown: function() { obj = null; Foo = null; $foo = null; } }; module('Ember.get with path', moduleOpts); // .......................................................... // LOCAL PATHS // test('[obj, foo] -> obj.foo', function() { deepEqual(Ember.get(obj, 'foo'), obj.foo); }); test('[obj, foo.bar...
},
random_line_split
templates.js
'use strict'; // gulp and general utils var gulp = require('gulp'); var gif = require('gulp-if'); var concat = require('gulp-concat');
var header = require('gulp-header'); // templates var ngHtml2js = require('gulp-ng-html2js'); var minifyHtml = require("gulp-minify-html"); module.exports = function(cfg) { var wwwDir = cfg.uri[cfg.siteBuild].ghpages; var templatesHtmlIn = cfg.uri[cfg.siteBuild].templatesHtmlIn; var templates...
var templateCache = require('gulp-angular-templatecache');
random_line_split
ref.py
# This file is part of OpenStack Ansible driver for Kostyor. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
_run_playbook = _run_playbook _run_playbook_for = _run_playbook_for
identifier_body
ref.py
# This file is part of OpenStack Ansible driver for Kostyor. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
(base.Driver): _run_playbook = _run_playbook _run_playbook_for = _run_playbook_for
Driver
identifier_name
ref.py
# This file is part of OpenStack Ansible driver for Kostyor. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
return settings def _run_playbook_impl(playbook, hosts_fn=None, cwd=None, ignore_errors=False): # Unfortunately, there's no good way to get the options instance # with proper defaults since it's generated by argparse inside # PlaybookCLI. Due to the fact that the options can't be empty # and mus...
settings = combine_vars(settings, loader.load_from_file(filename))
conditional_block
ref.py
# This file is part of OpenStack Ansible driver for Kostyor. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
# Get others required options. loader = DataLoader() variable_manager = VariableManager() inventory = Inventory(loader, variable_manager) variable_manager.set_inventory(inventory) variable_manager.extra_vars = _get_user_settings(loader) # Limit playbook execution to hosts returned by 'hosts...
playbook_cli = PlaybookCLI(['to-be-stripped', playbook]) playbook_cli.parse() options = playbook_cli.options
random_line_split
producto.service.ts
import { Injectable } from '@angular/core'; import {producto, maquinaria,select} from '../app.interfaces'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { HttpModule } from '@angular/http'; import {MaquinariaService} from './maquinaria.serv...
return this.http.post('http://localhost:3000/producto/modify/'+producto.idProducto, producto, {headers}).map( res => res.json()); } }
{ console.log(this.productos[i].idProducto, producto.idProducto) if(this.productos[i].idProducto==producto.idProducto){ this.productos.splice(i,1); this.productos.push(producto); } }
conditional_block
producto.service.ts
import { Injectable } from '@angular/core'; import {producto, maquinaria,select} from '../app.interfaces'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { HttpModule } from '@angular/http'; import {MaquinariaService} from './maquinaria.serv...
return this.http.get('http://localhost:3000/producto/delete/'+id).map(res => res.json()); } getProductos(){ return this.http.get('http://localhost:3000/producto/').map(res => res.json()); } returnProductos(){ this.productos= this.establecerValores(); return this.productos; } guardarProducto...
} } console.log('http://localhost:3000/producto/delete/'+id);
random_line_split
producto.service.ts
import { Injectable } from '@angular/core'; import {producto, maquinaria,select} from '../app.interfaces'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { HttpModule } from '@angular/http'; import {MaquinariaService} from './maquinaria.serv...
(private http:Http) { } establecerValores(){ this.productos.length = 0; this.getProductos().subscribe(data => { for(let key$ in data.datos){ this.productos.push(data.datos[key$]); } }); return this.productos; } deleteProducto(id:number){ console.log("Eliminando...
constructor
identifier_name
producto.service.ts
import { Injectable } from '@angular/core'; import {producto, maquinaria,select} from '../app.interfaces'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { HttpModule } from '@angular/http'; import {MaquinariaService} from './maquinaria.serv...
guardarProducto(producto:producto){ this.addProducto(producto).subscribe(data => { for(let key$ in data.datos){ this.productos[key$] = data.datos[key$]; } }); } addProducto(producto:producto){ let headers = new Headers({ 'Content-Type':'application/json' }); ret...
{ this.productos= this.establecerValores(); return this.productos; }
identifier_body
0024_auto_20201206_0819.py
# Generated by Django 3.1.4 on 2020-12-06 08:19 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('projects', '0023_auto_20201202_0349'), ] operations = [ migrations.AlterField( model_name='review', name='status', field=models.CharField(choices=[('PENDING', 'Pending'), ('REQUESTED', 'Requested'), ('CANCELLED', 'Cancelled'), ('ACCEPTED', ...
identifier_body
0024_auto_20201206_0819.py
# Generated by Django 3.1.4 on 2020-12-06 08:19 from django.db import migrations, models
('projects', '0023_auto_20201202_0349'), ] operations = [ migrations.AlterField( model_name='review', name='status', field=models.CharField(choices=[('PENDING', 'Pending'), ('REQUESTED', 'Requested'), ('CANCELLED', 'Cancelled'), ('ACCEPTED', 'Accepted'), ('DE...
class Migration(migrations.Migration): dependencies = [
random_line_split
0024_auto_20201206_0819.py
# Generated by Django 3.1.4 on 2020-12-06 08:19 from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('projects', '0023_auto_20201202_0349'), ] operations = [ migrations.AlterField( model_name='review', name='status', field=models.CharField(choices=[('PENDING', 'Pending'), ('REQUESTED', 'Requested'), ('CANCELLED'...
Migration
identifier_name
drop_zone.js
/** * Shopware 4.0 * Copyright © 2012 shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permi...
html: me.snippets.header, padding: 10, cls: Ext.baseCSSPrefix + 'global-notice-text' }); }, /** * Creates the drop zone container * @return Ext.container.Container */ createDropZone: function() { var me = this; return Ext.create('E...
random_line_split
webpack-manifest-plugin_vx.x.x.js
// flow-typed signature: 03af697d18fe8a7b11299425ad8b778f // flow-typed version: <<STUB>>/webpack-manifest-plugin_v^1.1.0/flow_v0.41.0 /** * This is an autogenerated libdef stub for: * * 'webpack-manifest-plugin' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to...
} declare module 'webpack-manifest-plugin/index.js' { declare module.exports: $Exports<'webpack-manifest-plugin'>; } declare module 'webpack-manifest-plugin/lib/plugin.js' { declare module.exports: $Exports<'webpack-manifest-plugin/lib/plugin'>; } declare module 'webpack-manifest-plugin/spec/fixtures/file-two.js' {...
declare module 'webpack-manifest-plugin/index' { declare module.exports: $Exports<'webpack-manifest-plugin'>;
random_line_split
issue-2631-a.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 ...
pub fn request<T:Copy>(req: &header_map) { let _x = copy *(copy **req.get(&~"METHOD"))[0u]; }
pub type header_map = HashMap<~str, @mut ~[@~str]>; // the unused ty param is necessary so this gets monomorphized
random_line_split
issue-2631-a.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 ...
<T:Copy>(req: &header_map) { let _x = copy *(copy **req.get(&~"METHOD"))[0u]; }
request
identifier_name
issue-2631-a.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 = copy *(copy **req.get(&~"METHOD"))[0u]; }
identifier_body
locale_messages.js
locale_messages = { cloud:{ "id": false, "Id": "序号", "Name": "名称", "Provider": "云厂商", "LastestPartNum": false, "PartOfInstances": false, "Desc": "描述", "Account": "KeyId", "CreateTime": "创建时间", "DeleteTime": false, "Cpu": "CPU", "Ram": "内存", "InstanceType": "实例类型", ...
id: '序号', name: '名称', desc: '描述', biz: false, service_type: '服务类型', docker_image: 'Docker镜像', cluster_id: '隶属集群序号', vm_type: '机型模板', sd_id: '服务发现序号', service_id: '隶属服务序号', tasks: '扩缩容任务', node_count: '节点数量', template_id: '任务模板序号', template_name: '任务模板名称', task...
layout: {
random_line_split
create_taxonomic_profile_from_blast.py
## output file to be written parser.add_argument('-o', '--output_file', type=str, required=True, help='Path where the result file should written' ) ## E-value cutoff to use parser.add_argument('-e', '--eval_cutoff', type=float, required=False, help='Optional E-value cutoff to use.' ) ## Top N hits pe...
cursor.execute("""SELECT scientific_name FROM orgs WHERE tax_id = ?""", (taxon_id,) ) row = cursor.fetchone() if row: return row[0] else: return None def get_taxon_id_by_gi( gi, cursor ): """Attempts to fetch a taxon
random_line_split
create_taxonomic_profile_from_blast.py
0 stats['gi_lookup_fail_count'] = 0 stats['taxon_lookup_success_count'] = 0 stats['taxon_lookup_failure_count'] = 0 for file in blast_files: print("Processing file: ", file) if args.input_format == 'blast_m8' or args.input_format == 'btab': parse_blast_file( file, c, ta...
return None
conditional_block
create_taxonomic_profile_from_blast.py
## output file to be written parser.add_argument('-o', '--output_file', type=str, required=True, help='Path where the result file should written' ) ## E-value cutoff to use parser.add_argument('-e', '--eval_cutoff', type=float, required=False, help='Optional E-value cutoff to use.' ) ## Top N hits pe...
SUBJECT_LABEL_COLUMN_NUM = 1 EVAL_COLUMN_NUM = 10 ALIGN_LEN_COLUMN_NUM = 3 BIT_SCORE_COLUMN_NUM = 11 if format == 'btab': ID_COLUMN_NUM = 0 SUBJECT_LABEL_COLUMN_NUM = 5 EVAL_COLUMN_NUM = 19 current_id = "" current_id_classified = False current_id_match_count = 0...
""" For each query sequence find the top match above the E-val cutoff (if any) which has an NCBI taxonomy assignment. """ if ( not os.path.isfile(file) ): raise Exception("Couldn't find file: " + file) ## presets are for ncbi_m8, for which lines should have 12 columns. they are # 1: Qu...
identifier_body
create_taxonomic_profile_from_blast.py
## output file to be written parser.add_argument('-o', '--output_file', type=str, required=True, help='Path where the result file should written' ) ## E-value cutoff to use parser.add_argument('-e', '--eval_cutoff', type=float, required=False, help='Optional E-value cutoff to use.' ) ## Top N hits pe...
( gi, cursor ): """Attempts to fetch a tax
get_taxon_id_by_gi
identifier_name
DirPlacesQueryBackend.ts
import { Collection } from '../../utilities' import Packet from './Packet' import * as Types from '../types' /** * DirPlacesQueryBackend Packet */ class DirPlacesQueryBackend extends Packet { /** * Packet ID, this value is only unique per-frequency range, see key get * method of Packet, plus the buffer help...
(data = {}) { super(data) } } export default DirPlacesQueryBackend
constructor
identifier_name
DirPlacesQueryBackend.ts
import { Collection } from '../../utilities' import Packet from './Packet' import * as Types from '../types' /** * DirPlacesQueryBackend Packet */ class DirPlacesQueryBackend extends Packet { /** * Packet ID, this value is only unique per-frequency range, see key get * method of Packet, plus the buffer help...
export default DirPlacesQueryBackend
random_line_split
handle.rs
object_id: ObjectId, opcode: u16, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } ...
} enum DispatchAction<D> { Request { object: Object<Data<D>>,
random_line_split
handle.rs
, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> ...
(&self, id: ClientId) -> Result<Credentials, InvalidId> { let client = self.clients.get_client(id)?; Ok(client.get_credentials()) } /// Returns an iterator over all clients connected to the server. pub fn all_clients<'a>(&'a self) -> Box<dyn Iterator<Item = ClientId> + 'a> { Box::ne...
get_client_credentials
identifier_name
handle.rs
, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> ...
/// Retrieve the `ObjectId` for a wayland object given its protocol numerical ID pub fn object_for_protocol_id( &self, client_id: ClientId, interface: &'static Interface, protocol_id: u32, ) -> Result<ObjectId, InvalidId> { let client = self.clients.get_client(clien...
{ let client = self.clients.get_client(client_id)?; Ok(Box::new(client.all_objects())) }
identifier_body
handle.rs
, arguments: SmallVec<[Argument<ObjectId>; 4]>, is_destructor: bool, created_id: Option<ObjectId>, }, Bind { object: ObjectId, client: ClientId, global: GlobalId, handler: Arc<dyn GlobalHandler<D>>, }, } impl<D> Handle<D> { pub(crate) fn new() -> ...
else { let object_id = ObjectId { id: message.sender_id, serial: object.data.serial, interface: object.interface, client_id: client.id.clone(), }; let opcode = mes...
{ if let Some((client, global, object, handler)) = client.handle_registry_request(message, &mut self.registry) { DispatchAction::Bind { client, global, object, handler } } else { continue;...
conditional_block
middleware.py
from django.contrib.auth.models import User from ws.messages import security from ws.models import Participant class PrefetchGroupsMiddleware: """Prefetch the user's groups for use in the requset. We do a lot of group-centric logic - if the user's groups aren't prefetched, then we can easily have n+1 qu...
(self, get_response): self.get_response = get_response def __call__(self, request): # TODO: We check for `password_quality` on every request. We should join that. request.participant = Participant.from_user(request.user) return self.get_response(request) class CustomMessagesMiddle...
__init__
identifier_name
middleware.py
from django.contrib.auth.models import User from ws.messages import security from ws.models import Participant class PrefetchGroupsMiddleware:
We do a lot of group-centric logic - if the user's groups aren't prefetched, then we can easily have n+1 queries. This middleware prevents n+1 queries, at the cost of 1 extra query. This is a slight hack - the proper way to implement this is with a custom authentication backend where we implement t...
"""Prefetch the user's groups for use in the requset.
random_line_split
middleware.py
from django.contrib.auth.models import User from ws.messages import security from ws.models import Participant class PrefetchGroupsMiddleware: """Prefetch the user's groups for use in the requset. We do a lot of group-centric logic - if the user's groups aren't prefetched, then we can easily have n+1 qu...
return self.get_response(request) class ParticipantMiddleware: """Include the user's participant (used in most views)""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # TODO: We check for `password_quality` on every request. We s...
filtered_user = User.objects.filter(pk=request.user.pk) request.user = filtered_user.prefetch_related('groups').get()
conditional_block
middleware.py
from django.contrib.auth.models import User from ws.messages import security from ws.models import Participant class PrefetchGroupsMiddleware: """Prefetch the user's groups for use in the requset. We do a lot of group-centric logic - if the user's groups aren't prefetched, then we can easily have n+1 qu...
def __call__(self, request): # TODO: We check for `password_quality` on every request. We should join that. request.participant = Participant.from_user(request.user) return self.get_response(request) class CustomMessagesMiddleware: """Render some custom messages on every page load. ...
self.get_response = get_response
identifier_body
App.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { Route } from 'react-router'; import { store } from '..'; import { isConfigLoaded, getConfig } from '../modules/config'; import AppBar from './AppBar'; import Dashb...
autoHideDuration={timings.snackbarCloseTimeout} /> ) : null} </div> ); } } } export default connect( state => ({ failed: state.tallessa.getIn(['config', 'failed']), snackbarMessage: state.tallessa.getIn(['ui', 'snackbar']), }), { getConfig, ...
{ return ( <div> <AppBar /> <Drawer /> <MainView> <Route path="/" component={Dashboard} /> <Route path="/stuff" component={StuffList} /> <Route path="/stuff/:itemSlug" component={ItemEditor} /> <Route path="/places" component={P...
conditional_block
App.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { Route } from 'react-router'; import { store } from '..'; import { isConfigLoaded, getConfig } from '../modules/config'; import AppBar from './AppBar'; import Dashb...
extends React.Component { static propTypes = { failed: PropTypes.bool, snackbarMessage: PropTypes.string, getConfig: PropTypes.func.isRequired, } static defaultProps = { failed: false, snackbarMessage: '', } componentDidMount = () => { if (!isConfigLoaded(store.getState())) { ...
App
identifier_name
App.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { Route } from 'react-router'; import { store } from '..'; import { isConfigLoaded, getConfig } from '../modules/config'; import AppBar from './AppBar'; import Dashb...
snackbarMessage: state.tallessa.getIn(['ui', 'snackbar']), }), { getConfig, }, )(App);
state => ({ failed: state.tallessa.getIn(['config', 'failed']),
random_line_split
App.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { Route } from 'react-router'; import { store } from '..'; import { isConfigLoaded, getConfig } from '../modules/config'; import AppBar from './AppBar'; import Dashb...
<SpeedDial /> {snackbarMessage ? ( <Snackbar open message={snackbarMessage} autoHideDuration={timings.snackbarCloseTimeout} /> ) : null} </div> ); } } } export default connect( state => ({ failed...
{ const { failed, snackbarMessage } = this.props; if (failed) { return <FailureDialog />; } else { return ( <div> <AppBar /> <Drawer /> <MainView> <Route path="/" component={Dashboard} /> <Route path="/stuff" component={StuffList} />...
identifier_body
add-user-item.ts
import { MongoClient } from 'mongodb'; import { promisify } from 'util'; import { UserDoc } from '../libs/users';
.then(async (client: MongoClient) => { const db = client.db(); const userdata = db.collection<UserDoc>('users'); // Get all users const userDocs = await userdata.find({}).toArray(); for (const userDoc of userDocs) { const buf = await promisify(crypto.randomBytes)(16); const unsubscribeHash = buf.toS...
import * as crypto from 'crypto'; import config from '../libs/config'; // Connect to database MongoClient.connect(config.mongodb.uri)
random_line_split
ServerConf.py
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, ...
except KeyError as e: print msg % ('version',) try: self.set_organization(conf['organization']) except KeyError as e: print msg % ('organization',) try: self.set_notes(conf['notes']) except KeyError as e: print msg % ('n...
int 'WARNING: ServerConf and AUTOCONFIG_JSON version mismatch!'
conditional_block
ServerConf.py
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, ...
elf): return self._users_conf def set_auth_conf(self, auth_conf): self._auth_conf = auth_conf return self def set_chef_conf(self, chef_conf): self._chef_conf = chef_conf return self def set_ntp_conf(self, ntp_conf): self._ntp_conf = ntp_conf return ...
t_users_conf(s
identifier_name
ServerConf.py
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, ...
def load_data(self, conf): msg = 'ServerConf: Key "%s" not found in the configuration file.' try: v = conf['version'] if v != self.VERSION: print 'WARNING: ServerConf and AUTOCONFIG_JSON version mismatch!' except KeyError as e: print msg % ...
lf._data = {} self.VERSION = '0.2.0' self._data['gem_repo'] = 'http://rubygems.org' self._data['version'] = self.VERSION self._data['organization'] = '' self._chef_conf = ChefConf() self._gcc_conf = GCCConf() self._auth_conf = AuthConf() self._ntp_conf = D...
identifier_body
ServerConf.py
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, ...
""" def __init__(self, decorated): self._decorated = decorated def Instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created...
Limitations: The decorated class cannot be inherited from.
random_line_split
registry.rs
new(), overrides: vec!(), config: config, locked: HashMap::new(), } } pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> { trace!("getting packages; sources={}", self.sources.len()); // TODO: Only call source with package I...
{ self.overrides.push(summary); self }
identifier_body
registry.rs
lists of new packages. It is here that /// sources are updated (e.g. network operations) and overrides are /// handled. /// /// The general idea behind this registry is that it is centered around the /// `SourceMap` structure, contained within which is a mapping of a `SourceId` to /// a `Source`. Each `Source` in the ...
(&self, summary: Summary) -> Summary { let pair = self.locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) }).and_then(|vec| { vec.iter().find(|&&(ref id, _)| id == summary.package_id()) }); // Lock the summary's id if possible let su...
lock
identifier_name
registry.rs
that the underlying source is updated. // // This is basically a long-winded way of saying that we want to know // precisely what the keys of `sources` are, so this is a mapping of key to // what exactly the key is. source_ids: HashMap<SourceId, (SourceId, Kind)>, locked: HashMap<SourceId, Has...
random_line_split
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute; #[allow(non_camel_case_types)] #[derive(Copy, Clone...
{ for bytes in 0..65535 as u16 { let h0 = f16 { bytes: bytes }; let f: f32 = h0.into(); let h1 = f16::from(f); assert_eq!(h0, h1); } }
identifier_body
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute;
} impl PartialEq for f16 { fn eq(self: &f16, other: &f16) -> bool { return self.bytes == other.bytes; } } impl From<f32> for f16 { fn from(f: f32) -> f16 { unsafe { let base_table: *const u16 = transmute(include_bytes!("base_table.bin")); let shift_table: *const u8 ...
#[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] pub struct f16 { pub bytes: u16,
random_line_split
lib.rs
//! # Half-precision conversion for Rust //! This crate uses the fast table-based f32 <-> f16 conversions given in //! "Fast Half Float Conversions" by Jeroen van der Zijp; see //! `ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf`. use std::mem::transmute; #[allow(non_camel_case_types)] #[derive(Copy, Clone...
() { for bytes in 0..65535 as u16 { let h0 = f16 { bytes: bytes }; let f: f32 = h0.into(); let h1 = f16::from(f); assert_eq!(h0, h1); } }
test
identifier_name
buttons.js
var buttons = function(req, res, next) { var request = require('request'); var cheerio = require('cheerio'); var Case = require('case'); // var url = "http://clas.asu.edu"; var url = req.body.page; var parsedResults = []; //testing url argument site buttons casing request(url, function (error, respo...
var text = $(this).text().trim(); var casing = Case.of($(this).text().trim()); if ( (casing == "sentence") || (casing == "header") ){ var passfail = "PASS"; } else { var passfail = "FAIL"; } var testResults = { text: text, casing...
var $ = cheerio.load(html); $('.btn').each(function(i, element){
random_line_split
buttons.js
var buttons = function(req, res, next) { var request = require('request'); var cheerio = require('cheerio'); var Case = require('case'); // var url = "http://clas.asu.edu"; var url = req.body.page; var parsedResults = []; //testing url argument site buttons casing request(url, function (error, respo...
else { var passfail = "FAIL"; } var testResults = { text: text, casing: casing, passfail: passfail }; parsedResults.push(testResults); }); req.pf = parsedResults; next(); }; }); }; module.exports = buttons;
{ var passfail = "PASS"; }
conditional_block
package.py
############################################################################## # Copyright (c) 2013-2017, 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): """libICE - Inter-Client Exchange Library.""" homepage = "http://cgit.freedesktop.org/xorg/lib/libICE" url = "https://www.x.org/archive/individual/lib/libICE-1.0.9.tar.gz" version('1.0.9', '95812d61df8139c7cacc1325a26d5e37') depends_on('xproto', type='build') depends_...
Libice
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2017, 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...
depends_on('util-macros', type='build')
depends_on('xproto', type='build') depends_on('xtrans', type='build') depends_on('pkg-config@0.9.0:', type='build')
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2017, 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...
"""libICE - Inter-Client Exchange Library.""" homepage = "http://cgit.freedesktop.org/xorg/lib/libICE" url = "https://www.x.org/archive/individual/lib/libICE-1.0.9.tar.gz" version('1.0.9', '95812d61df8139c7cacc1325a26d5e37') depends_on('xproto', type='build') depends_on('xtrans', type='build...
identifier_body
conf.rs
PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std::os::raw::...
let res = val * unit as f64; Ok(res as u64) } #[cfg(test)] mod tests { use super::*; #[test] fn test_memval_nospace() { let s = "10"; let res = 10 ; assert_eq!(Ok(10), get_memval(s)); let s = "10kb"; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); ...
{ return Err("Invalid memory unit"); }
conditional_block
conf.rs
PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std::os::raw::...
() { let s = " 10 "; let res = 10 ; assert_eq!(Ok(res), get_memval(s)); let s = "10Kb "; assert_eq!(Ok(res * KILOBYTE), get_memval(s)); let s = "10mb "; assert_eq!(Ok(res * MEGABYTE), get_memval(s)); let s = " 10Gb ...
test_memval_space_end
identifier_name
conf.rs
PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ use std...
let s = CString::new(key).unwrap(); if ConfGet(s.as_ptr(), &mut vptr) != 1 { SCLogDebug!("Failed to find value for key {}", key); return None; } } if vptr.is_null() { return None; } let value = str::from_utf8(unsafe{ CStr::from_ptr(vptr)....
unsafe {
random_line_split
TagsArrayInput.tsx
import React, {forwardRef, useCallback, useImperativeHandle, useMemo, useRef} from 'react' import {FormField} from '@sanity/base/components' import {useId} from '@reach/auto-id' import {TagInput} from '../components/tagInput' import PatchEvent, {set, unset} from '../PatchEvent' import {Props} from './types' export con...
useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus(), })) return ( <FormField level={level} title={type.title} description={type.description} __unstable_presence={presence} inputId={id} __unstable_markers={markers} > <TagInput id={...
[onChange] )
random_line_split
details.rs
With the **Details** view, the output gets formatted into columns, with /// each `Column` object showing some piece of information about the file, /// such as its size, or its permissions. /// /// To do this, the results have to be written to a table, instead of /// displaying each file immediately. Then, the width of...
let name = Cell { text: filename(&file, &self.colours, true), length: file.file_name_width() }; let mut dir = None; if let Some(r) = self.recurse { if file.is_direct...
random_line_split
details.rs
ories /// on top have depth 0. depth: usize, /// Whether this is the last entry in the directory. This flag is used /// when calculating the tree view. last: bool, } impl Row { /// Gets the Unicode display width of the indexed column, if present. If /// not, returns 0. fn column_width...
.len(), } } } } else { Cell::paint(self.colours.punctuation, "-") } } fn render_time(&self, timestamp: f::Time) -> Cell { let date = self.tz.at(LocalDateTime::at(timestamp.0)); let format = if date.year() == se...
conditional_block
details.rs
With the **Details** view, the output gets formatted into columns, with /// each `Column` object showing some piece of information about the file, /// such as its size, or its permissions. /// /// To do this, the results have to be written to a table, instead of /// displaying each file immediately. Then, the width of...
lish()), tz: TimeZone::localtime().unwrap(), users: OSUsers::empty_cache(), colours: colours, current_year: LocalDateTime::now
ic::eng
identifier_name
details.rs
on standard output. pub fn print_table(&self) -> Vec<Cell> { let mut stack = Vec::new(); let mut cells = Vec::new(); // Work out the list of column widths by finding the longest cell for // each column, then formatting each cell in that column to be the // width of that one...
identifier_body
test_static.py
import unittest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from scipy.sparse import csr_matrix from graphs.base import Graph PAIRS = np.array([[0,1],[0,2],[1,1],[2,1],[3,3]]) ADJ = [[0,1,1,0], [0,1,0,0], [0,1,0,0], [0,0,0,1]] class TestStaticConst...
unittest.main()
conditional_block
test_static.py
import unittest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from scipy.sparse import csr_matrix from graphs.base import Graph PAIRS = np.array([[0,1],[0,2],[1,1],[2,1],[3,3]]) ADJ = [[0,1,1,0], [0,1,0,0], [0,1,0,0], [0,0,0,1]] class TestStaticConst...
(self): g = Graph.from_edge_pairs(PAIRS.astype(float)) p = g.pairs() self.assertTrue(np.can_cast(p, PAIRS.dtype, casting='same_kind'), "Expected integral dtype, got %s" % p.dtype) assert_array_equal(p, PAIRS) def test_from_pairs_weighted(self): w = np.array([1,1,0.1,2,1,2,3.1,...
test_from_pairs_floating
identifier_name
test_static.py
import unittest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from scipy.sparse import csr_matrix from graphs.base import Graph PAIRS = np.array([[0,1],[0,2],[1,1],[2,1],[3,3]]) ADJ = [[0,1,1,0], [0,1,0,0], [0,1,0,0], [0,0,0,1]] class TestStaticConst...
self.assertEqual(g.num_vertices(), 10) g = Graph.from_edge_pairs(PAIRS, symmetric=True) self.assertEqual(g.num_edges(), 8) self.assertEqual(g.num_vertices(), 4) def test_from_pairs_empty(self): g = Graph.from_edge_pairs([]) self.assertEqual(g.num_edges(), 0) self.assertEqual(g.num_vertice...
self.assertEqual(g.num_vertices(), 4) g = Graph.from_edge_pairs(PAIRS, num_vertices=10) self.assertEqual(g.num_edges(), 5)
random_line_split
test_static.py
import unittest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from scipy.sparse import csr_matrix from graphs.base import Graph PAIRS = np.array([[0,1],[0,2],[1,1],[2,1],[3,3]]) ADJ = [[0,1,1,0], [0,1,0,0], [0,1,0,0], [0,0,0,1]] class TestStaticConst...
def test_from_pairs_weighted(self): w = np.array([1,1,0.1,2,1,2,3.1,4]) p = [[0,1],[1,2],[2,3],[3,4],[1,0],[2,1],[3,2],[4,3]] expected = [[0,1,0,0,0],[1,0,1,0,0],[0,2,0,0.1,0],[0,0,3.1,0,2],[0,0,0,4,0]] G = Graph.from_edge_pairs(p, weights=w, num_vertices=5) assert_array_almost_equal(G.matrix('d...
g = Graph.from_edge_pairs(PAIRS.astype(float)) p = g.pairs() self.assertTrue(np.can_cast(p, PAIRS.dtype, casting='same_kind'), "Expected integral dtype, got %s" % p.dtype) assert_array_equal(p, PAIRS)
identifier_body
basic.js
var helper = require("../../../helper"); var sqlHelper = require("../../../sql-helper"); var Manager = require("../../../../src/etl/dim/dim-staff-etl-manager"); var instanceManager = null; var should = require("should"); before("#00. connect db", function (done) { Promise.all([helper, sqlHelper]) .then((re...
}); }); it("#01. should success when run etl dim staff", function (done) { instanceManager.run() .then(() => { done(); }) .catch((e) => { console.log(e); done(e); }); });
done(e); })
random_line_split
string_test.js
var primitivemap = require('./../primitivemap') var m = new primitivemap.StringStringMap() m.put('hello', 'world') console.log('hello ' + m.get('hello')) m.put(undefined,undefined) var lookup = {} var deleted = {} for(var i=0;i<100000;++i){ var k = 'key_'+i var v = 'value_'+i+'_'+Math.random() lookup[k] = v m.p...
console.log('ok')
random_line_split
GameScreen.tsx
import { Button, Layout, Text } from "@ui-kitten/components"; import React from "react"; import { FlatList, View, Dimensions } from "react-native"; import { connect, ConnectedProps } from 'react-redux'; import { ThemedSafeAreaView } from "../components/ThemedSafeAreaView"; import { State, actions, Game } from "../store...
class GameScreen extends React.Component<NavigationStackScreenProps & PropsFromRedux, {}>{// & {players: Array<Player>, rounds: Array<Round>, games: Array<string>},{}> { reportResult: (index: -1|0|1) => void = (index) => { this.props.gameResult({winnerIndex: index}) } gameIndex: number = this.props.rounds.l...
{ let prefix = (index+1)+". " return prefix+game.name }
identifier_body
GameScreen.tsx
import { Button, Layout, Text } from "@ui-kitten/components"; import React from "react"; import { FlatList, View, Dimensions } from "react-native"; import { connect, ConnectedProps } from 'react-redux'; import { ThemedSafeAreaView } from "../components/ThemedSafeAreaView"; import { State, actions, Game } from "../store...
(index: number, game: Game){ let prefix = (index+1)+". " return prefix+game.name } class GameScreen extends React.Component<NavigationStackScreenProps & PropsFromRedux, {}>{// & {players: Array<Player>, rounds: Array<Round>, games: Array<string>},{}> { reportResult: (index: -1|0|1) => void = (index) => { thi...
_gameString
identifier_name
GameScreen.tsx
import { Button, Layout, Text } from "@ui-kitten/components"; import React from "react"; import { FlatList, View, Dimensions } from "react-native"; import { connect, ConnectedProps } from 'react-redux'; import { ThemedSafeAreaView } from "../components/ThemedSafeAreaView"; import { State, actions, Game } from "../store...
const connector = connect((state: State) => state, actions) type PropsFromRedux = ConnectedProps<typeof connector> export default connector(GameScreen)
random_line_split
cabi_powerpc.rs
// Copyright 2014-2015 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...
(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ...
struct_ty
identifier_name
cabi_powerpc.rs
// Copyright 2014-2015 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 ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys.iter() { let ty = classify_...
identifier_body
cabi_powerpc.rs
// Copyright 2014-2015 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...
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ...
args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8;
random_line_split
cabi_powerpc.rs
// Copyright 2014-2015 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...
} fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) ...
{ ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) }
conditional_block
detect-rpc_8c.js
var detect_rpc_8c = [
[ "DetectRpcParse", "detect-rpc_8c.html#afa191c3feaef5872722d9bed7c161546", null ], [ "DetectRpcRegister", "detect-rpc_8c.html#a159a5e14280d4a8fcf57568852b6cd06", null ], [ "DetectRpcRegisterTests", "detect-rpc_8c.html#a1c5e786f45529cd36498d6a1d44d8c67", null ], [ "DetectRpcSetup", "detect-rpc_8c.html#a...
[ "MAX_SUBSTRINGS", "detect-rpc_8c.html#a7d9ab03945d9f1a2af62c4bb49206536", null ], [ "PARSE_REGEX", "detect-rpc_8c.html#adcc3158aa6bb4d1bd0ddf953a33f55ec", null ], [ "DetectRpcFree", "detect-rpc_8c.html#acb73d1a55d544fefa4d86d398661e7b8", null ], [ "DetectRpcMatch", "detect-rpc_8c.html#ad98df5a086ab4d0...
random_line_split
popover.d.ts
/// <reference types="react" /> import * as React from "react"; import * as Tether from "tether"; import { AbstractComponent } from "../../common/abstractComponent"; import * as PosUtils from "../../common/position"; import { IProps } from "../../common/props"; import * as TetherUtils from "../../common/tetherUti...
* Prevents the popover from appearing when `true`. * @default false */ isDisabled?: boolean; /** * Enables an invisible overlay beneath the popover that captures clicks and prevents * interaction with the rest of the document until the popover is closed. * This prop is only ...
* The kind of interaction that triggers the display of the popover. * @default PopoverInteractionKind.CLICK */ interactionKind?: PopoverInteractionKind; /**
random_line_split
popover.d.ts
/// <reference types="react" /> import * as React from "react"; import * as Tether from "tether"; import { AbstractComponent } from "../../common/abstractComponent"; import * as PosUtils from "../../common/position"; import { IProps } from "../../common/props"; import * as TetherUtils from "../../common/tetherUti...
extends AbstractComponent<IPopoverProps, IPopoverState> { static defaultProps: IPopoverProps; static displayName: string; /** * DOM element that contains the popover. * When `inline={false}`, this element will be portaled outside the usual DOM flow, * so this reference can be very usef...
Popover
identifier_name
agilentDSA91204A.py
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
"Agilent Infiniium DSA91204A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO91204A') super(agilentDSA91204A, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._digital_channel_count...
identifier_body
agilentDSA91204A.py
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
THE SOFTWARE. """ from .agilent90000 import * class agilentDSA91204A(agilent90000): "Agilent Infiniium DSA91204A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO91204A') super(agilentDSA91204A, self).__init__(*args, **...
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
random_line_split
agilentDSA91204A.py
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
(agilent90000): "Agilent Infiniium DSA91204A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO91204A') super(agilentDSA91204A, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._d...
agilentDSA91204A
identifier_name
UsuarioControle.ts
import {Conexao} from "../dao/Conexao"; import {Usuario} from "../modelo/Usuario"; /** * Created by paulo.rettamozo on 26/03/2017. */ export class UsuarioControle{ public async
(usuario:string, chave : string):Promise<Usuario>{ let usuarioRep = Conexao.getConnection().getRepository(Usuario); let usuarioAutenticado = usuarioRep.createQueryBuilder("usuario") .where("usuario.nome_usuario=:usr",{usr:usuario}) .andWhere("usuario.chave=md5( :senha )",{senha:...
validarAcesso
identifier_name
UsuarioControle.ts
import {Conexao} from "../dao/Conexao"; import {Usuario} from "../modelo/Usuario"; /** * Created by paulo.rettamozo on 26/03/2017. */ export class UsuarioControle{ public async validarAcesso(usuario:string, chave : string):Promise<Usuario>{ let usuarioRep = Conexao.getConnection().getRepository(Usuario...
public async obter(usuario:string):Promise<Usuario>{ let usuarioRep = Conexao.getConnection().getRepository(Usuario); let usuarioAutenticado = usuarioRep.createQueryBuilder("usuario") .innerJoinAndSelect("usuario.status","status") .where("usuario.nome_usuario=:usr",{usr:usu...
{ let usuarioRep = Conexao.getConnection().getRepository(Usuario); let usuarios = usuarioRep.createQueryBuilder("usuario") .getMany(); return usuarios; }
identifier_body
UsuarioControle.ts
import {Conexao} from "../dao/Conexao"; import {Usuario} from "../modelo/Usuario"; /** * Created by paulo.rettamozo on 26/03/2017. */ export class UsuarioControle{ public async validarAcesso(usuario:string, chave : string):Promise<Usuario>{ let usuarioRep = Conexao.getConnection().getRepository(Usuario...
let usuarioRep = Conexao.getConnection().getRepository(Usuario); let usuarios = usuarioRep.createQueryBuilder("usuario") .getMany(); return usuarios; } public async obter(usuario:string):Promise<Usuario>{ let usuarioRep = Conexao.getConnection().getRepositor...
return usuarioAutenticado; } public async obterLista(usuario:string):Promise<Usuario[]>{
random_line_split
update.py
from git import Repo from util import hook, web @hook.command def update(inp, bot=None): repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else: return pull
@hook.command def version(inp, bot=None): repo = Repo() # get origin and fetch it origin = repo.remotes.origin info = origin.fetch() # get objects head = repo.head origin_head = info[0] current_commit = head.commit remote_commit = origin_head.commit if current_commit == remot...
random_line_split
update.py
from git import Repo from util import hook, web @hook.command def update(inp, bot=None): repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else:
@hook.command def version(inp, bot=None): repo = Repo() # get origin and fetch it origin = repo.remotes.origin info = origin.fetch() # get objects head = repo.head origin_head = info[0] current_commit = head.commit remote_commit = origin_head.commit if current_commit == rem...
return pull
conditional_block
update.py
from git import Repo from util import hook, web @hook.command def update(inp, bot=None):
@hook.command def version(inp, bot=None): repo = Repo() # get origin and fetch it origin = repo.remotes.origin info = origin.fetch() # get objects head = repo.head origin_head = info[0] current_commit = head.commit remote_commit = origin_head.commit if current_commit == rem...
repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else: return pull
identifier_body