file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
test_region_info_accessor.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use keys::data_end_key; use kvproto::metapb::Region; use raft::StateRole; use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor}; use raftstore::store::util::{find_peer, new_peer}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread...
#[test] fn test_node_cluster_region_info_accessor() { let mut cluster = new_node_cluster(1, 3); configure_for_merge(&mut cluster); let pd_client = Arc::clone(&cluster.pd_client); pd_client.disable_default_operator(); // Create a RegionInfoAccessor on node 1 let (tx, rx) = channel(); let ...
{ for i in 0..9 { let k = format!("k{}", i).into_bytes(); let v = format!("v{}", i).into_bytes(); cluster.must_put(&k, &v); } let pd_client = Arc::clone(&cluster.pd_client); let init_regions = dump(c); check_region_ranges(&init_regions, &[(&b""[..], &b""[..])]); assert_...
identifier_body
test_region_info_accessor.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use keys::data_end_key; use kvproto::metapb::Region; use raft::StateRole; use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor}; use raftstore::store::util::{find_peer, new_peer}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread...
(regions: &[(Region, StateRole)], ranges: &[(&[u8], &[u8])]) { assert_eq!(regions.len(), ranges.len()); regions .iter() .zip(ranges.iter()) .for_each(|((r, _), (start_key, end_key))| { assert_eq!(r.get_start_key(), *start_key); assert_eq!(r.get_end_key(), *end_key...
check_region_ranges
identifier_name
test_region_info_accessor.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use keys::data_end_key; use kvproto::metapb::Region; use raft::StateRole; use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor}; use raftstore::store::util::{find_peer, new_peer}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread...
thread::sleep(Duration::from_millis(20)); } check_region_ranges( &regions_after_removing, &[(&b""[..], &b"k1"[..]), (b"k4", b"")], ); } #[test] fn test_node_cluster_region_info_accessor() { let mut cluster = new_node_cluster(1, 3); configure_for_merge(&mut cluster); le...
{ break; }
conditional_block
test_region_info_accessor.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use keys::data_end_key; use kvproto::metapb::Region; use raft::StateRole; use raftstore::coprocessor::{RegionInfo, RegionInfoAccessor}; use raftstore::store::util::{find_peer, new_peer}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread...
drop(cluster); c.stop(); }
random_line_split
admin_list.py
from __future__ import unicode_literals import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.util import (lookup_field, display_for_field, display_for_value, label_for_field) from django.contrib.admin.views.main import (ALL_VAR, EMPTY_CHANGELIST_...
else: ON_EACH_SIDE = 3 ON_ENDS = 2 # If there are 10 or fewer pages, display links to every page. # Otherwise, do some fancy if paginator.num_pages <= 10: page_range = range(paginator.num_pages) else: # Insert "smart" pagination links, so tha...
page_range = []
conditional_block
admin_list.py
from __future__ import unicode_literals import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.util import (lookup_field, display_for_field, display_for_value, label_for_field) from django.contrib.admin.views.main import (ALL_VAR, EMPTY_CHANGELIST_...
year_lookup = cl.params.get(year_field) month_lookup = cl.params.get(month_field) day_lookup = cl.params.get(day_field) link = lambda d: cl.get_query_string(d, [field_generic]) if not (year_lookup or month_lookup or day_lookup): # select appropriate start level ...
month_field = '%s__month' % field_name day_field = '%s__day' % field_name field_generic = '%s__' % field_name
random_line_split
admin_list.py
from __future__ import unicode_literals import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.util import (lookup_field, display_for_field, display_for_value, label_for_field) from django.contrib.admin.views.main import (ALL_VAR, EMPTY_CHANGELIST_...
def _boolean_icon(field_val): icon_url = static('admin/img/icon-%s.gif' % {True: 'yes', False: 'no', None: 'unknown'}[field_val]) return format_html('<img src="{0}" alt="{1}" />', icon_url, field_val) def items_for_result(cl, result, form): """ Generates the actual list of data....
""" Generates the list column headers. """ ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field(field_name, cl.model, model_admin = cl.model_admin, return_attr = True ) if at...
identifier_body
admin_list.py
from __future__ import unicode_literals import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.util import (lookup_field, display_for_field, display_for_value, label_for_field) from django.contrib.admin.views.main import (ALL_VAR, EMPTY_CHANGELIST_...
(self, form, *items): self.form = form super(ResultList, self).__init__(*items) def results(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): yield ResultList(form, items_for_result(cl, res, form)) else: for res in cl.result_list: ...
__init__
identifier_name
codemap.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 lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); let fm = (*self.files.borrow())[idx].clone(); let offset = bpos - fm.start_pos; FileMapAndBytePos {fm: fm, pos: offset} } /// Converts an absolute BytePos to a C...
{ for fm in self.files.borrow().iter() { if filename == fm.name { return fm.clone(); } } panic!("asking for {} which we don't know about", filename); }
identifier_body
codemap.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 ...
<D: Decoder>(_d: &mut D) -> Result<Span, D::Error> { Ok(DUMMY_SP) } } pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> { respan(mk_sp(lo, hi), t) } pub fn respan<T>(sp: Span, t: T) -> Spanned<T> { Spanned {node: t, span: sp} } pub fn dummy_spanned<T>(t: T) -> Spanned<T> { respa...
decode
identifier_name
codemap.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(loc2.line, 1); assert_eq!(loc2.col, CharPos(0)); } fn init_code_map_mbc() -> CodeMap { let cm = CodeMap::new(); // € is a three byte utf8 char. let fm1 = cm.new_filemap("blork.rs".to_string(), "fir€st €€€€ line.\nsecond l...
let loc2 = cm.lookup_char_pos(BytePos(24)); assert_eq!(loc2.file.name, "blork2.rs");
random_line_split
restaurant_oper.py
#!/usr/bin/env python #-*- encoding:utf-8 -*- import json from datetime import datetime from bottle import route, mako_template as template, redirect, request, response, get, post from bottle import static_file, view #为了不经过controller直接返回诸如html,css等静态文件引入 from model.documents import * from setting import * DATE_FORM...
em = Restaurant.objects(id = id)[0] data = { 'item': item } return template('views/system/item/edit', data = data, site_opt = site_opt)
params.get('address') telno = request.params.get('telno') lat = request.params.get('lat') lon = request.params.get('lon') print 'modify item=====%s, %s, %s, %s' % (id, name, address, telno) Restaurant.objects(id=id).update(set__name = unicode(name, 'utf8'), set__address = address, set__telno = unicode(telno, 'utf...
identifier_body
restaurant_oper.py
#!/usr/bin/env python #-*- encoding:utf-8 -*- import json from datetime import datetime from bottle import route, mako_template as template, redirect, request, response, get, post from bottle import static_file, view #为了不经过controller直接返回诸如html,css等静态文件引入 from model.documents import * from setting import * DATE_FORM...
#request.params可以同时获取到GET或者POST方法传入的参数 name = request.params.get('name') address = request.params.get('address') telno = request.params.get('telno') lat = request.params.get('lat') lon = request.params.get('lon') item = Restaurant(name=unicode(name, 'utf8'), address=unicode(address, 'utf8'), telno=telno, lat = ...
@route('/add_item', method = 'POST') def add_item(): DATE_FORMAT = '%Y%m%d%H%M%S' innerName = 'attr_%s' % datetime.now().strftime(DATE_FORMAT)
random_line_split
restaurant_oper.py
#!/usr/bin/env python #-*- encoding:utf-8 -*- import json from datetime import datetime from bottle import route, mako_template as template, redirect, request, response, get, post from bottle import static_file, view #为了不经过controller直接返回诸如html,css等静态文件引入 from model.documents import * from setting import * DATE_FORM...
'item': item } return template('views/system/item/edit', data = data, site_opt = site_opt)
[0] data = {
identifier_name
RegulatingControl.py
# Copyright (C) 2010-2011 Richard Lincoln # # 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 # rights to use, copy, modify, merge, publish...
def removeRegulatingCondEq(self, *RegulatingCondEq): for obj in RegulatingCondEq: obj.RegulatingControl = None def getTerminal(self): """The terminal associated with this regulating control. """ return self._Terminal def setTerminal(self, value): if sel...
def addRegulatingCondEq(self, *RegulatingCondEq): for obj in RegulatingCondEq: obj.RegulatingControl = self
random_line_split
RegulatingControl.py
# Copyright (C) 2010-2011 Richard Lincoln # # 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 # rights to use, copy, modify, merge, publish...
obj.RegulatingControl = None
conditional_block
RegulatingControl.py
# Copyright (C) 2010-2011 Richard Lincoln # # 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 # rights to use, copy, modify, merge, publish...
def setRegulatingCondEq(self, value): for x in self._RegulatingCondEq: x.RegulatingControl = None for y in value: y._RegulatingControl = self self._RegulatingCondEq = value RegulatingCondEq = property(getRegulatingCondEq, setRegulatingCondEq) def addRegula...
"""The equipment that participates in this regulating control scheme. """ return self._RegulatingCondEq
identifier_body
RegulatingControl.py
# Copyright (C) 2010-2011 Richard Lincoln # # 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 # rights to use, copy, modify, merge, publish...
(self, *RegulatingCondEq): for obj in RegulatingCondEq: obj.RegulatingControl = None def getTerminal(self): """The terminal associated with this regulating control. """ return self._Terminal def setTerminal(self, value): if self._Terminal is not None: ...
removeRegulatingCondEq
identifier_name
spamcan1.py
#!/usr/bin/env python ############################################################################### # Copyright (C) 1994 - 2013, Performance Dynamics Company # # # # This software is licensed as described in the file COPY...
# good agreement with monitored queue lengths. import pdq # Measured performance parameters cpusPerServer = 4 emailThruput = 2376 # emails per hour scannerTime = 6.0 # seconds per email pdq.Init("Spam Farm Model") # Timebase is SECONDS ... nstreams = pdq.CreateOpen("Email", float(emailThruput)/3600) nnodes = ...
random_line_split
navigation-instruction.ts
import core from 'core-js'; export class
{ public fragment; public queryString; public params; public queryParams; public config; public lifecycleArgs; public viewPortInstructions; constructor(fragment, queryString, params, queryParams, config, parentInstruction) { const allParams = Object.assign({}, queryParams, params); this.fragme...
NavigationInstruction
identifier_name
navigation-instruction.ts
import core from 'core-js'; export class NavigationInstruction { public fragment; public queryString; public params; public queryParams; public config; public lifecycleArgs; public viewPortInstructions; constructor(fragment, queryString, params, queryParams, config, parentInstruction) { const allPa...
return this.fragment.substr(0, this.fragment.lastIndexOf(path)); } }
{ return this.fragment; }
conditional_block
navigation-instruction.ts
import core from 'core-js'; export class NavigationInstruction { public fragment; public queryString; public params; public queryParams; public config; public lifecycleArgs; public viewPortInstructions; constructor(fragment, queryString, params, queryParams, config, parentInstruction) { const allPa...
} getWildCardName() { var wildcardIndex = this.config.route.lastIndexOf('*'); return this.config.route.substr(wildcardIndex + 1); } getWildcardPath() { var wildcardName = this.getWildCardName(), path = this.params[wildcardName]; if (this.queryString) { path += "?" + this.querySt...
random_line_split
navigation-instruction.ts
import core from 'core-js'; export class NavigationInstruction { public fragment; public queryString; public params; public queryParams; public config; public lifecycleArgs; public viewPortInstructions; constructor(fragment, queryString, params, queryParams, config, parentInstruction) { const allPa...
}
{ if (!this.params) { return this.fragment; } var wildcardName = this.getWildCardName(), path = this.params[wildcardName]; if (!path) { return this.fragment; } return this.fragment.substr(0, this.fragment.lastIndexOf(path)); }
identifier_body
server.ts
import { Services } from './services/services' var app = require('./app'); var debug = require('debug'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = 3000; app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen ...
/** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); }
{ if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.ex...
identifier_body
server.ts
import { Services } from './services/services' var app = require('./app'); var debug = require('debug'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = 3000; app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen ...
(error:any) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); ...
onError
identifier_name
server.ts
import { Services } from './services/services' var app = require('./app'); var debug = require('debug'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = 3000; app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen ...
case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event....
// handle specific listen errors with friendly messages switch (error.code) {
random_line_split
language_tools.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * 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 sou...
var onChangeMode = function(e, editor) { loadSnippetsForMode(editor.session.$mode); }; var loadSnippetsForMode = function(mode) { var id = mode.$id; if (!snippetManager.files) snippetManager.files = {}; loadSnippetFile(id); if (mode.modes) mode.modes.forEach(loadSnippetsForMode); }...
random_line_split
language_tools.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * 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 sou...
var doLiveAutocomplete = function(e) { var editor = e.editor; var text = e.args || ""; var hasCompleter = editor.completer && editor.completer.activated; // We don't want to autocomplete with no prefix if (e.command.name === "backspace") { if (hasCompleter && !getCompletionPrefix(editor...
{ var pos = editor.getCursorPosition(); var line = editor.session.getLine(pos.row); var prefix = util.retrievePrecedingIdentifier(line, pos.column); // Try to find custom prefixes on the completers editor.completers.forEach(function(completer) { if (completer.identifierRegexps) { ...
identifier_body
language_tools.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * 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 sou...
(editor) { var pos = editor.getCursorPosition(); var line = editor.session.getLine(pos.row); var prefix = util.retrievePrecedingIdentifier(line, pos.column); // Try to find custom prefixes on the completers editor.completers.forEach(function(completer) { if (completer.identifierRegexps) { ...
getCompletionPrefix
identifier_name
dynamic.to.top.min.js
/* * Dynamic To Top Plugin * http://www.mattvarone.com * * By Matt Varone * @sksmatt * */ var mv_dynamic_to_top;(function($,mv_dynamic_to_top){jQuery.fn.DynamicToTop=function(options){var defaults={text:mv_dynamic_to_top.text,min:parseInt(mv_dynamic_to_top.min,10),fade_in:600,fade_out:400,speed:parseInt(mv_dynam...
});};$('body').DynamicToTop();})(jQuery,mv_dynamic_to_top);
{$toTop.fadeOut(settings.fade_out);}
conditional_block
dynamic.to.top.min.js
/*
* * By Matt Varone * @sksmatt * */ var mv_dynamic_to_top;(function($,mv_dynamic_to_top){jQuery.fn.DynamicToTop=function(options){var defaults={text:mv_dynamic_to_top.text,min:parseInt(mv_dynamic_to_top.min,10),fade_in:600,fade_out:400,speed:parseInt(mv_dynamic_to_top.speed,10),easing:mv_dynamic_to_top.easing,versi...
* Dynamic To Top Plugin * http://www.mattvarone.com
random_line_split
index.d.ts
// Type definitions for pty.js 0.2 // Project: https://github.com/chjj/pty.js // Definitions by: Vadim Macagon <https://github.com/enlight> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// <reference types="node" /> /** Options that can be used when creating a new pse...
/** Windows-only. */ export function kill(pid: number): void; export function resize(fd: number, cols: number, rows: number): void; }
export function startProcess( pid: number, file: string, cmdline: string, env: string[], cwd: string ): void;
random_line_split
index.d.ts
// Type definitions for pty.js 0.2 // Project: https://github.com/chjj/pty.js // Definitions by: Vadim Macagon <https://github.com/enlight> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// <reference types="node" /> /** Options that can be used when creating a new pse...
{ /** Read-only name of the terminal. */ name: string; /** Read-only number of columns in the terminal. */ cols: number; /** Read-only number of rows in the terminal. */ rows: number; /** * Read-only identifier of the spawned process associated with the slave end of the * pseu...
Terminal
identifier_name
dictio.py
#!/usr/bin/python #Covered by GPL V2.0 from encoders import * from payloads import * # generate_dictio evolution class dictionary: def __init__(self,dicc=None): if dicc: self.__payload=dicc.getpayload()
self.__payload=payload() self.__encoder = [lambda x: encoder().encode(x)] self.restart() def count (self): return self.__payload.count() * len(self.__encoder) def setpayload(self,payl): self.__payload = payl self.restart() def setencoder(self,encd): self.__encoder=encd self.generator = self.gen(...
self.__encoder=dicc.getencoder() else:
random_line_split
dictio.py
#!/usr/bin/python #Covered by GPL V2.0 from encoders import * from payloads import * # generate_dictio evolution class dictionary: def __init__(self,dicc=None): if dicc: self.__payload=dicc.getpayload() self.__encoder=dicc.getencoder() else: self.__payload=payload() self.__encoder = [lambda x: en...
(self): return self.__encoder def generate_all(self): dicc=[] for i in self.__payload: dicc.append(self.__encoder.encode(i)) return dicc def __iter__(self): self.restart() return self def gen(self): while 1: pl=self.iter.next() for encode in self.__encoder: yield encode(pl) def ne...
getencoder
identifier_name
dictio.py
#!/usr/bin/python #Covered by GPL V2.0 from encoders import * from payloads import * # generate_dictio evolution class dictionary: def __init__(self,dicc=None): if dicc: self.__payload=dicc.getpayload() self.__encoder=dicc.getencoder() else: self.__payload=payload() self.__encoder = [lambda x: en...
def getencoder (self): return self.__encoder def generate_all(self): dicc=[] for i in self.__payload: dicc.append(self.__encoder.encode(i)) return dicc def __iter__(self): self.restart() return self def gen(self): while 1: pl=self.iter.next() for encode in self.__encoder: yield e...
return self.__payload
identifier_body
dictio.py
#!/usr/bin/python #Covered by GPL V2.0 from encoders import * from payloads import * # generate_dictio evolution class dictionary: def __init__(self,dicc=None): if dicc: self.__payload=dicc.getpayload() self.__encoder=dicc.getencoder() else: self.__payload=payload() self.__encoder = [lambda x: en...
return dicc def __iter__(self): self.restart() return self def gen(self): while 1: pl=self.iter.next() for encode in self.__encoder: yield encode(pl) def next(self): return self.generator.next() def restart(self): self.iter=self.__payload.__iter__() self.generator = self.gen()
dicc.append(self.__encoder.encode(i))
conditional_block
carousels.js
$(document).ready(function(){ $('#bx1').bxSlider(); $('#bx2').bxSlider({ hideControlOnEnd: true, captions: true, pager: false }) $('#bx3').bxSlider({ hideControlOnEnd: true, minSlides: 3, maxSlides: 3, slideWidth: 360, slide...
$('#bx4').bxSlider({ hideControlOnEnd: true, minSlides: 4, maxSlides: 4, slideWidth: 360, slideMargin: 10, pager: false, nextSelector: '#bx-next4', prevSelector: '#bx-prev4', nextText: '>', prevText: '<', }) $('#bx...
})
random_line_split
test_nmount.rs
use crate::*; use nix::{ errno::Errno, mount::{MntFlags, Nmount, unmount} }; use std::{ ffi::CString,
path::Path }; use tempfile::tempdir; #[test] fn ok() { require_mount!("nullfs"); let mountpoint = tempdir().unwrap(); let target = tempdir().unwrap(); let _sentry = File::create(target.path().join("sentry")).unwrap(); let fstype = CString::new("fstype").unwrap(); let nullfs = CString::new...
fs::File,
random_line_split
test_nmount.rs
use crate::*; use nix::{ errno::Errno, mount::{MntFlags, Nmount, unmount} }; use std::{ ffi::CString, fs::File, path::Path }; use tempfile::tempdir; #[test] fn
() { require_mount!("nullfs"); let mountpoint = tempdir().unwrap(); let target = tempdir().unwrap(); let _sentry = File::create(target.path().join("sentry")).unwrap(); let fstype = CString::new("fstype").unwrap(); let nullfs = CString::new("nullfs").unwrap(); Nmount::new() .str_opt...
ok
identifier_name
test_nmount.rs
use crate::*; use nix::{ errno::Errno, mount::{MntFlags, Nmount, unmount} }; use std::{ ffi::CString, fs::File, path::Path }; use tempfile::tempdir; #[test] fn ok() { require_mount!("nullfs"); let mountpoint = tempdir().unwrap(); let target = tempdir().unwrap(); let _sentry = File:...
{ let mountpoint = tempdir().unwrap(); let target = tempdir().unwrap(); let _sentry = File::create(target.path().join("sentry")).unwrap(); let e = Nmount::new() .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) .str_opt_owned("target", target.path().to_str().unwrap()) ...
identifier_body
prepareProject.ts
import { addTypenameIfAbsent } from "./addTypenameToSelectionSet"; import fs from "fs" import {parse, visit, print, OperationDefinitionNode, FragmentDefinitionNode, FragmentSpreadNode, DocumentNode} from "graphql" import { removeClientFields } from "./removeClientFields"; /** * Take a whole bunch of GraphQL in one bi...
export default prepareProject
{ var removeDefinitionNode = function(node: FragmentDefinitionNode | OperationDefinitionNode) { if (node.name && definitionNames.indexOf(node.name.value) === -1) { return null } else { return undefined } } var visitor = { OperationDefinition: removeDefinitionNode, FragmentDefinitio...
identifier_body
prepareProject.ts
import { addTypenameIfAbsent } from "./addTypenameToSelectionSet"; import fs from "fs" import {parse, visit, print, OperationDefinitionNode, FragmentDefinitionNode, FragmentSpreadNode, DocumentNode} from "graphql" import { removeClientFields } from "./removeClientFields"; /** * Take a whole bunch of GraphQL in one bi...
} var visitor = { OperationDefinition: { enter: function(node: OperationDefinitionNode) { enterDefinition(node) node.name && allOperationNames.push(node.name.value) }, }, FragmentDefinition: { enter: enterDefinition, }, // When entering a fragment spread, regi...
{ var definitionName = node.name.value if (definitionDependencyNames[definitionName]) { throw new Error("Found duplicate definition name: " + definitionName + ", fragment & operation names must be unique to sync") } else { currentDependencyNames = definitionDependencyNames[definitionNa...
conditional_block
prepareProject.ts
import { addTypenameIfAbsent } from "./addTypenameToSelectionSet"; import fs from "fs" import {parse, visit, print, OperationDefinitionNode, FragmentDefinitionNode, FragmentSpreadNode, DocumentNode} from "graphql" import { removeClientFields } from "./removeClientFields"; /** * Take a whole bunch of GraphQL in one bi...
(filenames: string[], addTypename: boolean) { if(!filenames.length) { return []; } var allGraphQL = "" filenames.forEach(function(filename) { allGraphQL += fs.readFileSync(filename) }) var ast = parse(allGraphQL) // This will contain { name: [name, name] } pairs var definitionDependencyNames: {[key:...
prepareProject
identifier_name
prepareProject.ts
import { addTypenameIfAbsent } from "./addTypenameToSelectionSet"; import fs from "fs" import {parse, visit, print, OperationDefinitionNode, FragmentDefinitionNode, FragmentSpreadNode, DocumentNode} from "graphql" import { removeClientFields } from "./removeClientFields"; /** * Take a whole bunch of GraphQL in one bi...
export default prepareProject
random_line_split
x86_64.rs
#![allow(unused_imports)] use core::intrinsics; // NOTE These functions are implemented using assembly because they using a custom // calling convention which can't be implemented using a normal Rust function
// NOTE These functions are never mangled as they are not tested against compiler-rt // and mangling ___chkstk would break the `jmp ___chkstk` instruction in __alloca #[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))] #[naked] #[no_mangle] pub unsafe fn ___chkstk_ms() { asm!(" push ...
random_line_split
x86_64.rs
#![allow(unused_imports)] use core::intrinsics; // NOTE These functions are implemented using assembly because they using a custom // calling convention which can't be implemented using a normal Rust function // NOTE These functions are never mangled as they are not tested against compiler-rt // and mangling ___chks...
#[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))] #[naked] #[no_mangle] pub unsafe fn __alloca() { asm!("mov %rcx,%rax // x64 _alloca is a normal function with parameter in rcx jmp ___chkstk // Jump to ___chkstk since fallthrough may be unreliable" ::: "memory" : ...
{ asm!(" push %rcx push %rax cmp $$0x1000,%rax lea 24(%rsp),%rcx jb 1f 2: sub $$0x1000,%rcx test %rcx,(%rcx) sub $$0x1000,%rax cmp $$0x1000,%rax ja 2b 1: sub %rax,%rcx test %rcx,...
identifier_body
x86_64.rs
#![allow(unused_imports)] use core::intrinsics; // NOTE These functions are implemented using assembly because they using a custom // calling convention which can't be implemented using a normal Rust function // NOTE These functions are never mangled as they are not tested against compiler-rt // and mangling ___chks...
() { asm!("mov %rcx,%rax // x64 _alloca is a normal function with parameter in rcx jmp ___chkstk // Jump to ___chkstk since fallthrough may be unreliable" ::: "memory" : "volatile"); intrinsics::unreachable(); } #[cfg(all(windows, target_env = "gnu", not(feature = "mangled-names")))]...
__alloca
identifier_name
tile.js
var Tile = function (type, x, y) { this.type = type; this.tint = 0; this.hover = false; this.isAllowed = undefined; this.isAllowedForBeat = undefined; this.x = x; this.y = y; this.graphic = new fabric.Rect({ left: Tile.size * x, top: Tile.size * y, fill: type === Tile.TileType.NONPLAYABLE ?...
} }); this.isAllowedForBeat = true; }; Tile.prototype.clearHighlights = function() { var graphic = this.graphic; fabric.util.animateColor(this.graphic.fill, Tile.ColorPlayable, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll(); } }); this.isAll...
fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowedForBeat, colorAnimationTime, { onChange: function(val) { graphic.setFill(val); canvas.renderAll();
random_line_split
tile.js
var Tile = function (type, x, y) { this.type = type; this.tint = 0; this.hover = false; this.isAllowed = undefined; this.isAllowedForBeat = undefined; this.x = x; this.y = y; this.graphic = new fabric.Rect({ left: Tile.size * x, top: Tile.size * y, fill: type === Tile.TileType.NONPLAYABLE ?...
};
{ //or unselect man, if clicked on empty tile board.unselect(); }
conditional_block
test_api.py
from __future__ import absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def
(self): self.da = deviantart.Api(CLIENT_ID, CLIENT_SECRET) @optional(CLIENT_ID == "", mock_response('user_profile_devart')) def test_get_user(self): user = self.da.get_user("devart") self.assertEqual("devart", user.username) self.assertEqual("devart", repr(user)) @optional(...
setUp
identifier_name
test_api.py
from __future__ import absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def setUp(self):
@optional(CLIENT_ID == "", mock_response('user_profile_devart')) def test_get_user(self): user = self.da.get_user("devart") self.assertEqual("devart", user.username) self.assertEqual("devart", repr(user)) @optional(CLIENT_ID == "", mock_response('deviation')) def test_get_devi...
self.da = deviantart.Api(CLIENT_ID, CLIENT_SECRET)
identifier_body
test_api.py
from __future__ import absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def setUp(self): self.da = deviantart.Api(C...
self.assertEqual("234546F5-C9D1-A9B1-D823-47C4E3D2DB95", deviation.deviationid) self.assertEqual("234546F5-C9D1-A9B1-D823-47C4E3D2DB95", repr(deviation)) @optional(CLIENT_ID == "", mock_response('comments_siblings')) def test_get_comment(self): comments = self.da.get_comments("siblings"...
self.assertEqual("devart", repr(user)) @optional(CLIENT_ID == "", mock_response('deviation')) def test_get_deviation(self): deviation = self.da.get_deviation("234546F5-C9D1-A9B1-D823-47C4E3D2DB95")
random_line_split
commands.ts
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // ***************************...
else { return cy .get('@Editable') .children() .then($el => { const el = $el.get(0) range.setStart(el, 0) range.setEnd(el, 0) return cy.getEditor().then(editor => { ...
{ range.setStart(el, 0) range.setEnd(el, 0) return cy.getEditor().then(editor => { editor.selection.saveRange(range) return editor }) }
conditional_block
commands.ts
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // ***************************...
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) Cypress.Commands.add('getByClass', (selector, ...args) => { return cy.get(`.w-e-${selector}`, ...args) }) Cypress.Commands.add('getEditor', () => { return cy.window().its('editor') }) Cypress.Commands.add('saveRange', (el?: HTMLElem...
// -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command --
random_line_split
feed_parse_extractSecretchateauWordpressCom.py
def extractSecretchateauWordpressCom(item): ''' Parser for 'secretchateau.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None titlemap = [ ('GRMHCD ', 'Grim Reaper Makes His C-Debut', 'trans...
if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap:
random_line_split
feed_parse_extractSecretchateauWordpressCom.py
def extractSecretchateauWordpressCom(item):
''' Parser for 'secretchateau.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None titlemap = [ ('GRMHCD ', 'Grim Reaper Makes His C-Debut', 'translated'), ('Tensei Shoujo no Rirekisho', 'T...
identifier_body
feed_parse_extractSecretchateauWordpressCom.py
def
(item): ''' Parser for 'secretchateau.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None titlemap = [ ('GRMHCD ', 'Grim Reaper Makes His C-Debut', 'translated'), ('Tensei Shoujo no Rireki...
extractSecretchateauWordpressCom
identifier_name
feed_parse_extractSecretchateauWordpressCom.py
def extractSecretchateauWordpressCom(item): ''' Parser for 'secretchateau.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None titlemap = [ ('GRMHCD ', 'Grim Reaper Makes His C-Debut', 'trans...
return False
if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
conditional_block
Slice.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::raw::Slice; use core::raw::Repr; // pub unsafe trait Repr<T> { // /// This function "unwraps" a rust value (without consuming it) into its raw // /// struct representation. This can be used to read/write different valu...
() { let slice: &[T] = &[1, 2, 3, 4]; let repr: Slice<T> = slice.repr(); assert_eq!(repr.len, 4); } #[test] fn slice_test2 () { let slice: &[T] = &[1, 2, 3, 4]; let repr: Slice<T> = slice.repr(); let copy: &[T] = slice; let copy_repr: Slice<T> = copy.repr(); assert_eq!(copy_repr.data, repr.data...
slice_test1
identifier_name
Slice.rs
#[cfg(test)] mod tests { use core::raw::Slice; use core::raw::Repr; // pub unsafe trait Repr<T> { // /// This function "unwraps" a rust value (without consuming it) into its raw // /// struct representation. This can be used to read/write different values // /// for the struct. This...
#![feature(core)] extern crate core;
random_line_split
Slice.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::raw::Slice; use core::raw::Repr; // pub unsafe trait Repr<T> { // /// This function "unwraps" a rust value (without consuming it) into its raw // /// struct representation. This can be used to read/write different valu...
}
{ let slice: &[T] = &[1, 2, 3, 4]; let repr: Slice<T> = slice.repr(); let copy: &[T] = slice; let copy_repr: Slice<T> = copy.repr(); assert_eq!(copy_repr.data, repr.data); assert_eq!(copy_repr.len, repr.len); }
identifier_body
yelp_polarity_test.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for yelp dataset module.""" from tensorflow_datasets import testing from tensorflow_datasets.text import yelp_polarity class Yelp...
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
yelp_polarity_test.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appl...
testing.test_main()
conditional_block
yelp_polarity_test.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appl...
(testing.DatasetBuilderTestCase): DATASET_CLASS = yelp_polarity.YelpPolarityReviews SPLITS = { "train": 2, "test": 2, } if __name__ == "__main__": testing.test_main()
YelpPolarityReviewsTest
identifier_name
yelp_polarity_test.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appl...
if __name__ == "__main__": testing.test_main()
DATASET_CLASS = yelp_polarity.YelpPolarityReviews SPLITS = { "train": 2, "test": 2, }
identifier_body
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::AsRawFd; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr =...
} _ => panic!("nope"), } assert_eq!(addr.to_str(), "127.0.0.1:3000"); let inet = addr.to_std(); assert_eq!(actual, inet); } #[test] pub fn test_path_to_sock_addr() { let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [i8] =...
assert_eq!(addr.sin_addr.s_addr, ip.to_be()); assert_eq!(addr.sin_port, port.to_be());
random_line_split
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::AsRawFd; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr =...
() { use std::net::TcpListener; let addr = localhost(); let sock = TcpListener::bind(&*addr).unwrap(); let res = getsockname(sock.as_raw_fd()).unwrap(); assert_eq!(addr, res.to_str()); }
test_getsockname
identifier_name
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::AsRawFd; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr =...
{ use std::net::TcpListener; let addr = localhost(); let sock = TcpListener::bind(&*addr).unwrap(); let res = getsockname(sock.as_raw_fd()).unwrap(); assert_eq!(addr, res.to_str()); }
identifier_body
async.ts
import { assert } from 'utils/assert'; type AsyncIterable<T> = Iterable<T | Promise<T>> | Promise<Iterable<T | Promise<T>>>; type AsyncForEachIteratee<T> = ( value: T, index: number, arrayLength: number, ) => unknown | Promise<unknown>; /** * Native port of Bluebird's Promise.prototype.each. Accepts an iterable (...
} } enqueueNextPromises(); }); } export async function asyncMapSeries<T, R>( iterable: AsyncIterable<T>, iteratee: AsyncMapIteratee<T, R>, ): Promise<R[]> { return asyncMap(iterable, iteratee, { concurrency: 1 }); }
{ const index = cursor; const next = resolvedList[index]; cursor++; pending++; Promise.resolve(next) .then((value) => { return iteratee(value, index, resolvedLength); }) .then( // eslint-disable-next-line no-loop-func (value) => { pending--; ...
conditional_block
async.ts
import { assert } from 'utils/assert'; type AsyncIterable<T> = Iterable<T | Promise<T>> | Promise<Iterable<T | Promise<T>>>; type AsyncForEachIteratee<T> = ( value: T, index: number, arrayLength: number, ) => unknown | Promise<unknown>; /** * Native port of Bluebird's Promise.prototype.each. Accepts an iterable (...
): Promise<T[]> { const results: T[] = []; const resolvedList = Array.from(await iterable); const resolvedLength = resolvedList.length; for (let i = 0; i < resolvedList.length; i++) { // eslint-disable-next-line no-await-in-loop const value = await resolvedList[i]; results.push(value); // eslint-disable-nex...
random_line_split
async.ts
import { assert } from 'utils/assert'; type AsyncIterable<T> = Iterable<T | Promise<T>> | Promise<Iterable<T | Promise<T>>>; type AsyncForEachIteratee<T> = ( value: T, index: number, arrayLength: number, ) => unknown | Promise<unknown>; /** * Native port of Bluebird's Promise.prototype.each. Accepts an iterable (...
<T, R>( iterable: AsyncIterable<T>, iteratee: AsyncMapIteratee<T, R>, options?: AsyncMapOptions, ): Promise<R[]> { const concurrency = options?.concurrency ?? Infinity; const resolvedList = Array.from(await iterable); const resolvedLength = resolvedList.length; assert(concurrency > 0); return new Promise((resol...
asyncMap
identifier_name
async.ts
import { assert } from 'utils/assert'; type AsyncIterable<T> = Iterable<T | Promise<T>> | Promise<Iterable<T | Promise<T>>>; type AsyncForEachIteratee<T> = ( value: T, index: number, arrayLength: number, ) => unknown | Promise<unknown>; /** * Native port of Bluebird's Promise.prototype.each. Accepts an iterable (...
export async function asyncMapSeries<T, R>( iterable: AsyncIterable<T>, iteratee: AsyncMapIteratee<T, R>, ): Promise<R[]> { return asyncMap(iterable, iteratee, { concurrency: 1 }); }
{ const concurrency = options?.concurrency ?? Infinity; const resolvedList = Array.from(await iterable); const resolvedLength = resolvedList.length; assert(concurrency > 0); return new Promise((resolve, reject) => { const results: R[] = []; let cursor = 0; let pending = 0; function enqueueNextPromises() ...
identifier_body
feature_format.py
#!/usr/bin/python """ A general tool for converting data from the dictionary format to an (n x k) python list that's ready for training an sklearn algorithm n--no. of key-value pairs in dictonary k--no. of features being extracted dictionary keys are names of persons in dataset dictiona...
elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list = [] for feature in features: try: dictionary[key][feature] except KeyError: print "error: key ", feature, " not...
import pickle keys = pickle.load(open(sort_keys, "rb"))
conditional_block
feature_format.py
#!/usr/bin/python """ A general tool for converting data from the dictionary format to an (n x k) python list that's ready for training an sklearn algorithm n--no. of key-value pairs in dictonary k--no. of features being extracted dictionary keys are names of persons in dataset dictiona...
( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): """ convert dictionary to numpy array of features remove_NaN = True will convert "NaN" string to 0.0 remove_all_zeroes = True will omit any data points for which all the features...
featureFormat
identifier_name
feature_format.py
#!/usr/bin/python """ A general tool for converting data from the dictionary format to an (n x k) python list that's ready for training an sklearn algorithm n--no. of key-value pairs in dictonary k--no. of features being extracted dictionary keys are names of persons in dataset dictiona...
""" given a numpy array like the one returned from featureFormat, separate out the first feature and put it into its own list (this should be the quantity you want to predict) return targets and features as separate lists (sklearn can generally handle both lists and n...
identifier_body
feature_format.py
#!/usr/bin/python """ A general tool for converting data from the dictionary format to an (n x k) python list that's ready for training an sklearn algorithm n--no. of key-value pairs in dictonary k--no. of features being extracted dictionary keys are names of persons in dataset dictiona...
quantity you want to predict) return targets and features as separate lists (sklearn can generally handle both lists and numpy arrays as input formats when training/predicting) """ target = [] features = [] for item in data: target.append( item[0] ) fe...
and put it into its own list (this should be the
random_line_split
weight.rs
//! Provides configuration of weights and their initialization. use capnp_util::*; use co::{ITensorDesc, SharedTensor}; use juice_capnp::weight_config as capnp_config; use rand; use rand::distributions::{IndependentSample, Range}; use util::native_backend; #[derive(Debug, Clone)] /// Specifies training configuration ...
(&self) -> f32 { match self.lr_mult { Some(val) => val, None => 1.0f32, } } /// The multiplier on the global weight decay for this weight blob. pub fn decay_mult(&self) -> f32 { match self.decay_mult { Some(val) => val, None => 1.0f32,...
lr_mult
identifier_name
weight.rs
//! Provides configuration of weights and their initialization. use capnp_util::*; use co::{ITensorDesc, SharedTensor}; use juice_capnp::weight_config as capnp_config; use rand; use rand::distributions::{IndependentSample, Range};
/// The name of the weight blob -- useful for sharing weights among /// layers, but never required otherwise. To share a weight between two /// layers, give it a (non-empty) name. /// /// Default: "" pub name: String, /// Whether to require shared weights to have the same shape, or just the ...
use util::native_backend; #[derive(Debug, Clone)] /// Specifies training configuration for a weight blob. pub struct WeightConfig {
random_line_split
weight.rs
//! Provides configuration of weights and their initialization. use capnp_util::*; use co::{ITensorDesc, SharedTensor}; use juice_capnp::weight_config as capnp_config; use rand; use rand::distributions::{IndependentSample, Range}; use util::native_backend; #[derive(Debug, Clone)] /// Specifies training configuration ...
} impl<'a> CapnpWrite<'a> for WeightConfig { type Builder = capnp_config::Builder<'a>; /// Write the WeightConfig into a capnp message. fn write_capnp(&self, builder: &mut Self::Builder) { // TODO: incomplete since WeightConfig isn't really used internally in Juice at the moment. builder....
{ match self.decay_mult { Some(val) => val, None => 1.0f32, } }
identifier_body
StringBuilder.js
const assert = require('assert'); const is = require('is_js'); function StringBuilder() { const chars = []; //appends a value to the string function append(value) { assert.equal(is.not.object(value), true); value + ''; for (let i = 0; i < value.length; i++) { chars.push(value[i]); } } // removes any ...
} } // returns the string let toString = function toString() { return chars.reduce((x, char) => { return x + char; }); } return { append: append, remove: remove, toString: toString, }; } module.exports = StringBuilder;
{ let str = chars.slice(i, i + value.length); let matches = true; for (let k = 0; k < str.length; k++) { if (str[k] != value[j]) { matches = false; break; } j++; } if (matches) { chars.splice(i, value.length); } i = j; j = 0; }
conditional_block
StringBuilder.js
const assert = require('assert'); const is = require('is_js'); function StringBuilder() { const chars = []; //appends a value to the string function append(value) { assert.equal(is.not.object(value), true); value + ''; for (let i = 0; i < value.length; i++) { chars.push(value[i]); } } // removes any ...
if (matches) { chars.splice(i, value.length); } i = j; j = 0; } } } // returns the string let toString = function toString() { return chars.reduce((x, char) => { return x + char; }); } return { append: append, remove: remove, toString: toString, }; } module.exports = Stri...
random_line_split
StringBuilder.js
const assert = require('assert'); const is = require('is_js'); function
() { const chars = []; //appends a value to the string function append(value) { assert.equal(is.not.object(value), true); value + ''; for (let i = 0; i < value.length; i++) { chars.push(value[i]); } } // removes any instance of the value from within the string function remove(value) { assert.equal(...
StringBuilder
identifier_name
StringBuilder.js
const assert = require('assert'); const is = require('is_js'); function StringBuilder() { const chars = []; //appends a value to the string function append(value)
// removes any instance of the value from within the string function remove(value) { assert.equal(is.not.object(value), true); let j = 0; let strs = []; for (let i = 0; i < chars.length; i++) { if (chars[i] == value[j]) { let str = chars.slice(i, i + value.length); let matches = true; for (l...
{ assert.equal(is.not.object(value), true); value + ''; for (let i = 0; i < value.length; i++) { chars.push(value[i]); } }
identifier_body
columnWidget.js
import React from 'react'; import PropTypes from 'prop-types'; import ColumnChart from './columnChart'; import Tooltip from './../tooltip/tooltip'; import {dateFormats} from './../../utils/displayFormats'; import './columnWidget.css'; const ColumnWidget = ({ chartTitle, chartDescription, chartUpdatedDate,
xAxis, yAxis, viewport, displayHighContrast, }) => { return ( <article role="article" className="D_widget"> <header> {chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>} <h1 className="highcharts-title">{chartTitle}<...
series,
random_line_split
columnWidget.js
import React from 'react'; import PropTypes from 'prop-types'; import ColumnChart from './columnChart'; import Tooltip from './../tooltip/tooltip'; import {dateFormats} from './../../utils/displayFormats'; import './columnWidget.css'; const ColumnWidget = ({ chartTitle, chartDescription, chartUpdatedDate, ...
export default ColumnWidget;
{ ColumnWidget.propTypes = { chartTitle: PropTypes.string, chartDescription: PropTypes.string, chartUpdatedDate: PropTypes.string, series: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string.isRequired, units: PropTypes.string, color: PropTypes.string, data: PropTypes.ar...
conditional_block
keyboard.rs
use libc::{c_int, c_char, uint8_t, uint16_t,
use keycode::{SDL_Keycode, SDL_Keymod}; pub type SDL_bool = c_int; // SDL_keyboard.h #[derive(Copy, Clone)] pub struct SDL_Keysym { pub scancode: SDL_Scancode, pub sym: SDL_Keycode, pub _mod: uint16_t, pub unused: uint32_t, } extern "C" { pub fn SDL_GetKeyboardFocus() -> *mut SDL_Window; pub ...
uint32_t}; use rect::SDL_Rect; use video::SDL_Window; use scancode::SDL_Scancode;
random_line_split
keyboard.rs
use libc::{c_int, c_char, uint8_t, uint16_t, uint32_t}; use rect::SDL_Rect; use video::SDL_Window; use scancode::SDL_Scancode; use keycode::{SDL_Keycode, SDL_Keymod}; pub type SDL_bool = c_int; // SDL_keyboard.h #[derive(Copy, Clone)] pub struct
{ pub scancode: SDL_Scancode, pub sym: SDL_Keycode, pub _mod: uint16_t, pub unused: uint32_t, } extern "C" { pub fn SDL_GetKeyboardFocus() -> *mut SDL_Window; pub fn SDL_GetKeyboardState(numkeys: *mut c_int) -> *const uint8_t; pub fn SDL_GetModState() -> SDL_Keymod; pub fn SDL_SetModSt...
SDL_Keysym
identifier_name
tag-align-shape.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 = t_rec {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); debug!("y = %s", y); assert_eq!(y, ~"{c8: 22, t: a_tag(44)}"); }
identifier_body
tag-align-shape.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 ...
a_tag(u64) } struct t_rec { c8: u8, t: a_tag } pub fn main() { let x = t_rec {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); debug!("y = %s", y); assert_eq!(y, ~"{c8: 22, t: a_tag(44)}"); }
enum a_tag {
random_line_split
tag-align-shape.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 ...
{ a_tag(u64) } struct t_rec { c8: u8, t: a_tag } pub fn main() { let x = t_rec {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); debug!("y = %s", y); assert_eq!(y, ~"{c8: 22, t: a_tag(44)}"); }
a_tag
identifier_name
main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } // ANCHOR: here impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool
} // ANCHOR_END: here fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect...
{ self.width > other.width && self.height > other.height }
identifier_body
main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32,
impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } // ANCHOR_END: here fn main() { let rect1 = Rectangle { width: 30, height: 50, }; l...
} // ANCHOR: here
random_line_split
main.rs
#[derive(Debug)] struct
{ width: u32, height: u32, } // ANCHOR: here impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } // ANCHOR_END: here fn main() { let rect1 = Rectangl...
Rectangle
identifier_name
identifier.component.ts
import {Component, OnInit,Input} from 'angular2/core'; import {Identifier} from 'gedcomx'; import {CollapsibleFieldsetComponent} from './collapsibleFieldset.component';
<button (click)="createIdentifier()" *ngIf="!data">Set Identifier</button> <div *ngIf="data"> <label> Value: <input [(ngModel)]="data.value" placeholder="Value"/> </label> <label *ngIf="data">Type: <select [(ngModel)]="data.type"> <option *ngFor="#type...
@Component({ selector: 'identifier', template: ` <collapsibleFieldset legendLabel="Identifier">
random_line_split
identifier.component.ts
import {Component, OnInit,Input} from 'angular2/core'; import {Identifier} from 'gedcomx'; import {CollapsibleFieldsetComponent} from './collapsibleFieldset.component'; @Component({ selector: 'identifier', template: ` <collapsibleFieldset legendLabel="Identifier"> <button (click)="createIdentifier()"...
getAllIdentifierTypes() { return []; } }
{ }
identifier_body
identifier.component.ts
import {Component, OnInit,Input} from 'angular2/core'; import {Identifier} from 'gedcomx'; import {CollapsibleFieldsetComponent} from './collapsibleFieldset.component'; @Component({ selector: 'identifier', template: ` <collapsibleFieldset legendLabel="Identifier"> <button (click)="createIdentifier()"...
implements OnInit { data: Identifier; constructor() { } ngOnInit() { } getAllIdentifierTypes() { return []; } }
IdentifierComponent
identifier_name
builtin-superkinds-capabilities.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// except according to those terms. // Tests "capabilities" granted by traits that inherit from super- // builtin-kinds, e.g., if a trait requires Send to implement, then // at usage site of that trait, we know we have the Send capability. trait Foo : Send { } impl <T: Send> Foo for T { } fn foo<T: Foo>(val: T, cha...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
builtin-superkinds-capabilities.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let (tx, rx): (Sender<int>, Receiver<int>) = channel(); foo(31337i, tx); assert!(rx.recv() == 31337i); }
main
identifier_name
builtin-superkinds-capabilities.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let (tx, rx): (Sender<int>, Receiver<int>) = channel(); foo(31337i, tx); assert!(rx.recv() == 31337i); }
identifier_body