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
TabNote.ts
import { Note } from "./Note"; import { Fraction } from "../../Common/DataObjects/Fraction"; import { VoiceEntry } from "./VoiceEntry"; import { SourceStaffEntry } from "./SourceStaffEntry"; import { Pitch } from "../../Common/DataObjects/Pitch"; import { SourceMeasure } from "./SourceMeasure"; export class TabNote ex...
}
{ return this.vibratoStroke; }
identifier_body
garbage_collector.d.ts
/** * Copyright 2017 Google 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 law or agreed to i...
* - LocalView reference identified also by a target ID. * - Local mutation reference identified by a batch ID. * * The idea is that we want to keep a document around at least as long as any * remote target or local (latency compensated) view is referencing it, or * there's an outstanding local mutation to that ...
* * Usually the the local store this means tracking of three different types of * references to a document: * - RemoteTarget reference identified by a target ID.
random_line_split
url.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
* @param {string} [siteId] Site ID. If not defined, current site. * @return {Promise<any>} Promise resolved when the data is invalidated. */ invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<any> { siteId = siteId || this.sitesProvider.getCurrentSiteId(); ...
* * @param {number} moduleId The module ID. * @param {number} courseId Course ID of the module.
random_line_split
url.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
return Promise.reject(null); }); }); } /** * Get a url by course module ID. * * @param {number} courseId Course ID. * @param {number} cmId Course module ID. * @param {string} [siteId] Site ID. If not defined, current site. * @return {Promi...
{ const currentUrl = response.urls.find((url) => { return url[key] == value; }); if (currentUrl) { return currentUrl; } }
conditional_block
url.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
/** * Report the url as being viewed. * * @param {number} id Module ID. * @return {Promise<any>} Promise resolved when the WS call is successful. */ logView(id: number): Promise<any> { const params = { urlid: id }; return this.sitesProvider.getCur...
{ return this.sitesProvider.wsAvailableInCurrentSite('mod_url_get_urls_by_courses'); }
identifier_body
url.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
(moduleId: number, courseId: number, siteId?: string): Promise<any> { siteId = siteId || this.sitesProvider.getCurrentSiteId(); const promises = []; promises.push(this.invalidateUrlData(courseId, siteId)); promises.push(this.courseProvider.invalidateModule(moduleId, siteId, 'url')); ...
invalidateContent
identifier_name
breakaesecb.rs
use std::env; use std::io; use std::io::Write; use common::{err, ascii, util, challenge}; use common::cipher::oracle; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 12, title: "Byte-at-a-time ECB decryption (Simple)", help: "param1: path t...
} let plaintext = try!(ascii::raw_to_str(&plainraw)); Ok(plaintext) } pub fn detect_blocksize_plainsize(cbox: &cb::CipherBox, max: usize) -> Result<(usize, usize), err::Error> { let len1 = try!(cbox.encrypt(&Vec::<u8>::new())).len(); let mut prefix = vec![65 as u8]; for _ in 0 .. max { ...
{ prefix = vec![65 as u8; blocksize - 1]; block_no += 1; }
conditional_block
breakaesecb.rs
use std::env; use std::io; use std::io::Write; use common::{err, ascii, util, challenge}; use common::cipher::oracle; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 12, title: "Byte-at-a-time ECB decryption (Simple)", help: "param1: path t...
() -> err::ExitCode { let input_filepath = match env::args().nth(2) { Some(v) => v, None => { println!("please specify input data (base64 encoded) filepath"); return exit_err!(); } }; let cbox = rtry!(cb::init_from_file(&input_filepath), exit_err!()); rtry!(break_aes_ecb(&cbox), exit...
interactive
identifier_name
breakaesecb.rs
use std::env; use std::io; use std::io::Write; use common::{err, ascii, util, challenge}; use common::cipher::oracle; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 12, title: "Byte-at-a-time ECB decryption (Simple)", help: "param1: path t...
{ let input_filepath = match env::args().nth(2) { Some(v) => v, None => { println!("please specify input data (base64 encoded) filepath"); return exit_err!(); } }; let cbox = rtry!(cb::init_from_file(&input_filepath), exit_err!()); rtry!(break_aes_ecb(&cbox), exit_err!()); exit_...
identifier_body
breakaesecb.rs
use std::env; use std::io; use std::io::Write; use common::{err, ascii, util, challenge}; use common::cipher::oracle; use common::cipher::cipherbox as cb; pub static info: challenge::Info = challenge::Info { no: 12, title: "Byte-at-a-time ECB decryption (Simple)", help: "param1: path t...
//println!("{} - {}", printr!(&prefix), printr!(&dict_prefix)); let cipher = try!(cbox.encrypt(&prefix)); let dict = try!(cb::make_dict(&dict_prefix, &cbox, max_u8)); let cipher_block: Vec<u8> = cipher.chunks(blocksize).nth(block_no).unwrap().to_vec(); let mut raw_char: u8 = 0...
let mut dict_prefix = prefix.clone(); for i in 0 .. plaintext_size {
random_line_split
crypto.py
import Aplicacion import Probabilidades as pr from Menu import * from Variable import * from validador import * #------------------------------------------------ #--------------- TODO --------------------------- #------------------------------------------------ # 1) Lista de tareas pendientes a implementar. # ...
return sign + base36 def encriptar(self): self.espaciador() print "Ingrese la clave a encriptar:" clave = int(validador.ingresar(str),36) print "Ingrese la semilla a utilizar:" semilla = int(validador.ingresar(str),36) ...
base36 = alphabet[i] + base36
random_line_split
crypto.py
import Aplicacion import Probabilidades as pr from Menu import * from Variable import * from validador import * #------------------------------------------------ #--------------- TODO --------------------------- #------------------------------------------------ # 1) Lista de tareas pendientes a implementar. # ...
while number != 0: number, i = divmod(number, len(alphabet)) base36 = alphabet[i] + base36 return sign + base36 def encriptar(self): self.espaciador() print "Ingrese la clave a encriptar:" clave = int(validador....
return sign + alphabet[number]
conditional_block
crypto.py
import Aplicacion import Probabilidades as pr from Menu import * from Variable import * from validador import * #------------------------------------------------ #--------------- TODO --------------------------- #------------------------------------------------ # 1) Lista de tareas pendientes a implementar. # ...
(Aplicacion.Aplicacion): """ FILLME """ #----------------------- #--- inicializacion ---- #----------------------- def iniciar(self,**args): #variables de programa self.probs = pr.Probabilidad() self.probs.cargarDatos("0","1","2","3","4","5","6","7","8"...
Crypto
identifier_name
crypto.py
import Aplicacion import Probabilidades as pr from Menu import * from Variable import * from validador import * #------------------------------------------------ #--------------- TODO --------------------------- #------------------------------------------------ # 1) Lista de tareas pendientes a implementar. # ...
def doDesencriptar(self,criptado,semilla): return self.base36encode(int(criptado,36) - int(semilla,36)) def generarSemilla(self,longitud): crypto = "" for i in range(0,longitud): crypto += self.probs.generar() return crypto #--------------...
self.espaciador() print "Ingrese el codigo encriptado:" criptado = validador.ingresar(str) print "Ingrese la semilla utilizada:" semilla = validador.ingresar(str) self.espaciador() print "el codigo descencriptado es:" print sel...
identifier_body
classblackbone_1_1_m_map.js
var classblackbone_1_1_m_map = [ [ "MMap", "classblackbone_1_1_m_map.html#a73dce850d2a2b9949c3bcb6ac1ac9abe", null ], [ "~MMap", "classblackbone_1_1_m_map.html#af0d82aa41970f29d53dfc92ada2beefa", null ], [ "Cleanup", "classblackbone_1_1_m_map.html#a34bc7201d03a51463824d81b2e68c3b6", null ],
[ "MapImage", "classblackbone_1_1_m_map.html#a5454130bc294fe50ecd63a881ef7917e", null ], [ "reset", "classblackbone_1_1_m_map.html#af662672364ee90cef246b719b5691ee0", null ], [ "UnmapAllModules", "classblackbone_1_1_m_map.html#ab2c907908d1db59db079d4d2bfe4dc13", null ] ];
[ "MapImage", "classblackbone_1_1_m_map.html#ac32ee99111f95b472fb95834657f0ac7", null ],
random_line_split
class_wanzyee_studio_1_1_crypto_long.js
var class_wanzyee_studio_1_1_crypto_long = [ [ "CryptoLong", "class_wanzyee_studio_1_1_crypto_long.html#a4b1cd1e431c417c3e55cea9504b4ce6a", null ], [ "ReadObfuscated", "class_wanzyee_studio_1_1_crypto_long.html#af57cdb2e3959435a73f296e10919600e", null ], [ "WriteObfuscated", "class_wanzyee_studio_1_1_crypto...
];
[ "value", "class_wanzyee_studio_1_1_crypto_long.html#abcf64b84c9ecb7087867368699e3d812", null ]
random_line_split
download_samples.py
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> 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 right...
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE...
The above copyright notice and this permission notice shall be included in
random_line_split
download_samples.py
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> 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 right...
main_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(main_dir) # Now extract the samples download_submodule("tobspr", "RenderPipeline-Samples", ".", ["README.md", "LICENSE"])
conditional_block
topics.tsx
import * as React from 'react' import TopicColumn from './topicColumn' const Topics = ({ activity, createNewTopic, topicOptions, handleTopicsChange, }) => { const [topicsEnabled, setTopicsEnabled] = React.useState(!!activity.topic_ids.length) React.useEffect(() => { if (!topicsEnabled) { handleTopicsCh...
<TopicColumn {...sharedTopicColumnProps} levelNumber={3} /> <TopicColumn {...sharedTopicColumnProps} levelNumber={2} /> <TopicColumn {...sharedTopicColumnProps} levelNumber={1} /> <TopicColumn {...sharedTopicColumnProps} levelNumber={0} /> </section> ) } export default Topics
<label>Topics enabled</label> </section>
random_line_split
topics.tsx
import * as React from 'react' import TopicColumn from './topicColumn' const Topics = ({ activity, createNewTopic, topicOptions, handleTopicsChange, }) => { const [topicsEnabled, setTopicsEnabled] = React.useState(!!activity.topic_ids.length) React.useEffect(() => { if (!topicsEnabled) { handleTopicsCh...
const sharedTopicColumnProps = { getFilteredOptionsForLevel, selectTopic: onChangeTopics, getSelectedOptionForLevel, createNewTopic } return ( <section className="topics-container enabled-attribute-container"> <section className="enable-topics-container checkbox-container"> <i...
{ setTopicsEnabled(!topicsEnabled) }
identifier_body
topics.tsx
import * as React from 'react' import TopicColumn from './topicColumn' const Topics = ({ activity, createNewTopic, topicOptions, handleTopicsChange, }) => { const [topicsEnabled, setTopicsEnabled] = React.useState(!!activity.topic_ids.length) React.useEffect(() => { if (!topicsEnabled) { handleTopicsCh...
return topicOptions.filter(to => to.level === level) } function getFilteredOptionsForLevel(level: number) { const allOptions = getOptionsForLevel(level) const selectedLevelTwo = getSelectedOptionForLevel(2) const selectedLevelThree = getSelectedOptionForLevel(3) if (level === 3 && selectedLev...
{ return [] }
conditional_block
topics.tsx
import * as React from 'react' import TopicColumn from './topicColumn' const Topics = ({ activity, createNewTopic, topicOptions, handleTopicsChange, }) => { const [topicsEnabled, setTopicsEnabled] = React.useState(!!activity.topic_ids.length) React.useEffect(() => { if (!topicsEnabled) { handleTopicsCh...
(level: number) { if (!topicsEnabled) { return [] } return topicOptions.filter(to => to.level === level) } function getFilteredOptionsForLevel(level: number) { const allOptions = getOptionsForLevel(level) const selectedLevelTwo = getSelectedOptionForLevel(2) const selectedLevelThree = getSelect...
getOptionsForLevel
identifier_name
FastqFileFactory.py
import os,re,fnmatch from ehive.runnable.IGFBaseJobFactory import IGFBaseJobFactory class FastqFileFactory(IGFBaseJobFactory): ''' A job factory class for creating fan jobs for demultilexed fastq files ''' def param_defaults(self): params_dict=super(FastqFileFactory,self).param_defaults() params_dict.u...
elif filter_keyword and not fnmatch.fnmatch(file, filter_keyword ): fastq_list.append({'fastq_file':os.path.join(root,file)}) # add fastq file to the list if its not a match self.param('sub_tasks',fastq_list) # add fastq files...
fastq_list.append({'fastq_file':os.path.join(root,file)}) # add fastq file to the list if its amatch
random_line_split
FastqFileFactory.py
import os,re,fnmatch from ehive.runnable.IGFBaseJobFactory import IGFBaseJobFactory class
(IGFBaseJobFactory): ''' A job factory class for creating fan jobs for demultilexed fastq files ''' def param_defaults(self): params_dict=super(FastqFileFactory,self).param_defaults() params_dict.update({ 'required_keyword':None, 'filter_keyword':None, 'read_pattern':'\S+_L00\d_R...
FastqFileFactory
identifier_name
FastqFileFactory.py
import os,re,fnmatch from ehive.runnable.IGFBaseJobFactory import IGFBaseJobFactory class FastqFileFactory(IGFBaseJobFactory): ''' A job factory class for creating fan jobs for demultilexed fastq files ''' def param_defaults(self): params_dict=super(FastqFileFactory,self).param_defaults() params_dict.u...
self.param('sub_tasks',fastq_list) # add fastq files to the dataflow except Exception as e: message = \ 'seqrun: {2}, Error in {0}: {1}'.\ format( self.__class__.__name__, e, seqrun_igf_id) s...
for file in files: if fnmatch.fnmatch(file, '*.fastq.gz'): # only consider fastq.gz files for now if re.search(read_pattern,file): # skip if its not R1 and R2 reads and not illumina format name if required_keyword and f...
conditional_block
FastqFileFactory.py
import os,re,fnmatch from ehive.runnable.IGFBaseJobFactory import IGFBaseJobFactory class FastqFileFactory(IGFBaseJobFactory): ''' A job factory class for creating fan jobs for demultilexed fastq files ''' def param_defaults(self): params_dict=super(FastqFileFactory,self).param_defaults() params_dict.u...
if required_keyword and fnmatch.fnmatch(file, required_keyword ): fastq_list.append({'fastq_file':os.path.join(root,file)}) # add fastq file to the list if its amatch elif filter_keyword and not fnmatch.fnmatch(file, filter_keyword ): fastq_...
try: fastq_dir=self.param_required('fastq_dir') seqrun_igf_id=self.param_required('seqrun_igf_id') required_keyword=self.param('required_keyword') filter_keyword=self.param('filter_keyword') read_pattern=self.param_required('read_pattern') if required_keyword is None and \ ...
identifier_body
viewer-options-spec.js
/* * Copyright 2015 Trim-marks Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your opt...
* * You should have received a copy of the GNU Affero General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import vivliostyle from "../../../src/vivliostyle"; import PageViewMode from "../../../src/models/page-view-mode"; import ViewerOptions from "../../../src/models...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details.
random_line_split
expo.py
import RPi.GPIO as GPIO import time import pygame GPIO.setmode(GPIO.BCM) PIR_PIN = 4 GPIO.setup(PIR_PIN,GPIO.IN) time.sleep(2) playing = 0 start = 0 count = 0 limit = 10 while True: time.sleep(1) if GPIO.input(PIR_PIN):
if count == limit and playing == 1: playing = 0 pygame.mixer.music.stop() pygame.mixer.quit() #print "MUSICA stop" if count == limit: count = 0 #print "temps: "+str(count) count = count + 1
if playing == 0: start = 1 if playing == 1: start = 0 count = 0 #print "PIR activat" if start == 1: pygame.mixer.init() pygame.mixer.music.load("/home/pi/eb.mp3") pygame.mixer.music.play(-1,0.0) playing = 1 #print "MUSICA inici"
conditional_block
expo.py
import RPi.GPIO as GPIO import time import pygame GPIO.setmode(GPIO.BCM)
count = 0 limit = 10 while True: time.sleep(1) if GPIO.input(PIR_PIN): if playing == 0: start = 1 if playing == 1: start = 0 count = 0 #print "PIR activat" if start == 1: pygame.mixer.init() pygame.mixer.music.load("/home/pi/eb.mp3") pygame.mixer.music.play(-1,0.0) playing = 1 #print "M...
PIR_PIN = 4 GPIO.setup(PIR_PIN,GPIO.IN) time.sleep(2) playing = 0 start = 0
random_line_split
bencher.py
#! /usr/bin/env python3 # Suggest name to z3 binary based on it its sha import sys import words import subprocess import argparse import os.path import shutil from pathlib import Path import yaml class Bencher(object): def __init__(self): self._name = 'bencher' self._help = 'Make benchmark di...
inverse = dict() for id, src in enumerate(args.files): idx_str = num_fmt.format(idx=id) dst_name = f'{prefix}-{idx_str}.{suffix}' dst = out_dir / dst_name if (args.verbose): print(f'{src} --> {dst}') file_action(src, dst) ...
file_action = shutil.copy2
conditional_block
bencher.py
#! /usr/bin/env python3 # Suggest name to z3 binary based on it its sha import sys import words import subprocess import argparse import os.path import shutil from pathlib import Path import yaml class Bencher(object): def __init__(self): self._name = 'bencher' self._help = 'Make benchmark di...
(src, dst): pass file_action = _dry_run_action elif args.mv: file_action = shutil.move else: file_action = shutil.copy2 inverse = dict() for id, src in enumerate(args.files): idx_str = num_fmt.format(idx=id) ds...
_dry_run_action
identifier_name
bencher.py
#! /usr/bin/env python3 # Suggest name to z3 binary based on it its sha import sys import words import subprocess import argparse import os.path import shutil from pathlib import Path import yaml class Bencher(object): def __init__(self): self._name = 'bencher' self._help = 'Make benchmark di...
ap.add_argument('--dry-run', action='store_true') return ap def run(self, args=None): num_files = len(args.files) num_fmt = '{idx:0' + str(len(str(num_files))) + '}' out_dir = Path(args.out) out_dir.mkdir(parents=True, exist_ok=True) prefix = args.prefix ...
help='Move (instead of copy) benchmarks into new location') ap.add_argument('--verbose', '-v', action='store_true')
random_line_split
bencher.py
#! /usr/bin/env python3 # Suggest name to z3 binary based on it its sha import sys import words import subprocess import argparse import os.path import shutil from pathlib import Path import yaml class Bencher(object): def __init__(self): self._name = 'bencher' self._help = 'Make benchmark di...
action='store_true', help='Move (instead of copy) benchmarks into new location') ap.add_argument('--verbose', '-v', action='store_true') ap.add_argument('--dry-run', action='store_true') return ap def run(self, args=None): num_files = len(args.files) nu...
ap.add_argument('--suffix', '-s', metavar='EXT', type=str, default='smt2', help='File extension') ap.add_argument('--prefix', '-p', metavar='PRE...
identifier_body
validate_no_inline_with_raw_response_type.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::no_inline::{ is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME, }; use common::{Diagn...
fn validate_fragment(&mut self, fragment: &FragmentDefinition) -> DiagnosticsResult<()> { if let Some(directive) = fragment.directives.named(*NO_INLINE_DIRECTIVE_NAME) { if !is_raw_response_type_enabled(directive) { return Err(vec![ Diagnostic::error( ...
{ validate_map(program.operations(), |operation| { if operation .directives .named(*RAW_RESPONSE_TYPE_NAME) .is_some() { self.current_query_location = operation.name.location; self.default_validate_operation(...
identifier_body
validate_no_inline_with_raw_response_type.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::no_inline::{ is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME, }; use common::{Diagn...
(program: &'a Program) -> Self { Self { validated: Default::default(), current_query_location: Location::new(SourceLocationKey::generated(), Span::empty()), program, } } } impl<'a> Validator for NoInlineRawResponseTypeValidator<'a> { const NAME: &'static str ...
new
identifier_name
validate_no_inline_with_raw_response_type.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::no_inline::{ is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME, }; use common::{Diagn...
Self { validated: Default::default(), current_query_location: Location::new(SourceLocationKey::generated(), Span::empty()), program, } } } impl<'a> Validator for NoInlineRawResponseTypeValidator<'a> { const NAME: &'static str = "NoInlineRawResponseTypeValidat...
fn new(program: &'a Program) -> Self {
random_line_split
validate_no_inline_with_raw_response_type.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::no_inline::{ is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME, }; use common::{Diagn...
}) } fn validate_fragment(&mut self, fragment: &FragmentDefinition) -> DiagnosticsResult<()> { if let Some(directive) = fragment.directives.named(*NO_INLINE_DIRECTIVE_NAME) { if !is_raw_response_type_enabled(directive) { return Err(vec![ Diagnost...
{ Ok(()) }
conditional_block
test_iconpacker.py
import os from iconpacker import IconList test_icon = "/media/hda7/Graphics/png/Classic_Truck/128.png" icon_theme = IconList() def initialization(): treestore = icon_theme.setup_treeview('data/legacy-icon-mapping.xml') if treestore != None: for i in icon_theme.icon_list: icon_theme.set_item(i, test_icon) ret...
print "Theme Creation [FAILED]" return False print "Testing index file creation ..." if test_write_icon_theme(): print "Index file creation [PASSED]" else: print "Index file creation [FAILED]" return False #os.system("rm -rf %s/*" % icon_theme.build_path) def test_writing_themes(): initialization() ...
if test_make_theme(): print "Theme creation [PASSES]" else:
random_line_split
test_iconpacker.py
import os from iconpacker import IconList test_icon = "/media/hda7/Graphics/png/Classic_Truck/128.png" icon_theme = IconList() def initialization(): treestore = icon_theme.setup_treeview('data/legacy-icon-mapping.xml') if treestore != None: for i in icon_theme.icon_list: icon_theme.set_item(i, test_icon) ret...
(): icon_theme.build_paths() return True def test_icon_copying(): if icon_theme.copy_icon_files(): d = os.stat(test_icon) expected_size = d[6] * len(icon_theme.icon_list) - (4096 * len(icon_theme.categories_list)) print expected_size os.system ('du -c -b ' + icon_theme.tmp_ico_path) return True return F...
build_icon_paths
identifier_name
test_iconpacker.py
import os from iconpacker import IconList test_icon = "/media/hda7/Graphics/png/Classic_Truck/128.png" icon_theme = IconList() def initialization(): treestore = icon_theme.setup_treeview('data/legacy-icon-mapping.xml') if treestore != None: for i in icon_theme.icon_list: icon_theme.set_item(i, test_icon) ret...
else: print "Icon copying [FAILED]" return False print "Testing icon resizing ..." if test_resizing(): print "Resizing [PASSED]" else: print "Resizing [FAILED]" return False print "Testing Theme creation ..." if test_make_theme(): print "Theme creation [PASSES]" else: print "Theme Creation [FAIL...
print "Icon copying [PASSED]"
conditional_block
test_iconpacker.py
import os from iconpacker import IconList test_icon = "/media/hda7/Graphics/png/Classic_Truck/128.png" icon_theme = IconList() def initialization(): treestore = icon_theme.setup_treeview('data/legacy-icon-mapping.xml') if treestore != None: for i in icon_theme.icon_list: icon_theme.set_item(i, test_icon) ret...
def test_resizing(): if icon_theme.resize_icons(): return True else: return False def test_make_theme(): if icon_theme.make_icon_theme('TestTheme'): return True else: return False def test_write_icon_theme(): icon_theme.write_theme_file() def start_testing(): print "Testing treeview initialization .....
if icon_theme.copy_icon_files(): d = os.stat(test_icon) expected_size = d[6] * len(icon_theme.icon_list) - (4096 * len(icon_theme.categories_list)) print expected_size os.system ('du -c -b ' + icon_theme.tmp_ico_path) return True return False
identifier_body
uri.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
/** * The singularity of all resolving. * With URI as our one data type of truth, this method maps an absolute or relative path or URI to a URI using given base URI. * @param baseUri Absolute base URI * @param pathOrUri Relative/absolute path/URI * @returns Absolute URI */ export function ResolveUri(baseUri: ...
{ const lastPart = GetFilename(uri); const ext = lastPart.indexOf(".") === -1 ? "" : lastPart.split(".").reverse()[0]; return lastPart.substr(0, lastPart.length - ext.length - 1); }
identifier_body
uri.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// cut away last component const compLen = uri.split("/").reverse()[0].length; return uri.slice(0, uri.length - compLen); } export function MakeRelativeUri(baseUri: string, absoluteUri: string): string { return new URI(absoluteUri).relativeTo(baseUri).toString(); } /*********************** * OS abstraction ...
{ uri = uri.slice(0, uri.length - 1); }
conditional_block
uri.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} /*********************** * OS abstraction (writing files, enumerating files) ***********************/ import { readdir, mkdir, exists, writeFile } from "./async"; import { lstatSync } from "fs"; function isAccessibleFile(localPath: string) { try { return lstatSync(localPath).isFile(); } catch (e) { re...
random_line_split
uri.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(filePath: string): Promise<void> { var dir: string = dirname(filePath); if (!await exists(dir)) { await CreateDirectoryFor(dir); try { await mkdir(dir); } catch (e) { // mkdir throws if directory already exists - which happens occasionally due to race conditions } } } async function ...
CreateDirectoryFor
identifier_name
a3.js
downHeight=30; /*底部高度*/ var paddingHeight=11; /*页面内补丁高度 paddingTop+paddingBottom*/ var gridToolbar = null; /*按钮定义 */ var dgConf=null; /*dgConf配置信息*/ var dg1Conf=null; function initConf(){} /*在此初始化本页面的所有配置信息*/ function initButton(){ for(var i=0;i<gridToolbar.length;i++){ var b=gridToolbar[i];/*首次运行时所有按钮都是di...
'请选择您要删除的数据!',"info"); } function dg_refresh(){/*列表刷新按钮事件*/ } function dg_search(){/*列表搜索事件 search模式不再禁用其他面板*/ panelType="search"; $('#tab').tabs("select",1); } function dg_click(index){ /*切换回详细信息模式 首先判断tab的当前选项*/ if(panelType=="search"){ $('#tab').tabs("select",0); } } function dg_dbl(){/*列表双击事件 双击进入编辑模式*/ ...
('选择提示',
identifier_name
a3.js
downHeight=30; /*底部高度*/ var paddingHeight=11; /*页面内补丁高度 paddingTop+paddingBottom*/ var gridToolbar = null; /*按钮定义 */ var dgConf=null; /*dgConf配置信息*/ var dg1Conf=null; function initConf(){} /*在此初始化本页面的所有配置信息*/ function initButton(){ for(var i=0;i<gridToolbar.length;i++){ var b=gridToolbar[i];/*首次运行时所有按钮都是di...
dgConf.onLoadSuccess=dg_load; dgConf.onClickRow=dg_click; dgConf.onDblClickRow=dg_dbl; dgConf.onExpand=dg_expand; dgConf.collapsible=true; dgConf.collapseID="btn_collapse"; dgConf.pagination=true; dgConf.fit=true; dgConf.rownumbers=true; dgConf.singleSelect=true; dg1Conf.onClickRow=dg1_click; dg1Conf.onDbl...
dgConf.toolbar='#tb'; dgConf.onCollapse=dg_collapse; dgConf.onSelect=dg_select; dgConf.singleSelect=true;
random_line_split
a3.js
(btn2_search); $('#btn2_addItem').linkbutton({iconCls: 'icon-add'}).click(btn2_addItem); $('#btn2_editItem').linkbutton({iconCls: 'icon-edit'}).click(btn2_editItem); $('#btn2_rmItem').linkbutton({iconCls: 'icon-remove'}).click(btn2_rmItem); $('#btn2_ok').linkbutton({iconCls: 'icon-ok'}).click(btn2_ok); dgConf.too...
conditional_block
a3.js
downHeight=30; /*底部高度*/ var paddingHeight=11; /*页面内补丁高度 paddingTop+paddingBottom*/ var gridToolbar = null; /*按钮定义 */ var dgConf=null; /*dgConf配置信息*/ var dg1Conf=null; function initConf(){} /*在此初始化本页面的所有配置信息*/ function initButton(){ for(var i=0;i<gridToolbar.length;i++){ var b=gridToolbar[i];/*首次运行时所有按钮都是di...
dg_delete(){/*列表删除按钮触发事件*/ var confirmBack=function(r){ if(!r) return; var p=$('#dg').datagrid('getRowIndex',$('#dg').datagrid('getSelected')); /*执行服务器请求,完成服务端数据的删除 然后完成前端的删除*/ if (p == undefined){return} $('#dg').datagrid('cancelEdit', p) .datagrid('deleteRow', p); /*删除成功后应该刷新页面 并把下一条选中*/ var curr...
, rowData){/*选中事件 填充ff1 ff2 dg1*/ showChildGrid(rowData);/*子表模式下,重绘子表列表*/ showForm(rowData,"add"); useDetailMode(); } function dg_add(){/*列表新增按钮事件*/ useAddMode(); } function dg_edit(){/*列表编辑按钮触发事件*/ var row=$('#dg').datagrid('getSelected'); if(row){ useEditMode(); } else $.messager.alert('选择提示', '请选择您编辑的数...
identifier_body
core.py
"""Core functions used by the Thunder streaming feeder scripts, including asynchronous checking for new files. """ import errno import os import time from thunder_streaming.feeder.utils.filenames import getFilenamePostfix, getFilenamePrefix from thunder_streaming.feeder.utils.logger import global_logger from thunder_s...
next_batch_file = next(walker) delta = time.time() - os.stat(next_batch_file).st_mtime walker_restart_file = next_batch_file except StopIteration: # no files left, restart after polling interval if not filebatch: global_log...
filebatch.append(next_batch_file) files_left -= 1 next_batch_file = None # reset in case of exception on next line
random_line_split
core.py
"""Core functions used by the Thunder streaming feeder scripts, including asynchronous checking for new files. """ import errno import os import time from thunder_streaming.feeder.utils.filenames import getFilenamePostfix, getFilenamePrefix from thunder_streaming.feeder.utils.logger import global_logger from thunder_s...
else: fname_to_timepoint_fcn = getFilenamePostfix return fname_to_qname_fcn, fname_to_timepoint_fcn
fname_to_timepoint_fcn = RegexMatchToTimepointString.fromFile(opts.timepoint_regex_file).timepoint
conditional_block
core.py
"""Core functions used by the Thunder streaming feeder scripts, including asynchronous checking for new files. """ import errno import os import time from thunder_streaming.feeder.utils.filenames import getFilenamePostfix, getFilenamePrefix from thunder_streaming.feeder.utils.logger import global_logger from thunder_s...
def runloop(file_checkers, feeder, poll_time): """ Main program loop. This will check for new files in the passed input directories using file_check_generator, push any new files found into the passed Feeder subclass via its feed() method, wait for poll_time, and repeat forever. """ last_time = t...
if isinstance(source_dir_or_dirs, basestring): source_dirs = [source_dir_or_dirs] else: source_dirs = source_dir_or_dirs file_checkers = [file_check_generator(source_dir, mod_buffer_time, max_files=max_files, filename_predicate=filename_predicate) ...
identifier_body
core.py
"""Core functions used by the Thunder streaming feeder scripts, including asynchronous checking for new files. """ import errno import os import time from thunder_streaming.feeder.utils.filenames import getFilenamePostfix, getFilenamePrefix from thunder_streaming.feeder.utils.logger import global_logger from thunder_s...
(opts): if opts.prefix_regex_file: fname_to_qname_fcn = RegexMatchToQueueName.fromFile(opts.prefix_regex_file).queueName else: fname_to_qname_fcn = getFilenamePrefix if opts.timepoint_regex_file: fname_to_timepoint_fcn = RegexMatchToTimepointString.fromFile(opts.timepoint_regex_file)...
get_parsing_functions
identifier_name
different_defining_uses_never_type2.rs
// Copyright 2018 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 ...
if arg { loop {} } else { "boo" } } fn bar2(arg: bool) -> Foo { if arg { "bar2" } else { panic!() } } fn boo2(arg: bool) -> Foo { if arg { "boo2" } else { loop {} } }
} } fn boo(arg: bool) -> Foo {
random_line_split
different_defining_uses_never_type2.rs
// Copyright 2018 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 ...
(arg: bool) -> Foo { if arg { "boo2" } else { loop {} } }
boo2
identifier_name
different_defining_uses_never_type2.rs
// Copyright 2018 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 ...
else { "bar" } } fn boo(arg: bool) -> Foo { if arg { loop {} } else { "boo" } } fn bar2(arg: bool) -> Foo { if arg { "bar2" } else { panic!() } } fn boo2(arg: bool) -> Foo { if arg { "boo2" } else { loop {} } }
{ panic!() }
conditional_block
different_defining_uses_never_type2.rs
// Copyright 2018 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 ...
{ if arg { "boo2" } else { loop {} } }
identifier_body
development.js
'use strict'; module.exports = { db: 'mongodb://localhost/means7-dev', app: { title: 'MeanS7 - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID:...
} };
auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } }
random_line_split
test.js
'use strict'; module.exports = { db: 'mongodb://localhost/equinix-test', port: 3001, app: { title: 'Equinix - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID',
}, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', ...
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback'
random_line_split
birdCLEF_test.py
#General model params MODEL_TYPE = 1 MULTI_LABEL = False NONLINEARITY = nonlinearities.elu #nonlinearities.rectify INIT_GAIN = 1.0 #1.0 if elu, sqrt(2) if rectify #Pre-trained model params MODEL_PATH = 'model/' PRETRAINED_MODEL = 'birdCLEF_TUCMI_Run1_Model.pkl' #We need to define the class labels our net has learned ...
#load params of trained model loadParams(-1, filename=PRETRAINED_MODEL) ################# PREDICTION FUNCTION #################### def getPredictionFuntion(net): net_output = l.get_output(net, deterministic=True) print "COMPILING THEANO TEST FUNCTION...", start = time.time() test_net = theano.functi...
print "IMPORTING MODEL PARAMS...", net_filename = MODEL_PATH + filename with open(net_filename, 'rb') as f: params = pickle.load(f) l.set_all_param_values(NET, params) print "DONE!"
identifier_body
birdCLEF_test.py
#General model params MODEL_TYPE = 1 MULTI_LABEL = False NONLINEARITY = nonlinearities.elu #nonlinearities.rectify INIT_GAIN = 1.0 #1.0 if elu, sqrt(2) if rectify #Pre-trained model params MODEL_PATH = 'model/' PRETRAINED_MODEL = 'birdCLEF_TUCMI_Run1_Model.pkl' #We need to define the class labels our net has learne...
#normalize in [0, 1] magspec -= magspec.min(axis=None) magspec /= magspec.max(axis=None) #fix shape to 512x256 pixels without distortion magspec = magspec[:256, :512] temp = np.zeros((256, 512), dtype="float32") temp[:magspec.shape[0], :magspec.shape[1]]...
h, w = magspec.shape[:2] magspec = magspec[h - 256:, :]
random_line_split
birdCLEF_test.py
ities.elu #nonlinearities.rectify INIT_GAIN = 1.0 #1.0 if elu, sqrt(2) if rectify #Pre-trained model params MODEL_PATH = 'model/' PRETRAINED_MODEL = 'birdCLEF_TUCMI_Run1_Model.pkl' #We need to define the class labels our net has learned #but we use another file for that from birdCLEF_class_labels import CLASSES ####...
predictionPooling
identifier_name
birdCLEF_test.py
changeSampleRate(sig, rate): duration = sig.shape[0] / rate time_old = np.linspace(0, duration, sig.shape[0]) time_new = np.linspace(0, duration, int(sig.shape[0] * 44100 / rate)) interpolator = interpolate.interp1d(time_old, sig.T) new_audio = interpolator(time_new).T sig = np.round(new_...
p = predict(spec) spec_cnt += 1 #stack predictions if len(predictions): predictions = np.vstack([predictions, p]) else: predictions = p
conditional_block
splitter.py
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 # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more ...
(token, quote_char): ''' the goal of this block is to determine if the quoted string is unterminated in which case it needs to be put back together ''' # the char before the current one, used to see if # the current character is escaped prev_char = None for idx, cur_char in enumerate(tok...
_get_quote_state
identifier_name
splitter.py
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 # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more ...
prev_block_depth = block_depth block_depth = _count_jinja2_blocks(token, block_depth, "{%", "%}") if block_depth != prev_block_depth and not appended: params.append(token) appended = True prev_comment_depth = comment_depth co...
params.append(token) appended = True
conditional_block
splitter.py
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 # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more ...
# ex if tokens are "{{", "foo", "}}" these go together # These variables are used # to keep track of the state of the parsing, since blocks and quotes # may be nested within each other. quote_char = None inside_quotes = False print_depth = 0 # used to count nested jinja2 {{ }} blocks ...
items = args.strip().split('\n') # iterate over the tokens, and reassemble any that may have been # split on a space inside a jinja2 block.
random_line_split
splitter.py
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 # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more ...
def _count_jinja2_blocks(token, cur_depth, open_token, close_token): ''' this function counts the number of opening/closing blocks for a given opening/closing type and adjusts the current depth for that block based on the difference ''' num_open = token.count(open_token) num_close = token...
''' the goal of this block is to determine if the quoted string is unterminated in which case it needs to be put back together ''' # the char before the current one, used to see if # the current character is escaped prev_char = None for idx, cur_char in enumerate(token): if idx > 0: ...
identifier_body
ConversationsJoinResponse.ts
/* tslint:disable */ import { WebAPICallResult } from '../WebClient'; export type ConversationsJoinResponse = WebAPICallResult & { ok?: boolean; channel?: Channel; warning?: string; response_metadata?: ResponseMetadata; error?: string; needed?: strin...
id?: string; name?: string; is_channel?: boolean; is_group?: boolean; is_im?: boolean; created?: number; is_archived?: boolean; is_general?: boolean; u...
random_line_split
bin.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs, io::Write, path::Path}; use error_code::*; fn main()
f.write_all(s.as_bytes()).unwrap(); }); f.sync_all().unwrap(); }
{ let err_codes = vec![ cloud::ALL_ERROR_CODES.iter(), codec::ALL_ERROR_CODES.iter(), coprocessor::ALL_ERROR_CODES.iter(), encryption::ALL_ERROR_CODES.iter(), engine::ALL_ERROR_CODES.iter(), pd::ALL_ERROR_CODES.iter(), raft::ALL_ERROR_CODES.iter(), raf...
identifier_body
bin.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs, io::Write, path::Path}; use error_code::*; fn main() { let err_codes = vec![ cloud::ALL_ERROR_CODES.iter(), codec::ALL_ERROR_CODES.iter(), coprocessor::ALL_ERROR_CODES.iter(),
encryption::ALL_ERROR_CODES.iter(), engine::ALL_ERROR_CODES.iter(), pd::ALL_ERROR_CODES.iter(), raft::ALL_ERROR_CODES.iter(), raftstore::ALL_ERROR_CODES.iter(), sst_importer::ALL_ERROR_CODES.iter(), storage::ALL_ERROR_CODES.iter(), ]; let path = Path::new(...
random_line_split
bin.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs, io::Write, path::Path}; use error_code::*; fn
() { let err_codes = vec![ cloud::ALL_ERROR_CODES.iter(), codec::ALL_ERROR_CODES.iter(), coprocessor::ALL_ERROR_CODES.iter(), encryption::ALL_ERROR_CODES.iter(), engine::ALL_ERROR_CODES.iter(), pd::ALL_ERROR_CODES.iter(), raft::ALL_ERROR_CODES.iter(), ...
main
identifier_name
mod.rs
::PeerId; use futures::{ channel::oneshot, stream::{FuturesUnordered, StreamExt}, }; use rand::{rngs::SmallRng, Rng, SeedableRng}; use serde::{Deserialize, Serialize}; use short_hex_str::AsShortHexStr; use std::{collections::HashMap, sync::Arc, time::Duration}; pub mod builder; #[cfg(test)] mod test; /// The ...
(u32); #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Pong(u32); /// The actor performing health checks by running the Ping protocol pub struct HealthChecker { network_context: Arc<NetworkContext>, /// A handle to a time service for easily mocking time-related operations. time_service: TimeSer...
Ping
identifier_name
mod.rs
Network to HealthChecker layer. /// /// `HealthCheckerNetworkEvents` is a `Stream` of `PeerManagerNotification` where the /// raw `Bytes` rpc messages are deserialized into /// `HealthCheckerMsg` types. `HealthCheckerNetworkEvents` is a thin wrapper /// around an `channel::Receiver<PeerManagerNotification>`. pub type ...
{ if pong.0 == req_nonce { trace!( NetworkSchema::new(&self.network_context).remote_peer(&peer_id), rount = round, "{} Ping successful for peer: {} round: {}", self.network_context, ...
conditional_block
mod.rs
::PeerId; use futures::{ channel::oneshot, stream::{FuturesUnordered, StreamExt}, }; use rand::{rngs::SmallRng, Rng, SeedableRng}; use serde::{Deserialize, Serialize};
mod test; /// The interface from Network to HealthChecker layer. /// /// `HealthCheckerNetworkEvents` is a `Stream` of `PeerManagerNotification` where the /// raw `Bytes` rpc messages are deserialized into /// `HealthCheckerMsg` types. `HealthCheckerNetworkEvents` is a thin wrapper /// around an `channel::Receiver<Pee...
use short_hex_str::AsShortHexStr; use std::{collections::HashMap, sync::Arc, time::Duration}; pub mod builder; #[cfg(test)]
random_line_split
mod.rs
test; /// The interface from Network to HealthChecker layer. /// /// `HealthCheckerNetworkEvents` is a `Stream` of `PeerManagerNotification` where the /// raw `Bytes` rpc messages are deserialized into /// `HealthCheckerMsg` types. `HealthCheckerNetworkEvents` is a thin wrapper /// around an `channel::Receiver<PeerMa...
{ match ping_result { Ok(pong) => { if pong.0 == req_nonce { trace!( NetworkSchema::new(&self.network_context).remote_peer(&peer_id), rount = round, "{} Ping successful for peer: {} round: {}"...
identifier_body
index.js
/* Partout [Everywhere] - Policy-Based Configuration Management for the Data-Driven-Infrastructure. Copyright (C) 2016 Graham Lee Bevan <graham.bevan@ntlworld.com> This file is part of Partout. Partout is free software: you can redistribute it and/or modify it under the terms of the GNU Gener...
() { var facts_deferred = Q.defer(); if (!opts.facts) { return Q.resolve(); } opts.facts(facts_deferred, _impl.facts/*, mod_title, mod_opts*/); return facts_deferred.promise .then(function (role_facts) { if (opts.facts) { if (role_facts && role_facts.p2r...
refreshFacts
identifier_name
index.js
/* Partout [Everywhere] - Policy-Based Configuration Management for the Data-Driven-Infrastructure. Copyright (C) 2016 Graham Lee Bevan <graham.bevan@ntlworld.com> This file is part of Partout. Partout is free software: you can redistribute it and/or modify it under the terms of the GNU Gener...
} if (!Q.isPromise(role_promise)) { role_promise = Q(role_promise); } role_promise .done(function (role_res) { utils.dlog('role_promise resolved - role_res:', role_res); //p2.pushSteps(...
role_promise.reject(err);
random_line_split
index.js
/* Partout [Everywhere] - Policy-Based Configuration Management for the Data-Driven-Infrastructure. Copyright (C) 2016 Graham Lee Bevan <graham.bevan@ntlworld.com> This file is part of Partout. Partout is free software: you can redistribute it and/or modify it under the terms of the GNU Gener...
try { role_promise = opts.p2( mod_title, (mod_opts ? mod_opts : {}) ); // pushes it's own actions to run next } catch (err) { console.warn('Role: caught err:', err); role_promi...
{ /* * add passed p2 args dsl to addSteps in the p2 _impl */ push_refreshFacts(); // defer pushing on to actions so facts run first _impl.push_action(function () { utils.vlog(u.format('Role: %s running action: %s', name, mod_title)); ...
conditional_block
index.js
/* Partout [Everywhere] - Policy-Based Configuration Management for the Data-Driven-Infrastructure. Copyright (C) 2016 Graham Lee Bevan <graham.bevan@ntlworld.com> This file is part of Partout. Partout is free software: you can redistribute it and/or modify it under the terms of the GNU Gener...
} _.each(role_facts, function (v, k) { if (!k.match(/^(p2role)$/)) { _impl.facts[k] = v; } }); return Q.resolve(); } else { return Q.resolve(); } }); } // refreshFacts() /* * push role's facts ...
{ var facts_deferred = Q.defer(); if (!opts.facts) { return Q.resolve(); } opts.facts(facts_deferred, _impl.facts/*, mod_title, mod_opts*/); return facts_deferred.promise .then(function (role_facts) { if (opts.facts) { if (role_facts && role_facts.p2role)...
identifier_body
test-ignore-cfg.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 ...
() { } #[test] #[ignore(cfg(noignorecfg))] fn shouldnotignore() { } #[test] fn checktests() { // Pull the tests out of the secreturn test module let tests = __test::tests; assert!( tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore)); assert!( tests.iter()...
shouldignore
identifier_name
test-ignore-cfg.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!( tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldnotignore" && !t.desc.ignore)); }
assert!( tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
random_line_split
test-ignore-cfg.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 ...
{ // Pull the tests out of the secreturn test module let tests = __test::tests; assert!( tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore)); assert!( tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldnotignore" && !t.desc.ignore)); }
identifier_body
test_list.py
import pytest from swimlane.exceptions import ValidationError def test_getattr_fallback(mock_record): """Verify cursor __getattr__ falls back to AttributeError for unknown cursor + list methods""" with pytest.raises(AttributeError): getattr(mock_record['Text List'], 'unknown_method') def test_set_v...
value = ['Test', 'Value'] assert mock_record.get_field('Text List').get_bulk_modify(value) == value
def test_list_field_bulk_modify_value(mock_record): """Pass-through bulk_modify value"""
random_line_split
test_list.py
import pytest from swimlane.exceptions import ValidationError def test_getattr_fallback(mock_record): """Verify cursor __getattr__ falls back to AttributeError for unknown cursor + list methods""" with pytest.raises(AttributeError): getattr(mock_record['Text List'], 'unknown_method') def test_set_v...
(mock_record): """Min/max characters restriction validation""" key = 'Text List Char Limit' with pytest.raises(ValidationError): mock_record[key] = ['defg', 'hijkl', 'mno pqr'] with pytest.raises(ValidationError): mock_record[key] = [''] def test_list_field_bulk_modify_value(mock_rec...
test_min_max_char_validation
identifier_name
test_list.py
import pytest from swimlane.exceptions import ValidationError def test_getattr_fallback(mock_record): """Verify cursor __getattr__ falls back to AttributeError for unknown cursor + list methods""" with pytest.raises(AttributeError): getattr(mock_record['Text List'], 'unknown_method') def test_set_v...
def test_min_max_char_validation(mock_record): """Min/max characters restriction validation""" key = 'Text List Char Limit' with pytest.raises(ValidationError): mock_record[key] = ['defg', 'hijkl', 'mno pqr'] with pytest.raises(ValidationError): mock_record[key] = [''] def test_li...
"""Validate against min/max word restrictions""" key = 'Text List Word Limit' with pytest.raises(ValidationError): mock_record[key] = ['word ' * 10] with pytest.raises(ValidationError): mock_record[key] = ['word']
identifier_body
solcoin.py
from p2pool.bitcoin import networks PARENT = networks.nets['solcoin'] SHARE_PERIOD = 20 # seconds target spacing CHAIN_LENGTH = 12*60*60//20 # shares REAL_CHAIN_LENGTH = 12*60*60//20 # shares TARGET_LOOKBEHIND = 15 # shares SPREAD = 20 # blocks IDENTIFIER = 'e0f0b08e5af1e89a'.decode('hex') PREFIX = 'a6f2b07e0ac18b6e'....
PERSIST = False WORKER_PORT = 8360 BOOTSTRAP_ADDRS = 'p2pool.solcoin.net rav3n.dtdns.net pool.hostv.pl p2pool.org solidpool.org'.split(' ') ANNOUNCE_CHANNEL = '#p2pool-alt' VERSION_CHECK = lambda v: True
random_line_split
defaults-tr_TR.js
* Copyright 2012-2020 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register ...
/*! * Bootstrap-select v1.13.16 (https://developer.snapappointments.com/bootstrap-select) *
random_line_split
defaults-tr_TR.js
/*! * Bootstrap-select v1.13.16 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2020 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== unde...
else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQue...
{ // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); }
conditional_block
models.py
import socket,logging # Create your models here. class Sensor(models.Model): timestamp = models.DateTimeField(auto_now_add=True) env_light = models.IntegerField() env_humid = models.IntegerField() env_raindrop = models.IntegerField() env_temperature = models.IntegerField() soi_humid = models.I...
from django.db import models
random_line_split
models.py
from django.db import models import socket,logging # Create your models here. class
(models.Model): timestamp = models.DateTimeField(auto_now_add=True) env_light = models.IntegerField() env_humid = models.IntegerField() env_raindrop = models.IntegerField() env_temperature = models.IntegerField() soi_humid = models.IntegerField() soi_fatness = models.IntegerField() soi_t...
Sensor
identifier_name
models.py
from django.db import models import socket,logging # Create your models here. class Sensor(models.Model):
sensor = Sensor() sensor.env_light = data['env_light'] sensor.env_humid = data['env_humid'] sensor.env_raindrop = data['env_raindrop'] sensor.env_temperature = data['env_temperature'] sensor.soi_humid = data['humi_aval'] sensor.soi_fatn...
timestamp = models.DateTimeField(auto_now_add=True) env_light = models.IntegerField() env_humid = models.IntegerField() env_raindrop = models.IntegerField() env_temperature = models.IntegerField() soi_humid = models.IntegerField() soi_fatness = models.IntegerField() soi_temperature = models....
identifier_body
models.py
from django.db import models import socket,logging # Create your models here. class Sensor(models.Model): timestamp = models.DateTimeField(auto_now_add=True) env_light = models.IntegerField() env_humid = models.IntegerField() env_raindrop = models.IntegerField() env_temperature = models.IntegerFie...
else: logging.warning("error sensor data %s." % content) return False class Daily(models.Model): date = models.DateField(auto_now_add=True) env_light = models.IntegerField() env_humid = models.IntegerField() env_raindrop = models.IntegerField() env_temperature = m...
data = {k: v for k, v in [tuple(i.split('=')) for i in content.split("&")]} sensor = Sensor() sensor.env_light = data['env_light'] sensor.env_humid = data['env_humid'] sensor.env_raindrop = data['env_raindrop'] sensor.env_temperature = data['env_temperature'] ...
conditional_block
webpack.config.js
const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const WebpackShellPlugin = require('webpack-shell-plugin'); const { join, resolve } = require('path'); var BUILD_DIR = resolve(__dirname, '../../priv/static');...
"redux-logger", "react-router-redux", "react-router-dom", "history", "react-apollo", "qrcode.react", "graphql-tag", "react-select", "apollo-phoenix-websocket", "jquery", "phoenix", "bootstrap", ] }, output: { path: BUILD_DIR, public...
'dependencies.bundle': [ "react", "react-dom", "react-redux", "redux-thunk",
random_line_split
uberblock.rs
use redox::{mem, ptr}; use redox::{String, ToString}; use super::from_bytes::FromBytes; use super::block_ptr::BlockPtr; #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct Uberblock { pub magic: u64, pub version: u64, pub txg: u64, pub guid_sum: u64, pub timestamp: u64, pub rootbp: BlockP...
} impl FromBytes for Uberblock { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<Uberblock>() { let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) }; if uberblock.magic == Uberblock::magic_little() { return Ok...
{ return 0x00bab10c; }
identifier_body
uberblock.rs
use redox::{mem, ptr}; use redox::{String, ToString}; use super::from_bytes::FromBytes; use super::block_ptr::BlockPtr; #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct Uberblock { pub magic: u64, pub version: u64, pub txg: u64, pub guid_sum: u64, pub timestamp: u64, pub rootbp: BlockP...
if uberblock.magic == Uberblock::magic_little() { return Ok(uberblock); } else if uberblock.magic == Uberblock::magic_big() { return Ok(uberblock); } } Err("Error: cannot find Uberblock".to_string()) } }
impl FromBytes for Uberblock { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<Uberblock>() { let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) };
random_line_split
uberblock.rs
use redox::{mem, ptr}; use redox::{String, ToString}; use super::from_bytes::FromBytes; use super::block_ptr::BlockPtr; #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct Uberblock { pub magic: u64, pub version: u64, pub txg: u64, pub guid_sum: u64, pub timestamp: u64, pub rootbp: BlockP...
() -> u64 { return 0x00bab10c; } } impl FromBytes for Uberblock { fn from_bytes(data: &[u8]) -> Result<Self, String> { if data.len() >= mem::size_of::<Uberblock>() { let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) }; if uberblock.magic == Uberblock...
magic_big
identifier_name
game.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { QueryService, IGetGamesListDto, IGetGamePlayersDto } from '../query.service' import {DataSource} from '@angular/cdk/collections'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Component({ selector: 'poker-game', temp...
// if (window.hasOwnProperty("appInsights")) { // appInsights.trackEvent("GameExpanded", // { Game: this.game.GameId, GameDate: this.game.GameDate } // ); // } } ngOnInit() { } } export class PlayersDataSource extends DataSource<any> { constructor(private data: IGetGamePl...
{ this.queryService.GetGamePlayers(this.game.GameId) .subscribe(players => { this.Players = new PlayersDataSource( players.sort(function(a, b) { return a.Placing - b.Placing }))}); }
conditional_block
game.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { QueryService, IGetGamesListDto, IGetGamePlayersDto } from '../query.service' import {DataSource} from '@angular/cdk/collections'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Component({ selector: 'poker-game', temp...
players.sort(function(a, b) { return a.Placing - b.Placing }))}); } // if (window.hasOwnProperty("appInsights")) { // appInsights.trackEvent("GameExpanded", // { Game: this.game.GameId, GameDate: this.game...
this.Players = new PlayersDataSource(
random_line_split
game.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { QueryService, IGetGamesListDto, IGetGamePlayersDto } from '../query.service' import {DataSource} from '@angular/cdk/collections'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Component({ selector: 'poker-game', temp...
extends DataSource<any> { constructor(private data: IGetGamePlayersDto[]) { super(); } /** Connect function called by the table to retrieve one stream containing the data to render. */ connect(): Observable<IGetGamePlayersDto[]> { return Observable.of(this.data); } disconnect() {} }
PlayersDataSource
identifier_name
game.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { QueryService, IGetGamesListDto, IGetGamePlayersDto } from '../query.service' import {DataSource} from '@angular/cdk/collections'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Component({ selector: 'poker-game', temp...
ngOnInit() { } } export class PlayersDataSource extends DataSource<any> { constructor(private data: IGetGamePlayersDto[]) { super(); } /** Connect function called by the table to retrieve one stream containing the data to render. */ connect(): Observable<IGetGamePlayersDto[]> { return Observable...
{ if (!this.Players) { this.queryService.GetGamePlayers(this.game.GameId) .subscribe(players => { this.Players = new PlayersDataSource( players.sort(function(a, b) { return a.Placing - b.Placing }))}); } ...
identifier_body