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
main.rs
// y // 2 _|_|_ // 1 _|_|_ // 0 | | // 0 1 2 x use std::collections::LinkedList; use std::io::stdin; struct
{ loc: Loc, who: i8 } struct Loc { x: i8, y: i8, } struct EachRecord { win: Vec<Loc>, draw: Vec<Loc>, lose: Vec<Loc> } fn main() { let mut table : LinkedList<Step> = LinkedList::new(); let mut record : [EachRecord; 19683]; loop { if end_check(&table) { tab...
Step
identifier_name
main.rs
// y // 2 _|_|_ // 1 _|_|_ // 0 | | // 0 1 2 x use std::collections::LinkedList; use std::io::stdin; struct Step { loc: Loc, who: i8 } struct Loc { x: i8, y: i8, } struct EachRecord { win: Vec<Loc>, draw: Vec<Loc>, lose: Vec<Loc> } fn main() { let mut table : LinkedList<Step>...
fn add2record(table: &[[i8; 3]; 3], record: &mut [EachRecord; 19683]) { // Step(x, y, who) -> EachRecord[table]: // win: Vec<Loc NextStep>, draw: Vec<Loc>, lose: Vec<Loc> let t = table_status(table); } fn table_status(table: &[[i8; 3]; 3]) -> i8 { // ret // 0 = unfinished ...
{ return table.len() > 8; }
identifier_body
world.rs
use std::boxed::Box; use std::collections::HashMap; use glutin; use game::ContentId; use game::entity::{Entity, UID, EEntityType, EntityController}; use std::sync::mpsc::{Receiver, Sender, SyncSender}; use content::load_content::{EContentRequestType, EContentRequestResult}; use graphics::renderer::RenderFrame; use gam...
World { entity_uids: 1 as u64, //uids start at 1, because we can use 0 as a flag value, a NULL valye controller_uid: 1 as u64, to_content_server: to_content_server, from_cotent_server: from_cotent_server, to_render_thread: to_render_thread, ...
random_line_split
world.rs
use std::boxed::Box; use std::collections::HashMap; use glutin; use game::ContentId; use game::entity::{Entity, UID, EEntityType, EntityController}; use std::sync::mpsc::{Receiver, Sender, SyncSender}; use content::load_content::{EContentRequestType, EContentRequestResult}; use graphics::renderer::RenderFrame; use gam...
pub fn inner_update(mut self) { let mut frame_timer = FrameTimer::new(); let mut frame_count = 0 as u64; let controller_uid = self.get_uid_for_controller().clone(); let ui_uid = self.get_uid_for_controller().clone(); let mut entity_controllers: HashMap<EEntityType, &mut E...
{ let entity_type = entity.get_entity_type(); if !self.type_to_uid_list.contains_key(&entity_type) { self.type_to_uid_list.insert(entity_type, Vec::new()); } self.type_to_uid_list.get_mut(&entity_type).unwrap().push( entity.get_uid(), ); let entity...
identifier_body
world.rs
use std::boxed::Box; use std::collections::HashMap; use glutin; use game::ContentId; use game::entity::{Entity, UID, EEntityType, EntityController}; use std::sync::mpsc::{Receiver, Sender, SyncSender}; use content::load_content::{EContentRequestType, EContentRequestResult}; use graphics::renderer::RenderFrame; use gam...
(&mut self) -> UID { self.controller_uid += 1; return self.controller_uid; } pub fn load_content(&self, content: EContentRequestType) -> Result<ContentId, ELoadContentError> { let _ = self.to_content_server.send(content); let result = self.from_cotent_server.recv(); matc...
get_uid_for_controller
identifier_name
world.rs
use std::boxed::Box; use std::collections::HashMap; use glutin; use game::ContentId; use game::entity::{Entity, UID, EEntityType, EntityController}; use std::sync::mpsc::{Receiver, Sender, SyncSender}; use content::load_content::{EContentRequestType, EContentRequestResult}; use graphics::renderer::RenderFrame; use gam...
, } }, Err(_) => { return Err(ELoadContentError::LoadThreadNoResponce); }, } } }
{ return Ok(id); }
conditional_block
complex.rs
Clone + Num> Neg<Complex<T>> for Complex<T> { #[inline] fn neg(&self) -> Complex<T> { Complex::new(-self.re, -self.im) } } /* constants */ impl<T: Clone + Num> Zero for Complex<T> { #[inline] fn zero() -> Complex<T> { Complex::new(Zero::zero(), Zero::zero()) } #[inline] ...
{ assert_eq!(-_1_0i + _0_1i, _neg1_1i); assert_eq!((-_0_1i) * _0_1i, _1_0i); for &c in all_consts.iter() { assert_eq!(-(-c), c); } }
identifier_body
complex.rs
self) -> Complex<T> { let norm_sqr = self.norm_sqr(); Complex::new(self.re / norm_sqr, -self.im / norm_sqr) } } impl<T: Clone + FloatMath> Complex<T> { /// Calculate |self| #[inline] pub fn norm(&self) -> T { self.re.hypot(self.im) } } impl<T: Clone + Fl...
random_line_split
complex.rs
` by the scalar `t`. #[inline] pub fn scale(&self, t: T) -> Complex<T> { Complex::new(self.re * t, self.im * t) } /// Divides `self` by the scalar `t`. #[inline] pub fn unscale(&self, t: T) -> Complex<T> { Complex::new(self.re / t, self.im / t) } /// Returns `1/self` ...
} } #[cfg(test)] mod test { #![allow(non_uppercase_statics)] use super::{Complex64, Complex}; use std::num::{Zero,One,Float}; pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; pub static _1_1i : Complex64 = Complex {...
{ format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix)) }
conditional_block
complex.rs
` by the scalar `t`. #[inline] pub fn scale(&self, t: T) -> Complex<T> { Complex::new(self.re * t, self.im * t) } /// Divides `self` by the scalar `t`. #[inline] pub fn unscale(&self, t: T) -> Complex<T> { Complex::new(self.re / t, self.im / t) } /// Returns `1/self` ...
(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < Zero::zero() { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } } impl<T: ToStrRadix + Num + PartialOrd> ToStrRadix for Complex<T> { fn to_str_radix(&self, radi...
fmt
identifier_name
loader-interface.ts
/* istanbul ignore next */ import {TwingSource} from "./source"; export interface TwingLoaderInterface { /** * Returns the source context for a given template logical name. * * @param {string} name The template logical name * @param {TwingSource} from The source that initiated the template loa...
/** * Gets the cache key to use for the cache for a given template name. * * @param {string} name The name of the template to load * @param {TwingSource} from The source that initiated the template loading * * @returns {Promise<string>} The cache key * * @throws TwingErrorLo...
* * @throws TwingErrorLoader When name is not found */ getSourceContext(name: string, from: TwingSource): Promise<TwingSource>;
random_line_split
test_gfx.py
"core.Pixmap tests" from unittest import SkipTest from testutils import * from gfxprim.core import Pixmap from gfxprim import gfx, core def test_gfx_submodule_loads(): "gfx is present in a Pixmap" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx def test_gfx_submodule_has_C(): "gfx contains C" c = Pix...
elif t == 'S': args.append("") else: assert False return tuple(args) @for_each_case(gfx_params) def test_method_call(n, params): "Calling with dummy parameters:" c = PixmapRand(10, 10, core.C.PIXEL_RGB888) if isinstance(params, str): c.gfx.__getattribute__(n)(*gen_dummy_args(params)) ...
args.append(0.5)
conditional_block
test_gfx.py
"core.Pixmap tests" from unittest import SkipTest from testutils import * from gfxprim.core import Pixmap from gfxprim import gfx, core def
(): "gfx is present in a Pixmap" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx def test_gfx_submodule_has_C(): "gfx contains C" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx.C assert gfx.C # These set the param types of the functions in GFX gfx_params = { 'arc_segment': 'IIIIIFFP', '...
test_gfx_submodule_loads
identifier_name
test_gfx.py
"core.Pixmap tests" from unittest import SkipTest from testutils import * from gfxprim.core import Pixmap from gfxprim import gfx, core def test_gfx_submodule_loads(): "gfx is present in a Pixmap" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx def test_gfx_submodule_has_C(): "gfx contains C" c = Pix...
'putpixel_aa': 'IIP', # Fixpoint, originally 'FFP' 'rect': 'IIIIP', 'ring': 'IIIIP', 'tetragon': 'IIIIIIIIP', 'triangle': 'IIIIIIP', 'vline': 'IIIP', 'vline_aa': 'IIIP', # Fixpoint, originally 'FFFP' } def test_all_methods_are_known(): "All methods of gfx submodule have known param t...
'polygon': ([(0,0),(1,1),(1,0)], 0, {}),
random_line_split
test_gfx.py
"core.Pixmap tests" from unittest import SkipTest from testutils import * from gfxprim.core import Pixmap from gfxprim import gfx, core def test_gfx_submodule_loads(): "gfx is present in a Pixmap" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx def test_gfx_submodule_has_C():
# These set the param types of the functions in GFX gfx_params = { 'arc_segment': 'IIIIIFFP', 'circle': 'IIIP', 'ellipse': 'IIIIP', 'fill': 'P', 'fill_circle': 'IIIP', 'fill_ellipse': 'IIIIP', 'fill_polygon': ([(0,0),(1,1),(1,0)], 0, {}), 'fill_rect': 'IIIIP', 'fill_ring': 'IIIIP'...
"gfx contains C" c = Pixmap(1, 1, core.C.PIXEL_RGB888) assert c.gfx.C assert gfx.C
identifier_body
mfa.py
"""Multiple Factor Analysis (MFA)""" import itertools from matplotlib import markers import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import utils from . import mca from . import one_hot from . import pca from . import plot class MFA(pca.PCA): def __init__(self, groups=None, ...
Z_partial = X_partial / self.partial_factor_analysis_[name].s_[0] coords[name] = len(self.groups) * (Z_partial @ Z_partial.T) @ P # Convert coords to a MultiIndex DataFrame coords = pd.DataFrame({ (name, i): group_coords.loc[:, i] for name, group_coords...
X_partial = self.cat_one_hots_[name].transform(X_partial)
conditional_block
mfa.py
"""Multiple Factor Analysis (MFA)""" import itertools from matplotlib import markers import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import utils from . import mca from . import one_hot from . import pca from . import plot class MFA(pca.PCA): def __init__(self, groups=None, ...
mask = np.array(color_labels) == color_label label = '{} - {}'.format(name, color_label) ax.scatter(x[mask], y[mask], marker=mark, color=color, label=label, **kwargs) # Legend ax.legend() # Text ax.set_title('Partial row principal coordin...
ax.scatter(x, y, marker=mark, label=name, **kwargs) continue for color_label, color in sorted(colors.items()):
random_line_split
mfa.py
"""Multiple Factor Analysis (MFA)""" import itertools from matplotlib import markers import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import utils from . import mca from . import one_hot from . import pca from . import plot class MFA(pca.PCA): def
(self, groups=None, normalize=True, n_components=2, n_iter=10, copy=True, check_input=True, random_state=None, engine='auto'): super().__init__( rescale_with_mean=False, rescale_with_std=False, n_components=n_components, n_iter=n_iter, ...
__init__
identifier_name
mfa.py
"""Multiple Factor Analysis (MFA)""" import itertools from matplotlib import markers import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import utils from . import mca from . import one_hot from . import pca from . import plot class MFA(pca.PCA): def __init__(self, groups=None, ...
def transform(self, X): """Returns the row principal coordinates of a dataset.""" return self.row_coordinates(X) def _row_coordinates_from_global(self, X_global): """Returns the row principal coordinates.""" return len(X_global) ** 0.5 * super().row_coordinates(X_global) ...
X_partials = [] self.cat_one_hots_ = {} for name, cols in sorted(self.groups.items()): X_partial = X.loc[:, cols] if not self.all_nums_[name]: oh = one_hot.OneHotEncoder().fit(X_partial) X_partial = oh.fit_transform(X_partial) sel...
identifier_body
search.js
(function () { function getQueryVariable(variable) { var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } } function getPreview(query, content, previewL...
})();
random_line_split
search.js
(function () { function getQueryVariable(variable) { var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } } function getPreview(query, content, previewL...
match = content.toLowerCase().indexOf(parts[i].toLowerCase()); matchLength = parts[i].length; } // Create preview if (match >= 0) { var start = match - (previewLength / 2), end = start > 0 ? match + matchLength + (previewLength / 2) : previewLength; preview = content.substring(start, end).trim...
{ break; }
conditional_block
search.js
(function () { function getQueryVariable(variable) { var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } } function
(query, content, previewLength) { previewLength = previewLength || (content.length * 2); var parts = query.split(" "), match = content.toLowerCase().indexOf(query.toLowerCase()), matchLength = query.length, preview; // Find a relevant location in content for (var i = 0; i < parts.length; i++) { if...
getPreview
identifier_name
search.js
(function () { function getQueryVariable(variable)
function getPreview(query, content, previewLength) { previewLength = previewLength || (content.length * 2); var parts = query.split(" "), match = content.toLowerCase().indexOf(query.toLowerCase()), matchLength = query.length, preview; // Find a relevant location in content for (var i = 0; i < part...
{ var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } }
identifier_body
yelphelper.py
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c...
merge_translations
identifier_name
yelphelper.py
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def m...
pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
conditional_block
yelphelper.py
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
# Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang i...
random_line_split
yelphelper.py
# Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to ...
def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True...
for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources)
identifier_body
learner-local-nav.directive.ts
// Copyright 2014 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by ap...
ctrl.$onInit = function() { ctrl.explorationId = ExplorationEngineService.getExplorationId(); ReadOnlyExplorationBackendApiService .loadExploration(ctrl.explorationId) .then(function(exploration) { ctrl.canEdit = exploration.can_edit; ...
random_line_split
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Joël Grand-Guillaume (Camptocamp) # Copyright 2010-2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pub...
'author': "Camptocamp,Odoo Community Association (OCA)", 'website': 'http://camptocamp.com', 'license': 'AGPL-3', 'depends': ['account'], 'data': [ 'invoice_wkf.xml', 'invoice_view.xml', ], 'demo': [], 'test': [], 'installable': True, 'auto_install': False, 'a...
- To Send: For all invoices that need to be sent ''',
random_line_split
location_form.tsx
import React from "react"; import { Row, Col, FBSelect } from "../../ui"; import { locationFormList, NO_VALUE_SELECTED_DDI } from "./location_form_list"; import { convertDDItoVariable } from "../locals_list/handle_select"; import { LocationFormProps, PARENT, AllowedVariableNodes, VariableNode, } from "../locals_list/...
const maybeUseStepData = ({ resources, bodyVariables, variable, uuid }: { resources: ResourceIndex, bodyVariables: VariableNode[] | undefined, variable: SequenceMeta, uuid: UUID, }): SequenceMeta => { const executeStepData = bodyVariables?.filter(v => v.args.label === variable.celeryNode.args.label)[0]; ...
/** * If a variable with a matching label exists in local parameter applications * (step body, etc.), use it instead of the one in scope declarations. */
random_line_split
location_form.tsx
import React from "react"; import { Row, Col, FBSelect } from "../../ui"; import { locationFormList, NO_VALUE_SELECTED_DDI } from "./location_form_list"; import { convertDDItoVariable } from "../locals_list/handle_select"; import { LocationFormProps, PARENT, AllowedVariableNodes, VariableNode, } from "../locals_list/...
return variable; }; /** * Form with an "import from" dropdown and coordinate input boxes. * Can be used to set a specific value, import a value, or declare a variable. */ export const LocationForm = (props: LocationFormProps) => { const { sequenceUuid, resources, bodyVariables, variable, allowedVaria...
{ return { celeryNode: executeStepData, vector: determineVector(executeStepData, resources, uuid), dropdown: determineDropdown(executeStepData, resources, uuid), }; }
conditional_block
products-edit.js
", function(object){ return object.text; }); $.fn.select2.defaults.set("tags", true); /*$.fn.select2.defaults.set("createTag", function (params) { return { id: params.term, text: params.term, newOption: true}}); $.fn.select2.defaults.set("createSearchChoice", function(term, data){ if ( $(data).filter( functio...
{ var temp_array = {}; $.each(SelectedOptGgroup, function(index, data){ temp_array[index] = {text:data.text, id:data.id}; }); CombinationArray[$i++] = temp_array; }
conditional_block
products-edit.js
") }); $('[data-toggle="tooltip"]').tooltip(); // product varients var optiongroupMaster = $("#optiongroupmaster").html(); var optgroupContainer = $("#optiongroup-containner"); var createCombinations = function($elements){ var CombinationArray = {}; var $i = 0; $elements.each(function(inde...
} } });
random_line_split
canonical-title-map.spec.js
import chai from 'chai'; import { describe, it } from 'mocha'; import canonicalTitleMap from './canonical-title-map'; chai.should(); describe('canonical-title-map.js', () => { it('should hold a normalisation function for enums and titleMaps to generate titleMaps', () => { canonicalTitleMap.should.be.an('function')...
titlemap.push({ name: undefined, value: 'Mr Freeze', }); result.should.be.deep.equal(titlemap); }); }); });
random_line_split
uninit-consts-allow-partially-uninit.rs
// compile-flags: -C no-prepopulate-passes -Z partially_uninit_const_threshold=1024 // Like uninit-consts.rs, but tests that we correctly generate partially-uninit consts // when the (disabled by default) partially_uninit_const_threshold flag is used. #![crate_type = "lib"] use std::mem::MaybeUninit; pub struct Par...
pub const fn partially_uninit() -> PartiallyUninit { const X: PartiallyUninit = PartiallyUninit { x: 0xdeadbeef, y: MaybeUninit::uninit() }; // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{(32|64)}}(i8* align 4 %1, i8* align 4 getelementptr inbounds (<{ [4 x i8], [12 x i8] }>, <{ [4 x i8], [12 x i8] }>* [[PARTIAL...
// This shouldn't contain undef, since it's larger than the 1024 byte limit. // CHECK: [[UNINIT_PADDING_HUGE:@[0-9]+]] = private unnamed_addr constant <{ [32768 x i8] }> <{ [32768 x i8] c"{{.+}}" }>, align 4 // CHECK-LABEL: @partially_uninit #[no_mangle]
random_line_split
uninit-consts-allow-partially-uninit.rs
// compile-flags: -C no-prepopulate-passes -Z partially_uninit_const_threshold=1024 // Like uninit-consts.rs, but tests that we correctly generate partially-uninit consts // when the (disabled by default) partially_uninit_const_threshold flag is used. #![crate_type = "lib"] use std::mem::MaybeUninit; pub struct Par...
() -> [(u32, u8); 4096] { const X: [(u32, u8); 4096] = [(123, 45); 4096]; // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{(32|64)}}(i8* align 4 %1, i8* align 4 getelementptr inbounds (<{ [32768 x i8] }>, <{ [32768 x i8] }>* [[UNINIT_PADDING_HUGE]], i32 0, i32 0, i32 0), i{{(32|64)}} 32768, i1 false) X }
uninit_padding_huge
identifier_name
apply.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (fn /*, ...args*/) { var args = (0, _slice2.default)(arguments, 1); return function () /*callArgs*/{ var callArgs = (0, _slice2.default)(arguments); return fn.apply(null, args....
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ; /** * Creates a continuation function with some arguments already applied. * * Useful as a shorthand when combined with other control flow functions. Any * arguments passed to the returned function are added to the arguments * originally...
_interopRequireDefault
identifier_name
apply.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (fn /*, ...args*/) { var args = (0, _slice2.default)(arguments, 1); return function () /*callArgs*/{ var callArgs = (0, _slice2.default)(arguments); return fn.apply(null, args....
; /** * Creates a continuation function with some arguments already applied. * * Useful as a shorthand when combined with other control flow functions. Any * arguments passed to the returned function are added to the arguments * originally passed to apply. * * @name apply * @static * @memberOf ...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
apply.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (fn /*, ...args*/) { var args = (0, _slice2.default)(arguments, 1); return function () /*callArgs*/{ var callArgs = (0, _slice2.default)(arguments); return fn.apply(null, args....
* async.apply(fs.writeFile, 'testfile1', 'test1'), * async.apply(fs.writeFile, 'testfile2', 'test2') * ]); * * * // the same process without using apply * async.parallel([ * function(callback) { * fs.writeFile('testfile1', 'test1', callback); * }, * function(callback) { ...
* * // using apply * async.parallel([
random_line_split
options.py
from __future__ import absolute_import import logging import six from datetime import timedelta from django.utils import timezone from sentry.models import Option from sentry.options import default_manager from sentry.options.manager import UnknownOption from sentry.tasks.base import instrumented_task ONE_HOUR = 60...
This **does not** guarantee that the correct value is written into the cache though it will correct itself in the next update window. """ cutoff_dt = timezone.now() - timedelta(seconds=cutoff) # TODO(dcramer): this doesnt handle deleted options (which shouldn't be allowed) for option in Option....
@instrumented_task(name="sentry.tasks.options.sync_options", queue="options") def sync_options(cutoff=ONE_HOUR): """ Ensures all options that have been updated (within the database) since ``cutoff`` have their correct values stored in the cache.
random_line_split
options.py
from __future__ import absolute_import import logging import six from datetime import timedelta from django.utils import timezone from sentry.models import Option from sentry.options import default_manager from sentry.options.manager import UnknownOption from sentry.tasks.base import instrumented_task ONE_HOUR = 60...
""" Ensures all options that have been updated (within the database) since ``cutoff`` have their correct values stored in the cache. This **does not** guarantee that the correct value is written into the cache though it will correct itself in the next update window. """ cutoff_dt = timezone.now...
identifier_body
options.py
from __future__ import absolute_import import logging import six from datetime import timedelta from django.utils import timezone from sentry.models import Option from sentry.options import default_manager from sentry.options.manager import UnknownOption from sentry.tasks.base import instrumented_task ONE_HOUR = 60...
(cutoff=ONE_HOUR): """ Ensures all options that have been updated (within the database) since ``cutoff`` have their correct values stored in the cache. This **does not** guarantee that the correct value is written into the cache though it will correct itself in the next update window. """ c...
sync_options
identifier_name
options.py
from __future__ import absolute_import import logging import six from datetime import timedelta from django.utils import timezone from sentry.models import Option from sentry.options import default_manager from sentry.options.manager import UnknownOption from sentry.tasks.base import instrumented_task ONE_HOUR = 60...
try: opt = default_manager.lookup_key(option.key) default_manager.store.set_cache(opt, option.value) except UnknownOption as e: logger.exception(six.text_type(e))
conditional_block
angular-MQTT.js
/** * Created by shellus on 2016-03-16. */ angular.module('ngMQTT', []) .config(['$provide', function($provide){ $provide.provider('MQTT', function(){ var settings = { href: "" }; this.setHref = function(href){ settings.href = href; ...
}; return Service; }]);
}; Service.drop = function(name, callback){ callbacks[name] = callback; client.unsubscribe(name);
random_line_split
tunnel_calls.py
# Copyright (c) 2016 OpenStack Foundation # # 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 ...
(object): """Common tunnel calls for L2 agent.""" def __init__(self): self._construct_rpc_stuff() def _construct_rpc_stuff(self): self.notifier = rpc.AgentNotifierApi(topics.AGENT) self.type_manager = managers.TypeManager() self.tunnel_rpc_obj = rpc.RpcCallbacks(self.notifie...
Tunnel_Calls
identifier_name
tunnel_calls.py
# Copyright (c) 2016 OpenStack Foundation # # 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 ...
def trigger_l2pop_sync(self, context, other_fdb_entries): """Sends L2pop ADD RPC message to the neutron L2 agent.""" l2pop_rpc.L2populationAgentNotifyAPI( ).add_fdb_entries(context, other_fdb_entries) def trigger_l2pop_delete(self, context, other_fdb_entries, host=None): """...
"""Common tunnel calls for L2 agent.""" def __init__(self): self._construct_rpc_stuff() def _construct_rpc_stuff(self): self.notifier = rpc.AgentNotifierApi(topics.AGENT) self.type_manager = managers.TypeManager() self.tunnel_rpc_obj = rpc.RpcCallbacks(self.notifier, ...
identifier_body
tunnel_calls.py
# Copyright (c) 2016 OpenStack Foundation # # 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 ...
'tunnel_type': 'vxlan'} self.tunnel_rpc_obj.tunnel_sync(context, **tunnel_dict) def trigger_l2pop_sync(self, context, other_fdb_entries): """Sends L2pop ADD RPC message to the neutron L2 agent.""" l2pop_rpc.L2populationAgentNoti...
L2 agent. """ tunnel_dict = {'tunnel_ip': tunnel_ip,
random_line_split
rano.py
import sys try: data = map(int, sys.stdin.readline().split()) except ValueError: sys.stdout.write("NO" + '\n') exit()
if len(data) != 2: sys.stdout.write("NO" + '\n') exit() if data[0] < 1 or data[0] > 1000: sys.stdout.write("NO" + '\n') exit() if data[1] < 0 or data[1] > 100000: sys.stdout.write("NO" + '\n') exit() if data[1] == 0: sys.stdout.write("YES" + '\n') exit() constraints = [] try: fo...
if not data: sys.stdout.write("NO" + '\n') exit()
random_line_split
rano.py
import sys try: data = map(int, sys.stdin.readline().split()) except ValueError: sys.stdout.write("NO" + '\n') exit() if not data: sys.stdout.write("NO" + '\n') exit() if len(data) != 2: sys.stdout.write("NO" + '\n') exit() if data[0] < 1 or data[0] > 1000: sys.stdout.write("NO" + '\...
sys.stdout.write("YES" + '\n')
for i in range(len(item)): for j in range(i+1, len(item)): if item[i] in studyplan and item[j] in studyplan: if studyplan.index(item[i]) > studyplan.index(item[j]): sys.stdout.write("NO" + '\n') exit()
conditional_block
parse_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isPresent} from './facade/lang'; export class ParseLocation { constructor( public file: ParseSourceF...
} ctxLen = 0; ctxLines = 0; while (ctxLen < 100 && ctxEnd < source.length - 1) { ctxEnd++; ctxLen++; if (source[ctxEnd] == '\n') { if (++ctxLines == 3) { break; } } } let context = source.substring(ctxStart, this.span...
{ if (++ctxLines == 3) { break; } }
conditional_block
parse_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isPresent} from './facade/lang'; export class ParseLocation { constructor( public file: ParseSourceF...
public level: ParseErrorLevel = ParseErrorLevel.FATAL) {} toString(): string { var source = this.span.start.file.content; var ctxStart = this.span.start.offset; var contextStr = ''; var details = ''; if (isPresent(ctxStart)) { if (ctxStart > source.length - 1) { ctxStart = sou...
random_line_split
parse_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {isPresent} from './facade/lang'; export class ParseLocation { constructor( public file: ParseSourceF...
{ constructor( public start: ParseLocation, public end: ParseLocation, public details: string = null) {} toString(): string { return this.start.file.content.substring(this.start.offset, this.end.offset); } } export enum ParseErrorLevel { WARNING, FATAL } export class ParseError { constructor( ...
ParseSourceSpan
identifier_name
AmCoordinateChart.d.ts
import AmChart from "./AmChart"; import AmGraph from "./AmGraph"; import GraphDataItem from "./GraphDataItem"; import Guide from "./Guide"; import ValueAxis from "./ValueAxis"; /** * AmCoordinateChart is a base class of AmRectangularChart. It can not be instantiated explicitly. */ export default class
extends AmChart { /** * Array, holding processed chart's data. */ chartData: object[]; /** * Specifies the colors of the graphs if the lineColor of a graph is not set. * It there are more graphs then colors in this array, the chart picks random color. * @default ['#FF6600','#FCD202...
AmCoordinateChart
identifier_name
AmCoordinateChart.d.ts
import AmChart from "./AmChart"; import AmGraph from "./AmGraph"; import GraphDataItem from "./GraphDataItem"; import Guide from "./Guide"; import ValueAxis from "./ValueAxis"; /** * AmCoordinateChart is a base class of AmRectangularChart. It can not be instantiated explicitly. */ export default class AmCoordinateCh...
* adding/removing axes directly to array. * Chart creates one value axis automatically, so if you need only one value axis, you don't need to create it. */ valueAxes: any[]; /** * Adds a graph to the chart. */ addGraph(graph: AmGraph): void; /** * Adds value axis to the cha...
*/ urlTarget: any; /** * The array of value axes. * To add/remove value axis use addValueAxis/removeValueAxis methods instead of
random_line_split
datatable-body.js
Binds event subscriptions from the UI and the source (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles; if (this.source && !handles.columnsChange) { handles.columnsChange = this.source.after('columnsChan...
{ this._cssPrefix = cssPrefix; }
conditional_block
datatable-body.js
and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { this.columns = this._parseC...
values[token] = col.allowHTML ? value : htmlEscape(value);
random_line_split
lib.rs
ItemList, MetaNameValue}; mod data; pub use data::{Field, Variant, VariantData, Visibility, VisRestricted, VisCrate, VisPublic, VisInherited}; mod expr; pub use expr::{Expr, ExprKind, ExprBox, ExprInPlace, ExprArray, ExprCall, ExprMethodCall, ExprTup, ExprBinary, ExprUnary...
/// Parse a string of Rust code into the chosen syn data type. /// /// # Examples /// /// ```rust /// extern crate syn; /// # /// # #[macro_use] /// # extern crate error_chain; /// /// use syn::Expr; /// # /// # error_chain! { /// # foreign_links { /// # Syn(syn::ParseError); /// # } /// # } /// /// f...
{ _parse(tokens.into()) }
identifier_body
lib.rs
ItemList, MetaNameValue}; mod data; pub use data::{Field, Variant, VariantData, Visibility, VisRestricted, VisCrate, VisPublic, VisInherited}; mod expr; pub use expr::{Expr, ExprKind, ExprBox, ExprInPlace, ExprArray, ExprCall, ExprMethodCall, ExprTup, ExprBinary, ExprUnary...
<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError> where T: Synom, { let buf = SynomBuffer::new(tokens); let result = T::parse(buf.begin()); let err = match result { Ok((rest, t)) => { if rest.eof() { return Ok(t); } else if rest == buf.begin()...
_parse
identifier_name
lib.rs
ItemList, MetaNameValue}; mod data; pub use data::{Field, Variant, VariantData, Visibility, VisRestricted, VisCrate, VisPublic, VisInherited}; mod expr; pub use expr::{Expr, ExprKind, ExprBox, ExprInPlace, ExprArray, ExprCall, ExprMethodCall, ExprTup, ExprBinary, ExprUnary...
pub use file::File; mod lifetime; pub use lifetime::Lifetime; mod lit; pub use lit::{Lit, LitKind}; mod mac; pub use mac::{Mac, TokenTree}; mod derive; pub use derive::{Body, DeriveInput, BodyEnum, BodyStruct}; mod op; pub use op::{BinOp, UnOp}; mod ty; pub use ty::{Abi, AbiKind, AngleBracketedParameterData, Bare...
ArgSelf, ArgCaptured}; #[cfg(feature = "full")] mod file; #[cfg(feature = "full")]
random_line_split
fetch-all.function.ts
/** * @module helper */ import * as DynamoDB from 'aws-sdk/clients/dynamodb' import { QueryRequest } from '../dynamo/request/query/query.request' import { ReadManyRequest } from '../dynamo/request/read-many.request' import { ScanRequest } from '../dynamo/request/scan/scan.request' /** * When we cant load all the it...
return request.execFullResponse().then((response) => { if (response.LastEvaluatedKey) { return fetchAll(request, response.LastEvaluatedKey).then((innerResponse) => [...response.Items, ...innerResponse]) } else { return response.Items } }) }
{ request.exclusiveStartKey(startKey) }
conditional_block
fetch-all.function.ts
/** * @module helper */ import * as DynamoDB from 'aws-sdk/clients/dynamodb' import { QueryRequest } from '../dynamo/request/query/query.request' import { ReadManyRequest } from '../dynamo/request/read-many.request' import { ScanRequest } from '../dynamo/request/scan/scan.request' /** * When we cant load all the it...
<T>(request: ScanRequest<T> | QueryRequest<T>, startKey?: DynamoDB.Key): Promise<T[]> { request.limit(ReadManyRequest.INFINITE_LIMIT) if (startKey) { request.exclusiveStartKey(startKey) } return request.execFullResponse().then((response) => { if (response.LastEvaluatedKey) { return fetchAll(reques...
fetchAll
identifier_name
fetch-all.function.ts
/** * @module helper */ import * as DynamoDB from 'aws-sdk/clients/dynamodb' import { QueryRequest } from '../dynamo/request/query/query.request' import { ReadManyRequest } from '../dynamo/request/read-many.request' import { ScanRequest } from '../dynamo/request/scan/scan.request' /** * When we cant load all the it...
return fetchAll(request, response.LastEvaluatedKey).then((innerResponse) => [...response.Items, ...innerResponse]) } else { return response.Items } }) }
if (startKey) { request.exclusiveStartKey(startKey) } return request.execFullResponse().then((response) => { if (response.LastEvaluatedKey) {
random_line_split
fetch-all.function.ts
/** * @module helper */ import * as DynamoDB from 'aws-sdk/clients/dynamodb' import { QueryRequest } from '../dynamo/request/query/query.request' import { ReadManyRequest } from '../dynamo/request/read-many.request' import { ScanRequest } from '../dynamo/request/scan/scan.request' /** * When we cant load all the it...
{ request.limit(ReadManyRequest.INFINITE_LIMIT) if (startKey) { request.exclusiveStartKey(startKey) } return request.execFullResponse().then((response) => { if (response.LastEvaluatedKey) { return fetchAll(request, response.LastEvaluatedKey).then((innerResponse) => [...response.Items, ...innerResp...
identifier_body
interfaceNameRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
export class Rule extends Lint.Rules.AbstractRule { static FAILURE_STRING = "interface name must be a capitalized I"; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new NameWalker(sourceFile, this.getOptions())); } } class NameWalker extends Lint.RuleWal...
*/
random_line_split
interfaceNameRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
const firstCharacter = name.charAt(0); return (firstCharacter === "I"); } private addFailureAt(position: number, width: number) { const failure = this.createFailure(position, width, Rule.FAILURE_STRING); this.addFailure(failure); } }
{ return true; }
conditional_block
interfaceNameRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
(position: number, width: number) { const failure = this.createFailure(position, width, Rule.FAILURE_STRING); this.addFailure(failure); } }
addFailureAt
identifier_name
interfaceNameRule.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * 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 l...
private addFailureAt(position: number, width: number) { const failure = this.createFailure(position, width, Rule.FAILURE_STRING); this.addFailure(failure); } }
{ if (name.length <= 0) { return true; } const firstCharacter = name.charAt(0); return (firstCharacter === "I"); }
identifier_body
wrap_matcher.py
import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x):
def is_matchable_type(expected_type): if isinstance(expected_type, type): return True if isinstance(expected_type, six.class_types): return True if isinstance(expected_type, tuple) and \ expected_type and \ all(map(is_matchable_type, expected_type)): return True ...
"""Wraps argument in a matcher, if necessary. :returns: the argument as-is if it is already a matcher, otherwise wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher. """ if isinstance(x, Matcher): return x else: return equal_to(x)
identifier_body
wrap_matcher.py
import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x): """Wraps argument in a matcher, if necessary. :returns: the ...
(expected_type): if isinstance(expected_type, type): return True if isinstance(expected_type, six.class_types): return True if isinstance(expected_type, tuple) and \ expected_type and \ all(map(is_matchable_type, expected_type)): return True return False
is_matchable_type
identifier_name
wrap_matcher.py
import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x): """Wraps argument in a matcher, if necessary. :returns: the ...
return True return False
expected_type and \ all(map(is_matchable_type, expected_type)):
random_line_split
wrap_matcher.py
import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x): """Wraps argument in a matcher, if necessary. :returns: the ...
return False
return True
conditional_block
InvitationAction.ts
/* * Wire * Copyright (C) 2018 Wire Swiss GmbH * * 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 progr...
const newInvite: NewTeamInvitation = { email: invitationEmail, inviter_name: selfSelector.getSelfName(state), locale: languageSelector.getLanguage(state), role: Role.MEMBER, }; const teamId = selfSelector.getSelfTeamId(state); try { const createdInvite ...
{ const error = new BackendError({ code: HTTP_STATUS.CONFLICT, label: BackendError.LABEL.ALREADY_INVITED, message: 'This email has already been invited', }); dispatch(InvitationActionCreator.failedAddInvite(error)); throw error; }
conditional_block
InvitationAction.ts
/* * Wire * Copyright (C) 2018 Wire Swiss GmbH * * 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 progr...
{ invite = (invitation: {email: string}): ThunkAction => { return async (dispatch, getState, {apiClient}) => { dispatch(InvitationActionCreator.startAddInvite()); const state = getState(); const inviteList = InviteSelector.getInvites(state); const invitationEmail = invitation.email?.toLow...
InvitationAction
identifier_name
InvitationAction.ts
/* * Wire * Copyright (C) 2018 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify
* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License ...
* 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.
random_line_split
args.ts
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors ma...
'Defaults to 52428800 (50MB)', type: Number, defaultValue: 52428800, }, { name: 'port', alias: 'p', description: 'The port to serve from. Defaults to 8080', type: Number, }, { name: 'hostname', alias: 'H', description: 'The hostname to serve from. Defaults to localhos...
name: 'compile-cache', description: 'Maximum size in bytes (actually, UTF-8 characters) of ' + 'the cache used to store results for JavaScript compilation. Cache ' + 'size includes the uncompiled and compiled file content lengths. ' +
random_line_split
hmm.py
#author Matt Jacobsen ''' This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM). Implement a Baum-Welch algorithm (like EM?) to learn parameters Implement a Viterbi algorithm to learn structure. Implement a forward-backward algorithm (like BP) to do inference over the ...
(): pass #learn HMM structure from a set of observations def viterbi(): pass if __name__ == "__main__": if len(sys.argv) < 2: print 'missing test input' sys.exit() hmm = HMM() ''' print 'forward' pp.pprint(hmm.forward(sys.argv[1])) print 'backward' pp.pprint(hmm.backward(sys.argv[1])) ''' pri...
baumwelch
identifier_name
hmm.py
#author Matt Jacobsen ''' This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM). Implement a Baum-Welch algorithm (like EM?) to learn parameters Implement a Viterbi algorithm to learn structure. Implement a forward-backward algorithm (like BP) to do inference over the ...
return p #learn HMM parameters (emission and transition probabilities) from a set of observations def baumwelch(): pass #learn HMM structure from a set of observations def viterbi(): pass if __name__ == "__main__": if len(sys.argv) < 2: print 'missing test input' sys.exit() hmm = HMM() ''' p...
for j in range(0, len(p[i])): p[i][j] = p[i][j] / sum_p_i[j]
conditional_block
hmm.py
#author Matt Jacobsen ''' This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM). Implement a Baum-Welch algorithm (like EM?) to learn parameters Implement a Viterbi algorithm to learn structure. Implement a forward-backward algorithm (like BP) to do inference over the ...
#learn HMM parameters (emission and transition probabilities) from a set of observations def baumwelch(): pass #learn HMM structure from a set of observations def viterbi(): pass if __name__ == "__main__": if len(sys.argv) < 2: print 'missing test input' sys.exit() hmm = HMM() ''' print 'forwar...
alpha = self.forward(O) beta = self.backward(O) p = [0.0]*self.numstates #dot product between alpha and beta for i in range(0, len(p)): p[i] = [0.0] * len(alpha[i]) for j in range(0, len(alpha[i])): p[i][j] += alpha[i][j] * beta[i][j] #normalize to be a distribution sum_p_i = [0.0]*len(p[0]) fo...
identifier_body
hmm.py
#author Matt Jacobsen ''' This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM). Implement a Baum-Welch algorithm (like EM?) to learn parameters Implement a Viterbi algorithm to learn structure. Implement a forward-backward algorithm (like BP) to do inference over the ...
sum_p_i = [0.0]*len(p[0]) for i in range(0,len(p)): for j in range(0, len(p[i])): sum_p_i[j] += p[i][j] for i in range(0,len(p)): for j in range(0, len(p[i])): p[i][j] = p[i][j] / sum_p_i[j] return p #learn HMM parameters (emission and transition probabilities) from a set of observations def ...
for j in range(0, len(alpha[i])): p[i][j] += alpha[i][j] * beta[i][j] #normalize to be a distribution
random_line_split
user.rs
// // FSUIPC library // Copyright (c) 2015 Alvaro Polo // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::ffi::CString; use std::io; use std::os::raw::c_voi...
} pub struct UserSession<'a> { handle: &'a mut UserHandle, buffer: MutRawBytes, } impl<'a> Session for UserSession<'a> { fn read_bytes(&mut self, offset: u16, dest: *mut u8, len: usize) -> io::Result<usize> { self.buffer.write_rsd(offset, dest, len) } fn write_bytes(&mut self, offset: u1...
{ unsafe { GlobalDeleteAtom(self.file_mapping_atom); UnmapViewOfFile(self.data as *const c_void); CloseHandle(self.file_mapping); } }
identifier_body
user.rs
// // FSUIPC library // Copyright (c) 2015 Alvaro Polo // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::ffi::CString; use std::io; use std::os::raw::c_voi...
{ handle: HWND, file_mapping_atom: ATOM, file_mapping: HANDLE, msg_id: u32, data: *mut u8, } impl UserHandle { pub fn new() -> io::Result<Self> { unsafe { let win_name = CString::new("UIPCMAIN").unwrap(); let handle = FindWindowExA( ptr::null_mut...
UserHandle
identifier_name
user.rs
// // FSUIPC library // Copyright (c) 2015 Alvaro Polo // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::ffi::CString; use std::io; use std::os::raw::c_voi...
impl<'a> Session for UserSession<'a> { fn read_bytes(&mut self, offset: u16, dest: *mut u8, len: usize) -> io::Result<usize> { self.buffer.write_rsd(offset, dest, len) } fn write_bytes(&mut self, offset: u16, src: *const u8, len: usize) -> io::Result<usize> { self.buffer.write_wsd(offset, s...
buffer: MutRawBytes, }
random_line_split
user.rs
// // FSUIPC library // Copyright (c) 2015 Alvaro Polo // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::ffi::CString; use std::io; use std::os::raw::c_voi...
let file_mapping_name = CString::new( format!("FsasmLib:IPC:{:x}:{:x}", GetCurrentProcessId(), next_file_mapping_index())).unwrap(); let file_mapping_atom = GlobalAddAtomA(file_mapping_name.as_ptr()); if file_mapping_atom == ...
{ return Err(io::Error::new( io::ErrorKind::ConnectionRefused, "cannot connect to user FSUIPC: cannot register window message")); }
conditional_block
movies-list.component.ts
import {Component, OnInit} from '@angular/core'; import {Http} from '@angular/http'; @Component({ selector: 'mvdb-app', templateUrl: 'movies-list.component.html' }) export class MovieListComponent implements OnInit {
searched: string; sortedBy: string = 'imdbRating'; orderedBy: string = 'desc'; sortItems = [{name: 'Title', value: "Title"}, {name: 'Year', value: "Year"}, {name: 'Rating', value: "imdbRating"}]; orderItems = [{name: 'Asc', value: "asc"}, {name: 'Desc', value: "desc"}]; constructor(http: Http)...
movies: Array<any>; pageTitle: string = "Top iMDB Movies";
random_line_split
movies-list.component.ts
import {Component, OnInit} from '@angular/core'; import {Http} from '@angular/http'; @Component({ selector: 'mvdb-app', templateUrl: 'movies-list.component.html' }) export class MovieListComponent implements OnInit { movies: Array<any>; pageTitle: string = "Top iMDB Movies"; searched: string; ...
(http: Http) { //called first time before the ngOnInit() http.get('../data/movies.json') .map(res => res.json()) // Map will change your response ot json() .subscribe(movies => this.movies = movies, err => console.log('error:', err) ); } ngO...
constructor
identifier_name
movies-list.component.ts
import {Component, OnInit} from '@angular/core'; import {Http} from '@angular/http'; @Component({ selector: 'mvdb-app', templateUrl: 'movies-list.component.html' }) export class MovieListComponent implements OnInit { movies: Array<any>; pageTitle: string = "Top iMDB Movies"; searched: string; ...
}
{ //called after the constructor and called after the first ngOnChanges }
identifier_body
swiper-bundle.cjs.js
/** * Swiper 6.2.0 * Most modern mobile touch slider and framework with hardware accelerated transitions * http://swiperjs.com * * Copyright 2014-2020 Vladimir Kharlampidi * * Released under the MIT License * * Released on: September 4, 2020 */ 'use strict'; Object.defineProperty(exports, '__esModule', { va...
(ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Swiper = _interopDefault(require('./cjs/components/core/core-class')); var Virtual = _interopDefault(require('./cjs/components/virtual/virtual')); var Keyboard = _interopDefault(require('./cjs/components/keyboard/keyboard'))...
_interopDefault
identifier_name
swiper-bundle.cjs.js
/** * Swiper 6.2.0 * Most modern mobile touch slider and framework with hardware accelerated transitions * http://swiperjs.com * * Copyright 2014-2020 Vladimir Kharlampidi * * Released under the MIT License * * Released on: September 4, 2020 */ 'use strict'; Object.defineProperty(exports, '__esModule', { va...
var Pagination = _interopDefault(require('./cjs/components/pagination/pagination')); var Scrollbar = _interopDefault(require('./cjs/components/scrollbar/scrollbar')); var Parallax = _interopDefault(require('./cjs/components/parallax/parallax')); var Zoom = _interopDefault(require('./cjs/components/zoom/zoom')); var Laz...
var Mousewheel = _interopDefault(require('./cjs/components/mousewheel/mousewheel')); var Navigation = _interopDefault(require('./cjs/components/navigation/navigation'));
random_line_split
swiper-bundle.cjs.js
/** * Swiper 6.2.0 * Most modern mobile touch slider and framework with hardware accelerated transitions * http://swiperjs.com * * Copyright 2014-2020 Vladimir Kharlampidi * * Released under the MIT License * * Released on: September 4, 2020 */ 'use strict'; Object.defineProperty(exports, '__esModule', { va...
var Swiper = _interopDefault(require('./cjs/components/core/core-class')); var Virtual = _interopDefault(require('./cjs/components/virtual/virtual')); var Keyboard = _interopDefault(require('./cjs/components/keyboard/keyboard')); var Mousewheel = _interopDefault(require('./cjs/components/mousewheel/mousewheel')); var...
{ return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
identifier_body
CognateParser.py
import re from nexusmaker.tools import natsort is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""") class CognateParser(object): UNIQUE_IDENTIFIER = "u_" def __init__(self, strict=True, uniques=True, sort=True): """ Parses cognates. - strict (default=True): remove dubious cognat...
else: value = [v.replace("?", "") for v in value] # remove any empty things in the list value = [v for v in value if len(v) > 0] if self.sort: value = natsort(value) return value else: raise ValueError("%s...
return self.get_next_unique()
conditional_block
CognateParser.py
import re from nexusmaker.tools import natsort is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""") class CognateParser(object): UNIQUE_IDENTIFIER = "u_" def __init__(self, strict=True, uniques=True, sort=True): """ Parses cognates. - strict (default=True): remove dubious cognat...
self.sort = sort self.unique_id = 0 def is_unique_cognateset(self, cog, labelled=False): if not labelled: return str(cog).startswith(self.UNIQUE_IDENTIFIER) else: return "_%s" % self.UNIQUE_IDENTIFIER in str(cog) def _split_combined_cognate(self, cognate...
random_line_split
CognateParser.py
import re from nexusmaker.tools import natsort is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""") class CognateParser(object): UNIQUE_IDENTIFIER = "u_" def __init__(self, strict=True, uniques=True, sort=True): """ Parses cognates. - strict (default=True): remove dubious cognat...
(self, cognate): m = is_combined_cognate.findall(cognate) return [m[0][0], cognate] if m else [cognate] def get_next_unique(self): if not self.uniques: return [] self.unique_id = self.unique_id + 1 return ["%s%d" % (self.UNIQUE_IDENTIFIER, self.unique_id)] d...
_split_combined_cognate
identifier_name
CognateParser.py
import re from nexusmaker.tools import natsort is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""") class CognateParser(object): UNIQUE_IDENTIFIER = "u_" def __init__(self, strict=True, uniques=True, sort=True): """ Parses cognates. - strict (default=True): remove dubious cognat...
def get_next_unique(self): if not self.uniques: return [] self.unique_id = self.unique_id + 1 return ["%s%d" % (self.UNIQUE_IDENTIFIER, self.unique_id)] def parse_cognate(self, value): raw = value if value is None: return self.get_next_unique() ...
m = is_combined_cognate.findall(cognate) return [m[0][0], cognate] if m else [cognate]
identifier_body
lsm303d.py
#!/usr/bin/env python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2017 Intel Corporation. # # The MIT License # # 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 restrictio...
if __name__ == '__main__': main()
sensor.update() data = sensor.getAccelerometer() print("Accelerometer x:", data[0], end=' ') print(" y:", data[1], end=' ') print(" z:", data[2], end=' ') print(" g") data = sensor.getMagnetometer() print("Magnetometer x:", data[0], end=' ') print(" y:",...
conditional_block
lsm303d.py
#!/usr/bin/env python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2017 Intel Corporation. # # The MIT License # # 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 restrictio...
(): # Instantiate a BMP250E instance using default i2c bus and address sensor = sensorObj.LSM303D() ## Exit handlers ## # This function stops python from printing a stacktrace when you # hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This function lets you run c...
main
identifier_name
lsm303d.py
#!/usr/bin/env python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2017 Intel Corporation. # # The MIT License # # 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 restrictio...
data = sensor.getAccelerometer() print("Accelerometer x:", data[0], end=' ') print(" y:", data[1], end=' ') print(" z:", data[2], end=' ') print(" g") data = sensor.getMagnetometer() print("Magnetometer x:", data[0], end=' ') print(" y:", data[1], end=' ...
sensor = sensorObj.LSM303D() ## Exit handlers ## # This function stops python from printing a stacktrace when you # hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This function lets you run code on exit def exitHandler(): print("Exiting") sys.exit(0)...
identifier_body
lsm303d.py
#!/usr/bin/env python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2017 Intel Corporation. # # The MIT License # # 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 restrictio...
print(" z:", data[2], end=' ') print(" g") data = sensor.getMagnetometer() print("Magnetometer x:", data[0], end=' ') print(" y:", data[1], end=' ') print(" z:", data[2], end=' ') print(" uT") print("Temperature: ", sensor.getTemperature()) prin...
data = sensor.getAccelerometer() print("Accelerometer x:", data[0], end=' ') print(" y:", data[1], end=' ')
random_line_split
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, a...
(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
is_empty
identifier_name
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, a...
pub enum TextContent { Text(Box<str>), GeneratedContent(Vec<ContentItem>), } impl TextContent { pub fn is_empty(&self) -> bool { match *self { TextContent::Text(_) => false, TextContent::GeneratedContent(ref content) => content.is_empty(), } } }
damage } }
random_line_split
wrapper.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, a...
fn flow_debug_id(self) -> usize { self.borrow_layout_data() .map_or(0, |d| d.flow_construction_result.debug_id()) } } pub trait GetStyleAndLayoutData<'dom> { fn get_style_and_layout_data(self) -> Option<StyleAndLayoutData<'dom>>; } impl<'dom, T> GetStyleAndLayoutData<'dom> for T wher...
{ self.get_style_and_layout_data() .map(|d| d.layout_data.borrow_mut()) }
identifier_body