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
index.py
import os import traceback import json import requests from flask import Flask, request from cities_list import CITIES from messages import get_message, search_keyword token = os.environ.get('FB_ACCESS_TOKEN') api_key = os.environ.get('WEATHER_API_KEY') app = Flask(__name__) def location_quick_reply(sender, text=N...
def send_text(sender, text): return { "recipient": { "id": sender }, "message": { "text": text } } def send_message(payload): requests.post('https://graph.facebook.com/v2.6/me/messages/?access_token=' + token, json=payload) def send_weather_info...
return { "recipient": { "id": sender }, "message": { "attachment": { "type": type, "payload": payload, } } }
identifier_body
lex-bad-char-literals.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; static c: char = '\●' //~ ERROR: unknown character escape ; static s: &'static str = "\●" //~ ERROR: unknown character escape ; // THIS MUST BE LAST, since unterminated character constants kill the lexer static c: char = '● //~ ERROR: unterminated character constant ;
; static s2: &'static str = "\u23q" //~ ERROR: illegal character in numeric character escape //~^ ERROR: numeric character escape is too short
random_line_split
zigbee.py
ser = serial.Serial("/dev/ttyUSB0", 115200,timeout = 0.1) except serial.serialutil.SerialException: try: ser = serial.Serial("/dev/ttyS1", 115200,timeout = 0.1) with open("/sys/devices/virtual/misc/gpio/mode/gpio0",'w') as UART_RX: UART_RX.write('3') with open("/sys/devices/virtual/mis...
def set_target(short_mac): send = "0c fc 02 01 04 01 01 01 02"+short_mac+"02 0a" s = send.replace(' ','') a=binascii.a2b_hex(s) while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) a = rec.find("04 fd 02 01",0) if a != -1: print "set target ok" break time...
while True: ser.write('\x02') ser.write('\x75') ser.write('\x1e') data = ser.readline() val=hexShow(data) leng = len(val) if leng > 45: a = val.find("0e fc 02 e1",1) if a != -1: print "add equipment ok" b=a+12 mac = val[b:b+29] return mac break time.sleep(0.2)
identifier_body
zigbee.py
ser = serial.Serial("/dev/ttyUSB0", 115200,timeout = 0.1) except serial.serialutil.SerialException: try: ser = serial.Serial("/dev/ttyS1", 115200,timeout = 0.1) with open("/sys/devices/virtual/misc/gpio/mode/gpio0",'w') as UART_RX: UART_RX.write('3') with open("/sys/devices/virtual/mis...
(short_mac): send = "0c fc 02 01 04 01 01 01 02"+short_mac+"02 0a" s = send.replace(' ','') a=binascii.a2b_hex(s) while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) a = rec.find("04 fd 02 01",0) if a != -1: print "set target ok" break time.sleep(0.2) def...
set_target
identifier_name
zigbee.py
ser = serial.Serial("/dev/ttyUSB0", 115200,timeout = 0.1) except serial.serialutil.SerialException: try: ser = serial.Serial("/dev/ttyS1", 115200,timeout = 0.1) with open("/sys/devices/virtual/misc/gpio/mode/gpio0",'w') as UART_RX: UART_RX.write('3') with open("/sys/devices/virtual/mis...
else: print "serial open failure!" while True: # If check the GPIO12's status, if it is high, excuete commands to # add new zigbee device into zigbee gateway a = key_interrupt() if a == '1': print "Add equipment!" # Set gateway to allow adding device val=r...
print "serial open succeed!"
conditional_block
zigbee.py
ser = serial.Serial("/dev/ttyUSB0", 115200,timeout = 0.1) except serial.serialutil.SerialException: try: ser = serial.Serial("/dev/ttyS1", 115200,timeout = 0.1) with open("/sys/devices/virtual/misc/gpio/mode/gpio0",'w') as UART_RX: UART_RX.write('3') with open("/sys/devices/virtual/mis...
def main(): global Door_mac global PIR_mac global Leak_mac global Smoke_mac global Remote_mac setup() if ser.isOpen() == True: print "serial open succeed!" else: print "serial open failure!" while True: # If check the GPIO12's status, if it is high, excuete c...
http_post(values) if s == '1'or PIR == '1': timer = threading.Timer(2,recovery) timer.start()
random_line_split
testall.py
import sys, os import re import unittest import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo win32gui_dialog win32gui_...
output, _ = p.communicate() rc = p.returncode except ImportError: # py2.3? fin, fout, ferr = os.popen3(" ".join(self.argv)) fin.close() output = fout.read() + ferr.read() fout.close() rc = ferr.close() if rc:...
stderr=subprocess.STDOUT)
random_line_split
testall.py
import sys, os import re import unittest import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo win32gui_dialog win32gui_...
reconstituted = find_exception_in_output(output) if reconstituted is not None: raise reconstituted raise AssertionError("%s failed with exit code %s. Output is:\n%s" % (base, rc, output)) def get_demo_tests(): import win32api ret = [] demo_dir = os.path...
def __init__(self, argv): self.argv = argv def __call__(self): try: import subprocess p = subprocess.Popen(self.argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = p.communicate() ...
identifier_body
testall.py
import sys, os import re import unittest import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo win32gui_dialog win32gui_...
suite.addTest(test) for test in get_demo_tests(): suite.addTest(test) return suite class CustomLoader(pywin32_testutil.TestLoader): def loadTestsFromModule(self, module): return self.fixupTestsForLeakTests(suite()) if __name__=='__main__': pywin32_testutil.testmain(testLoa...
test = unittest.defaultTestLoader.loadTestsFromModule(mod)
conditional_block
testall.py
import sys, os import re import unittest import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo win32gui_dialog win32gui_...
(): # Some hacks for import order - dde depends on win32ui try: import win32ui except ImportError: pass # 'what-ev-a....' import win32api dir = os.path.dirname(win32api.__file__) num = 0 is_debug = os.path.basename(win32api.__file__).endswith("_d") for name in os.lis...
import_all
identifier_name
index.js
/* * ATLauncher CLI - https://github.com/ATLauncher/ATLauncher-CLI
* (at your option) any later version. * * 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 ...
* Copyright (C) 2016 ATLauncher * * 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
random_line_split
accountsResultComponent.js
/* * Copyright (C) 2013-2015 Uncharted Software Inc. * * Property of Uncharted(TM), formerly Oculus Info Inc. * http://uncharted.software/ *
* the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice ...
* Released under 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
random_line_split
relaycontrol.py
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep # The script as below using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Set relay pins as output GPIO.setup(24, GPIO.OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 US...
client = mqtt.Client(client_id="rasp-g1") # Callback declarations (functions run based on certain messages) client.on_connect = on_connect client.message_callback_add("/iot/control/", on_message_iotrl) # This is where the MQTT service connects and starts listening for messages client.username_pw_set(USERNAME, PAS...
print("Error: Unknown command")
identifier_body
relaycontrol.py
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep # The script as below using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Set relay pins as output GPIO.setup(24, GPIO.OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 US...
(client, userdata, msg): print("\n\t* Raspberry UPDATED ("+msg.topic+"): " + str(msg.payload)) if msg.payload == "gpio24on": GPIO.output(24, GPIO.HIGH) client.publish("/iot/status", "Relay gpio18on", 2) if msg.payload == "gpio24off": GPIO.output(24, GPIO.LOW) client.publish("/iot/s...
on_message_iotrl
identifier_name
relaycontrol.py
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep # The script as below using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Set relay pins as output GPIO.setup(24, GPIO.OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 US...
time.sleep(10)
conditional_block
relaycontrol.py
import paho.mqtt.client as mqtt import json, time import RPi.GPIO as GPIO from time import sleep # The script as below using BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Set relay pins as output GPIO.setup(24, GPIO.OUT) # ----- CHANGE THESE FOR YOUR SETUP ----- MQTT_HOST = "190.97.168.236" MQTT_PORT = 1883 US...
client.publish("/iot/status", "Relay gpio18off", 2) def command_error(): print("Error: Unknown command") client = mqtt.Client(client_id="rasp-g1") # Callback declarations (functions run based on certain messages) client.on_connect = on_connect client.message_callback_add("/iot/control/", on_message_iotrl...
if msg.payload == "gpio24off": GPIO.output(24, GPIO.LOW)
random_line_split
lib.rs
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Support crate for writing fuzzers in Chrome OS. //! //! The major features provided by this crate are: //! //! * The [`fuzz_target`] macro which wr...
/// /// # Examples /// /// ``` /// use std::str; /// # #[macro_use] extern crate cros_fuzz; /// /// fuzz_target!(|data: &[u8]| { /// let _ = str::from_utf8(data); /// }); /// /// # fn main() { /// # let buf = b"hello, world!"; /// # llvm_fuzzer_test_one_input(buf.as_ptr(), buf.len()); /// # } /// ``` #[macro_...
random_line_split
base64_ops_test.py
# Copyright 2016 The TensorFlow 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 applica...
for _ in range(np.random.randint(10))] self._RunTest(msg, pad=pad) # Zero-element, non-trivial shapes. for _ in range(10): k = np.random.randint(10) msg = np.empty((0, k), dtype=bytes) encoded = string_ops.encode_base64(msg, pad=pad) decoded = string_o...
for _ in range(10): msg = [np.random.bytes(np.random.randint(20))
random_line_split
base64_ops_test.py
# Copyright 2016 The TensorFlow 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 applica...
with self.test_session(): # Invalid length. msg = np.random.bytes(99) enc = base64.urlsafe_b64encode(msg) with self.assertRaisesRegexp(errors.InvalidArgumentError, "1 modulo 4"): try_decode(enc + b"a") # Invalid char used in encoding. msg = np.random.bytes(34) en...
self._decoded_f.eval(feed_dict={self._encoded_f: enc})
identifier_body
base64_ops_test.py
# Copyright 2016 The TensorFlow 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 applica...
def testInvalidInput(self): def try_decode(enc): self._decoded_f.eval(feed_dict={self._encoded_f: enc}) with self.test_session(): # Invalid length. msg = np.random.bytes(99) enc = base64.urlsafe_b64encode(msg) with self.assertRaisesRegexp(errors.InvalidArgumentError, "1 modulo...
for _ in range(10): msg = [np.random.bytes(np.random.randint(20)) for _ in range(np.random.randint(10))] self._RunTest(msg, pad=pad) # Zero-element, non-trivial shapes. for _ in range(10): k = np.random.randint(10) msg = np.empty((0, k), dtype=bytes) e...
conditional_block
base64_ops_test.py
# Copyright 2016 The TensorFlow 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 applica...
(self): def try_decode(enc): self._decoded_f.eval(feed_dict={self._encoded_f: enc}) with self.test_session(): # Invalid length. msg = np.random.bytes(99) enc = base64.urlsafe_b64encode(msg) with self.assertRaisesRegexp(errors.InvalidArgumentError, "1 modulo 4"): try_decode...
testInvalidInput
identifier_name
0021_sso_id_verification.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-11 15:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
]
dependencies = [ ('third_party_auth', '0020_cleanup_slug_fields'), ] operations = [ migrations.AddField( model_name='ltiproviderconfig', name='enable_sso_id_verification', field=models.BooleanField(default=False, help_text=b'Use the presence of a profile from...
identifier_body
0021_sso_id_verification.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-11 15:33 from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('third_party_auth', '0020_cleanup_slug_fields'), ] operations = [ migrations.AddField( model_name='ltiproviderconfig', name='enable_sso_id_verification', field=models.BooleanField(default=False, help_text=b'Use t...
Migration
identifier_name
mod.rs
use crate::types::game::paddock::PaddockInformationsForSell; use crate::types::game::paddock::PaddockInstancesInformations; use protocol_derive::{Decode, Encode}; #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 5824)] pub struct PaddockPropertiesMessage<'a> { pub properties: PaddockInstancesInfo...
<'a> { pub area_id: i32, pub at_least_nb_mount: i8, pub at_least_nb_machine: i8, #[protocol(var)] pub max_price: u64, pub order_by: u8, pub _phantom: std::marker::PhantomData<&'a ()>, } #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 6018)] pub struct PaddockSellBuyDialog...
PaddockToSellFilterMessage
identifier_name
mod.rs
use crate::types::game::paddock::PaddockInformationsForSell; use crate::types::game::paddock::PaddockInstancesInformations; use protocol_derive::{Decode, Encode}; #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 5824)] pub struct PaddockPropertiesMessage<'a> { pub properties: PaddockInstancesInfo...
#[protocol(var)] pub page_index: u16, pub _phantom: std::marker::PhantomData<&'a ()>, } #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 6026)] pub struct GameDataPlayFarmObjectAnimationMessage<'a> { #[protocol(var_contents)] pub cell_id: std::borrow::Cow<'a, [u16]>, } #[derive(C...
#[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 6141)] pub struct PaddockToSellListRequestMessage<'a> {
random_line_split
lighthouse-ext-background.js
/** * @license Copyright 2018 Google Inc. 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 applicable law or a...
(runnerResult) { performance.mark('report-start'); const html = runnerResult.report; const blob = new Blob([html], {type: 'text/html'}); const blobURL = URL.createObjectURL(blob); performance.mark('report-end'); performance.measure('generate report', 'report-start', 'report-end'); return blobURL; } /** ...
createReportPageAsBlob
identifier_name
lighthouse-ext-background.js
/** * @license Copyright 2018 Google Inc. 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 applicable law or a...
return results.report; } } /** * @param {LH.RunnerResult} runnerResult Lighthouse results object * @return {string} Blob URL of the report (or error page) HTML */ function createReportPageAsBlob(runnerResult) { performance.mark('report-start'); const html = runnerResult.report; const blob = new Blob(...
{ await assetSaver.logAssets(results.artifacts, results.lhr.audits); }
conditional_block
lighthouse-ext-background.js
/** * @license Copyright 2018 Google Inc. 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 applicable law or a...
// @ts-ignore window.loadSettings = loadSettings; // @ts-ignore window.saveSettings = saveSettings;
// @ts-ignore window.listenForStatus = listenForStatus;
random_line_split
lighthouse-ext-background.js
/** * @license Copyright 2018 Google Inc. 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 applicable law or a...
resolve({ useDevTools: !!savedSettings.useDevTools, selectedCategories: Object.keys(savedCategories).filter(cat => savedCategories[cat]), }); }); }); } /** @param {(status: [string, string, string]) => void} listenCallback */ function listenForStatus(listenCallback) { log.events.a...
{ return new Promise(resolve => { // Protip: debug what's in storage with: // chrome.storage.local.get(['lighthouse_audits'], console.log) chrome.storage.local.get([STORAGE_KEY, SETTINGS_KEY], result => { // Start with list of all default categories set to true so list is // always up to dat...
identifier_body
shared-libs.module.ts
import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgJhipsterModule } from 'ng-jhipster'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { CookieModul...
{}
GatewaySharedLibsModule
identifier_name
shared-libs.module.ts
import { CommonModule } from '@angular/common'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgJhipsterModule } from 'ng-jhipster'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { CookieModule } from 'ngx-cookie'; import { FontAwesomeModule } from '@fortawesome/angular-fontaweso...
import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms';
random_line_split
SmilesDupeFilter.py
# $Id$ # # Copyright (C) 2003 Rational Discovery LLC # All Rights Reserved # from rdkit import RDConfig from rdkit import six import sys, os from rdkit import Chem from rdkit.VLib.Filter import FilterNode class
(FilterNode): """ canonical-smiles based duplicate filter Assumptions: - inputs are molecules Sample Usage: >>> from rdkit.VLib.NodeLib.SDSupply import SDSupplyNode >>> fileN = os.path.join(RDConfig.RDCodeDir,'VLib','NodeLib',\ 'test_data','NCI_aids.10.sdf') >>> su...
DupeFilter
identifier_name
SmilesDupeFilter.py
# $Id$ # # Copyright (C) 2003 Rational Discovery LLC # All Rights Reserved # from rdkit import RDConfig from rdkit import six import sys, os from rdkit import Chem from rdkit.VLib.Filter import FilterNode class DupeFilter(FilterNode): """ canonical-smiles based duplicate filter Assumptions: - inputs a...
def filter(self, cmpd): smi = Chem.MolToSmiles(cmpd) if smi not in self._smisSeen: self._smisSeen.append(smi) return 1 else: return 0 #------------------------------------ # # doctest boilerplate # def _test(): import doctest, sys return doctest.testmod(sys.modules["__ma...
FilterNode.reset(self) self._smisSeen = []
identifier_body
SmilesDupeFilter.py
# $Id$ # # Copyright (C) 2003 Rational Discovery LLC # All Rights Reserved # from rdkit import RDConfig from rdkit import six import sys, os from rdkit import Chem from rdkit.VLib.Filter import FilterNode class DupeFilter(FilterNode): """ canonical-smiles based duplicate filter Assumptions: - inputs a...
if __name__ == '__main__': import sys failed, tried = _test() sys.exit(failed)
return doctest.testmod(sys.modules["__main__"])
random_line_split
SmilesDupeFilter.py
# $Id$ # # Copyright (C) 2003 Rational Discovery LLC # All Rights Reserved # from rdkit import RDConfig from rdkit import six import sys, os from rdkit import Chem from rdkit.VLib.Filter import FilterNode class DupeFilter(FilterNode): """ canonical-smiles based duplicate filter Assumptions: - inputs a...
#------------------------------------ # # doctest boilerplate # def _test(): import doctest, sys return doctest.testmod(sys.modules["__main__"]) if __name__ == '__main__': import sys failed, tried = _test() sys.exit(failed)
return 0
conditional_block
lib.rs
// Tifflin OS - Asynchronous common interface // - By John Hodge (thePowersGang) // // //! Asynchronous waiting support #[macro_use] extern crate syscalls; /// Trait for types that can be used for 'idle_loop' pub trait WaitController { fn get_count(&self) -> usize; fn populate(&self, cb: &mut FnMut(::syscalls::Wait...
(items: &mut [&mut WaitController]) { let mut objects = Vec::new(); loop { let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count()); objects.reserve( count ); for ctrlr in items.iter() { ctrlr.populate(&mut |wi| objects.push(wi)); } ::syscalls::threads::wait(&mut objects, !0); let mut o...
idle_loop
identifier_name
lib.rs
// Tifflin OS - Asynchronous common interface // - By John Hodge (thePowersGang) // // //! Asynchronous waiting support #[macro_use] extern crate syscalls; /// Trait for types that can be used for 'idle_loop' pub trait WaitController { fn get_count(&self) -> usize; fn populate(&self, cb: &mut FnMut(::syscalls::Wait...
let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count()); objects.reserve( count ); for ctrlr in items.iter() { ctrlr.populate(&mut |wi| objects.push(wi)); } ::syscalls::threads::wait(&mut objects, !0); let mut ofs = 0; for ctrlr in items.iter_mut() { let num = ctrlr.get_count(); ...
{ let mut objects = Vec::new(); loop {
random_line_split
lib.rs
// Tifflin OS - Asynchronous common interface // - By John Hodge (thePowersGang) // // //! Asynchronous waiting support #[macro_use] extern crate syscalls; /// Trait for types that can be used for 'idle_loop' pub trait WaitController { fn get_count(&self) -> usize; fn populate(&self, cb: &mut FnMut(::syscalls::Wait...
objects.clear(); } }
{ let mut objects = Vec::new(); loop { let count = items.iter().fold(0, |sum,ctrlr| sum + ctrlr.get_count()); objects.reserve( count ); for ctrlr in items.iter() { ctrlr.populate(&mut |wi| objects.push(wi)); } ::syscalls::threads::wait(&mut objects, !0); let mut ofs = 0; for ctrlr in items.iter_mu...
identifier_body
metadata.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ pub filename: String, pub line: usize } impl ErrorLocation { /// Create an error location from a span. pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation { let loc = ecx.codemap().lookup_char_pos_adj(sp.lo); ErrorLocation { filename: loc.filename, line...
ErrorLocation
identifier_name
metadata.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `prefix/name`. /// /// For our current purposes the prefix is the target architecture and the name is a crate name. /// If an error occurs steps will be taken to ensure that no file is created. pub fn output_metadata(ecx: &ExtCtxt, pre...
{ directory.join(format!("{}.json", name)) }
identifier_body
metadata.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
Ok(result?) }
{ remove_file(&metadata_path)?; }
conditional_block
metadata.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub struct ErrorLocation { pub filename: String, pub line: usize } impl ErrorLocation { /// Create an error location from a span. pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation { let loc = ecx.codemap().lookup_char_pos_adj(sp.lo); ErrorLocation { filename: loc.fi...
/// JSON encodable error location type with filename and line number. #[derive(PartialEq, Deserialize, Serialize)]
random_line_split
upgrade.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
from resource_management.core.exceptions import Fail from resource_management.core.logger import Logger def run_migration(env, upgrade_type): """ If the acl migration script is present, then run it for either upgrade or downgrade. That script was introduced in HDP 2.3.4.0 and requires stopping all Kafka brokers ...
from resource_management.libraries.functions import Direction
random_line_split
upgrade.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
elif params.upgrade_direction == Direction.DOWNGRADE: kafka_acls_script = format("{stack_root}/{downgrade_from_version}/kafka/bin/kafka-acls.sh") command_suffix = "--downgradeAcls" if kafka_acls_script is not None: if os.path.exists(kafka_acls_script): Logger.info("Found Kafka acls script: {0}"....
kafka_acls_script = format("{stack_root}/{version}/kafka/bin/kafka-acls.sh") command_suffix = "--upgradeAcls"
conditional_block
upgrade.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
# If the schema upgrade script exists in the version upgrading to, then attempt to upgrade/downgrade it while still using the present bits. kafka_acls_script = None command_suffix = "" if params.upgrade_direction == Direction.UPGRADE: kafka_acls_script = format("{stack_root}/{version}/kafka/bin/kafka-acls....
""" If the acl migration script is present, then run it for either upgrade or downgrade. That script was introduced in HDP 2.3.4.0 and requires stopping all Kafka brokers first. Requires configs to be present. :param env: Environment. :param upgrade_type: "rolling" or "nonrolling """ import params if u...
identifier_body
upgrade.py
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
(env, upgrade_type): """ If the acl migration script is present, then run it for either upgrade or downgrade. That script was introduced in HDP 2.3.4.0 and requires stopping all Kafka brokers first. Requires configs to be present. :param env: Environment. :param upgrade_type: "rolling" or "nonrolling """ ...
run_migration
identifier_name
MathUtils.js
/** * Collection Math and sorting methods * @Class MathUtils * @static */ var ME = module.exports = {}; /** * Takes an integer and calculates what the 16 bit float * representation of the binary data used to read the integer is. * @method f16 * @param {Number} h Integer value * @return {Number} Float value ...
else if (e == 0x1F) { return f?NaN:((s?-1:1)*Infinity); } return(s?-1:1) * Math.pow(2, e-15) * (1+(f/Math.pow(2, 10))); } /** * Calculates the number of binary ones present in the data used to * generate the input integer. * @method popcount * @param {Number} bits Integer * @return {Number} ...
{ return (s?-1:1) * Math.pow(2,-14) * (f/Math.pow(2, 10)); }
conditional_block
MathUtils.js
/** * Collection Math and sorting methods * @Class MathUtils * @static */ var ME = module.exports = {}; /** * Takes an integer and calculates what the 16 bit float * representation of the binary data used to read the integer is. * @method f16 * @param {Number} h Integer value * @return {Number} Float value ...
bits = (bits & SK3) + ((bits >> 2) & SK3); bits = (bits & SKF0) + ((bits >> 4) & SKF0); bits += bits >> 8; return (bits + (bits >> 15)) & 63; } /** * Calculates the 64 bit integer value of two 32 bit integers. Only works up to * the limit of the javascript Number maximum value. * @method arr32To64 * @...
bits -= (bits >> 1) & SK5;
random_line_split
Event.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-2015, Egret Technology Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // ...
////////////////////////////////////////////////////////////////////////////////////// module dragonBones { /** * @class dragonBones.Event * @classdesc * 事件 */ export class Event extends egret.Event { /** * 创建一个Event实例 * @param type 事件的类型 */ ...
random_line_split
Event.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-2015, Egret Technology Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // ...
ends egret.Event { /** * 创建一个Event实例 * @param type 事件的类型 */ public constructor(type:string, bubbles:boolean = false, cancelable:boolean = false) { super(type, bubbles, cancelable) } } }
t ext
identifier_name
Event.ts
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-2015, Egret Technology Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // ...
bubbles, cancelable) } } }
identifier_body
cleanup.rs
extern crate diesel; extern crate dotenv; extern crate kuchiki; extern crate rusoto_core; extern crate rusoto_credential; extern crate rusoto_s3; extern crate server; extern crate url; use diesel::pg::PgConnection; use diesel::prelude::*; use dotenv::dotenv; use kuchiki::traits::*; use rusoto_core::Region; use rusoto_...
() { use server::schema::ads::dsl::*; dotenv().ok(); start_logging(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let conn = PgConnection::establish(&database_url).unwrap(); let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap(); for...
main
identifier_name
cleanup.rs
extern crate diesel; extern crate dotenv; extern crate kuchiki; extern crate rusoto_core; extern crate rusoto_credential; extern crate rusoto_s3; extern crate server; extern crate url; use diesel::pg::PgConnection; use diesel::prelude::*; use dotenv::dotenv; use kuchiki::traits::*; use rusoto_core::Region; use rusoto_...
} } ret = true; } for comment in document.select(".commentable_item").unwrap() { comment.as_node().detach(); ret = true; } ad.html = document .select("div") .unwrap() .nth(0) .unwrap() .as_node() .to_string();...
{ println!("Couldn't delete {} {:?}", src, res); }
conditional_block
cleanup.rs
extern crate diesel; extern crate dotenv; extern crate kuchiki; extern crate rusoto_core; extern crate rusoto_credential; extern crate rusoto_s3; extern crate server; extern crate url; use diesel::pg::PgConnection; use diesel::prelude::*; use dotenv::dotenv; use kuchiki::traits::*; use rusoto_core::Region; use rusoto_...
.unwrap(); } else { println!("Skipped {}", ad.id); } } }
{ use server::schema::ads::dsl::*; dotenv().ok(); start_logging(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let conn = PgConnection::establish(&database_url).unwrap(); let dbads: Vec<Ad> = ads.order(created_at.desc()).load::<Ad>(&conn).unwrap(); for mu...
identifier_body
cleanup.rs
extern crate diesel; extern crate dotenv; extern crate kuchiki; extern crate rusoto_core; extern crate rusoto_credential; extern crate rusoto_s3; extern crate server; extern crate url; use diesel::pg::PgConnection; use diesel::prelude::*; use dotenv::dotenv; use kuchiki::traits::*; use rusoto_core::Region; use rusoto_...
.unwrap() .as_node() .to_string(); ad.images = images; ret } fn main() { use server::schema::ads::dsl::*; dotenv().ok(); start_logging(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let conn = PgConnection::establish(&database_url...
ad.html = document .select("div") .unwrap() .nth(0)
random_line_split
gen_key_io_test_vectors.py
SCRIPT_ADDRESS_REGTEST = 196 PRIVKEY = 176 PRIVKEY_TEST = 239 PRIVKEY_REGTEST = 239 # script OP_0 = 0x00 OP_1 = 0x51 OP_2 = 0x52 OP_16 = 0x60 OP_DUP = 0x76 OP_EQUAL = 0x87 OP_EQUALVERIFY = 0x88 OP_HASH160 = 0xa9 OP_CHECKSIG = 0xac pubkey_prefix = (OP_DUP, OP_HASH160, 20) pubkey_suffix = (OP_EQUALVERIFY, OP_CHECKSIG) s...
SCRIPT_ADDRESS_TEST = 196 SCRIPT_ADDRESS_TEST2 = 58 PUBKEY_ADDRESS_REGTEST = 111
random_line_split
gen_key_io_test_vectors.py
_TEST = 196 SCRIPT_ADDRESS_TEST2 = 58 PUBKEY_ADDRESS_REGTEST = 111 SCRIPT_ADDRESS_REGTEST = 196 PRIVKEY = 176 PRIVKEY_TEST = 239 PRIVKEY_REGTEST = 239 # script OP_0 = 0x00 OP_1 = 0x51 OP_2 = 0x52 OP_16 = 0x60 OP_DUP = 0x76 OP_EQUAL = 0x87 OP_EQUALVERIFY = 0x88 OP_HASH160 = 0xa9 OP_CHECKSIG = 0xac pubkey_prefix = (OP_D...
if corrupt_suffix: suffix = os.urandom(len(template[2])) else: suffix = bytearray(template[2]) val = b58encode_chk(prefix + payload + suffix) if random.randint(0,10)<1: # line corruption if randbool(): # add random character to end val += random.choice(b58chars) ...
'''Generate possibly invalid vector''' # kinds of invalid vectors: # invalid prefix # invalid payload length # invalid (randomized) suffix (add random data) # corrupt checksum corrupt_prefix = randbool(0.2) randomize_payload_size = randbool(0.2) corrupt_suffix = randbool(0.2) ...
identifier_body
gen_key_io_test_vectors.py
'] # templates for valid sequences templates = [ # prefix, payload_size, suffix, metadata, output_prefix, output_suffix # None = N/A ((PUBKEY_ADDRESS,), 20, (), (False, 'main', None, None), pubkey_prefix, pubkey_suffix), ((SCRIPT_ADDRESS,), 20, (), (False...
i = len(rv) - random.randrange(1, 7) rv = rv[:i] + random.choice(CHARSET.replace(rv[i], '')) + rv[i + 1:]
conditional_block
gen_key_io_test_vectors.py
_TEST = 196 SCRIPT_ADDRESS_TEST2 = 58 PUBKEY_ADDRESS_REGTEST = 111 SCRIPT_ADDRESS_REGTEST = 196 PRIVKEY = 176 PRIVKEY_TEST = 239 PRIVKEY_REGTEST = 239 # script OP_0 = 0x00 OP_1 = 0x51 OP_2 = 0x52 OP_16 = 0x60 OP_DUP = 0x76 OP_EQUAL = 0x87 OP_EQUALVERIFY = 0x88 OP_HASH160 = 0xa9 OP_CHECKSIG = 0xac pubkey_prefix = (OP_D...
(v): '''Check vector v for bech32 validity''' for hrp in ['ltc', 'tltc', 'rltc']: if decode(hrp, v) != (None, None): return True return False def gen_valid_base58_vector(template): '''Generate valid base58 vector''' prefix = bytearray(template[0]) payload = bytearray(os.uran...
is_valid_bech32
identifier_name
Hero.tsx
import React, { ReactNode } from 'react' import styled from 'styled-components' import { M1, M2, M3, maxWidth, DESKTOP, PHONE } from '../constants/measurements' import { Section, Row, Col } from './Grid' import { Fade } from './Fade' import { H1, H3, P } from './Typography' const TextWrapper = styled.div<{}>` align...
* Set this to false when there are other async / transition related events * which are needed for the image to load properly * * For example, if using a lazy load gatsby-image, this should be false */ shouldFadeImage?: boolean } export const Hero = ({ Image, title, subtitle, body, shouldFade...
body?: string | ReactNode /** * If the image should be wrapped in a `<Fade />` component or not. *
random_line_split
spa.shell.js
{ opened : true, closed : true } }, resize_interval : 200, main_html : String() + '<div class="spa-shell-head">' + '<div class="spa-shell-head-logo">' + '<h1>SPA</h1>' + '<p>javascript end to end</p>' + '</div>' + '<div class="spa-shell-he...
// Settings : none // Returns : false // Actions : // * Parses the URI anchor component // * Compares proposed application state with current // * Adjust the application only where proposed state // differs from existing and is allowed by anchor schema // onHashchange = function ( ev...
// Begin Event handler /onHashchange/ // Purpose : Handles the hashchange event // Arguments : // * event - jQuery event object.
random_line_split
spa.shell.js
{ opened : true, closed : true } }, resize_interval : 200, main_html : String() + '<div class="spa-shell-head">' + '<div class="spa-shell-head-logo">' + '<h1>SPA</h1>' + '<p>javascript end to end</p>' + '</div>' + '<div class="spa-shell-he...
// End adjust chat component if changed // Begin revert anchor if slider change denied if ( ! is_ok ) { if ( anchor_map_previous ) { $.uriAnchor.setAnchor( anchor_map_previous, null, true ); stateMap.anchor_map = anchor_map_previous; } else { delete anchor_map_pro...
{ s_chat_proposed = anchor_map_proposed.chat; switch ( s_chat_proposed ) { case 'opened' : is_ok = spa.chat.setSliderPosition( 'opened' ); break; case 'closed' : is_ok = spa.chat.setSliderPosition( 'closed' ); break; default : spa.chat.se...
conditional_block
subreddit-picker-item-view.js
'click .add': 'subscribe', 'click .remove': 'unsubscribe' }, initialize: function(data) { this.model = data.model; }, subscribe: function(e) { e.preventDefault() e.stopPropagation() ...
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/subreddit-picker-item', 'view/basem-view'], function(App, $, _, Backbone, SRPitemTmpl, BaseView) { return BaseView.extend({ template: SRPitemTmpl, events: {
random_line_split
logParser.py
# # DESCRIPTION: This script parses the given input bowtie and/or LAST files and creates a csv row of their data in the given output csv. # # AUTHOR: Chelsea Tymms import sys, os.path import argparse def getOptions(): """Function to pull in arguments from the command line""" description="""This script takes an i...
def parseLastLog(fileName): """Function to parse a LAST log file""" if not os.path.isfile(fileName): print "WARNING: " +fileName+" does not exist." return 0,0 lastAmbig=0 lastUniq=0 with open(fileName,'rb') as lastLogFile: for line in lastLog...
"""Function to parse a bowtie log file""" if not os.path.isfile(fileName): print "WARNING: " +fileName+" does not exist." return 0,0,0,0 processed,aligned,unaligned,ambig=0,0,0,0 with open(fileName,'rb') as bowtieLogFile: for line in bowtieLogFile.readlines(): if 'reads...
identifier_body
logParser.py
# # DESCRIPTION: This script parses the given input bowtie and/or LAST files and creates a csv row of their data in the given output csv. # # AUTHOR: Chelsea Tymms import sys, os.path import argparse def getOptions(): """Function to pull in arguments from the command line""" description="""This script takes an in...
return int(lastAmbig),int(lastUniq) if __name__ == '__main__': main()
if "Ambiguously Aligned Reads" in line: lastAmbig=line.split(':')[1].strip() elif "Uniquely Aligned Reads" in line: lastUniq=line.split(':')[1].strip()
random_line_split
logParser.py
# # DESCRIPTION: This script parses the given input bowtie and/or LAST files and creates a csv row of their data in the given output csv. # # AUTHOR: Chelsea Tymms import sys, os.path import argparse def
(): """Function to pull in arguments from the command line""" description="""This script takes an input fasta file of fusions and identifies all of the identical fusions.""" parser = argparse.ArgumentParser(description=description) parser.add_argument("-bowtie", "--bowtie_log_names", dest="bowtie", action='store', ...
getOptions
identifier_name
logParser.py
# # DESCRIPTION: This script parses the given input bowtie and/or LAST files and creates a csv row of their data in the given output csv. # # AUTHOR: Chelsea Tymms import sys, os.path import argparse def getOptions(): """Function to pull in arguments from the command line""" description="""This script takes an i...
outputFile.write(','.join(str(i) for i in treatmentArray)+',') if args.bowtie: #Get some important counts from the first and the final bowtie logs proc,aln,unaln,ambig=parseBowtieLog(args.bowtie[0]) firstBowtieTot=proc proc,aln,unaln,ambig=parseBowtieLog(ar...
outputFile=open(args.output,'w') for i in range(1,len(treatmentArray)+1): outputFile.write('t_var_'+str(i)+',') if args.bowtie: for i in range(1,len(args.bowtie)+1): bowtieNum='bowtie'+str(i) outputFile.write(','.join(bowtieNum+'_'+n for n in ['tot...
conditional_block
sync.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
if ( opts.dir ) { dir = resolve( cwd(), opts.dir ); } else { dir = cwd(); } pattern = opts.pattern; opts = { 'cwd': dir, 'ignore': IGNORE, 'nodir': true // do not match directories }; names = glob( pattern, opts ); return linter( names ); } // EXPORTS // module.exports = lint;
{ err = validate( opts, options ); if ( err ) { throw err; } }
conditional_block
sync.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
( options ) { var pattern; var names; var opts; var err; var dir; opts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } if ( opts.dir ) { dir = resolve( cwd(), opts.dir ); } else { dir = cwd(); } pattern = opts.pattern; opts = { 'cw...
lint
identifier_name
sync.js
/** * @license Apache-2.0
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Lic...
* * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
random_line_split
sync.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
opts = { 'cwd': dir, 'ignore': IGNORE, 'nodir': true // do not match directories }; names = glob( pattern, opts ); return linter( names ); } // EXPORTS // module.exports = lint;
{ var pattern; var names; var opts; var err; var dir; opts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } if ( opts.dir ) { dir = resolve( cwd(), opts.dir ); } else { dir = cwd(); } pattern = opts.pattern;
identifier_body
syst_rvr.rs
#[doc = "Register `SYST_RVR` reader"] pub struct R(crate::R<SYST_RVR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SYST_RVR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SYST_RVR_SPEC>> for R { #[inline(always)] fn from(reader: ...
0 } }
#[doc = "`reset()` method sets SYST_RVR to value 0"] impl crate::Resettable for SYST_RVR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux {
random_line_split
syst_rvr.rs
#[doc = "Register `SYST_RVR` reader"] pub struct R(crate::R<SYST_RVR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SYST_RVR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SYST_RVR_SPEC>> for R { #[inline(always)] fn from(reader: ...
} #[doc = "SysTick Reload Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#re...
{ self.0.bits(bits); self }
identifier_body
syst_rvr.rs
#[doc = "Register `SYST_RVR` reader"] pub struct R(crate::R<SYST_RVR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SYST_RVR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SYST_RVR_SPEC>> for R { #[inline(always)] fn from(reader: ...
(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0x00ff_ffff) | (value as u32 & 0x00ff_ffff); self.w } } impl R { #[doc = "Bits 0:23 - Reload Value"] #[inline(always)] pub fn reload(&self) -> RELOAD_R { RELOAD_R::new((self.bits & 0x00ff_ffff) as u32) } } impl W...
bits
identifier_name
index.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
{ console.log( 'acot(%d) = %d', x[ i ], acot( x[ i ] ) ); }
conditional_block
index.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
for ( i = 0; i < x.length; i++ ) { console.log( 'acot(%d) = %d', x[ i ], acot( x[ i ] ) ); }
var x = linspace( -5.0, 5.0, 100 ); var i;
random_line_split
upgrade.d.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 { ApplicationRef, OpaqueToken } from '@angular/core'; import { ExtraOptions, RouterPreloader } from '@angular/...
* export class AppModule { * ngDoBootstrap() {} * } * ``` * * @experimental */ export declare const RouterUpgradeInitializer: { provide: OpaqueToken; useFactory: (ngUpgrade: UpgradeModule, ref: ApplicationRef, preloader: RouterPreloader, opts: ExtraOptions) => Function; deps: (OpaqueToken | typeof ...
* ], * providers: [ * RouterUpgradeInitializer * ] * })
random_line_split
LineView.js
var angleExtent = angleAxis.getExtent(); var RADIAN = Math.PI / 180; // Avoid float number rounding error for symbol on the edge of axis extent. if (forSymbol) { radiusExtent[0] -= 0.5; radiusExtent[1] += 0.5; } var clipPath = new graphic.Sector({ shape: { ...
} if (!visualMeta) { if (__DEV__) { console.warn('Visual map on line style only support x or y dimension.'); } return; } // If the area to be rendered is bigger than area defined by LinearGradient, // the canvas spec prescribes that the color of the first stop ...
{ visualMeta = visualMetaList[i]; break; }
conditional_block
LineView.js
(); var angleExtent = angleAxis.getExtent(); var RADIAN = Math.PI / 180; // Avoid float number rounding error for symbol on the edge of axis extent. if (forSymbol) { radiusExtent[0] -= 0.5; radiusExtent[1] += 0.5; } var clipPath = new graphic.Sector({ shape: { ...
return; } // Otherwise follow the label interval strategy on category axis. var categoryDataDim = data.mapDimension(categoryAxis.dim); var labelMap = {}; zrUtil.each(categoryAxis.getViewLabels(), function (labelItem) { labelMap[labelItem.tickValue] = 1; }); return function...
{ var showAllSymbol = seriesModel.get('showAllSymbol'); var isAuto = showAllSymbol === 'auto'; if (showAllSymbol && !isAuto) { return; } var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; if (!categoryAxis) { return; } // Note that category label interval strate...
identifier_body
LineView.js
*/ // FIXME step not support polar import {__DEV__} from '../../config'; import * as zrUtil from 'zrender/src/core/util'; import SymbolDraw from '../helper/SymbolDraw'; import SymbolClz from '../helper/Symbol'; import lineAnimationDiff from './lineAnimationDiff'; import * as graphic from '../../util/graphic'; import ...
random_line_split
LineView.js
(smooth) { return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0); } function getAxisExtentWithGap(axis) { var extent = axis.getGlobalExtent(); if (axis.onBand) { // Remove extra 1px to avoid line miter in clipped edge var halfBandWidth = axis.getBandWidth() / 2 - 1; var ...
getSmooth
identifier_name
win32_aclui.py
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling...
_l = logging.getLogger(name=__name__) lib = SimLibrary() lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.set_library_names("aclui.dll") prototypes = \ { # 'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="ISecurityInformation")], SimTypePoint...
random_line_split
generic-function.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() {()}
zzz
identifier_name
generic-function.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// lldb-command:print *t0 // lldb-check:[...]$6 = 5 // lldb-command:print *t1 // lldb-check:[...]$7 = Struct { a: 6, b: 7.5 } // lldb-command:print ret // lldb-check:[...]$8 = ((5, Struct { a: 6, b: 7.5 }), (Struct { a: 6, b: 7.5 }, 5)) // lldb-command:continue #![omit_gdb_pretty_printer_section] #[derive(Clone)] st...
// lldb-command:print ret // lldb-check:[...]$5 = ((3.5, 4), (4, 3.5)) // lldb-command:continue
random_line_split
views.py
import uuid from random import randint from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Url def index(request):
def make_url(request): if request.method == "POST": url = None # initial url url_site = request.POST['url'] url_id = generate_key() try: url = Url.objects.get(url_id = url_id) while url: url_id = generate_key() url = Url.obj...
if request.session.has_key("has_url"): url = request.session.get("has_url") del request.session['has_url'] return render(request, "miudo/index.html", locals()) return render(request, "miudo/index.html", {})
identifier_body
views.py
import uuid from random import randint from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Url def index(request): if request.session.has_key("has_url"): url = request.session.get("has_url") del request.session['has_url'] return render(req...
url.save() def generate_key(): to_choose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; url_id = "" while len(url_id) != 6: i = randint(0, len(to_choose) - 1) url_id += to_choose[i] return url_id def redirect_url(request, url_id=None): try: url = U...
url = Url.objects.create(url_id = url_id, url_site = url_site)
conditional_block
views.py
import uuid from random import randint from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Url def index(request): if request.session.has_key("has_url"): url = request.session.get("has_url") del request.session['has_url'] return render(req...
(request): if request.method == "POST": url = None # initial url url_site = request.POST['url'] url_id = generate_key() try: url = Url.objects.get(url_id = url_id) while url: url_id = generate_key() url = Url.objects.get(url_i...
make_url
identifier_name
views.py
import uuid from random import randint from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Url def index(request): if request.session.has_key("has_url"): url = request.session.get("has_url") del request.session['has_url'] return render(req...
def make_url(request): if request.method == "POST": url = None # initial url url_site = request.POST['url'] url_id = generate_key() try: url = Url.objects.get(url_id = url_id) while url: url_id = generate_key() url = Url.objec...
random_line_split
tweet_card.py
#! /usr/bin/env python import rospy import sys from time import sleep import actionlib import yaml from random import randint #from threading import Timer import strands_tweets.msg import image_branding.msg from std_msgs.msg import String from sensor_msgs.msg import Image #from cv_bridge import CvBridge, CvBridge...
filename=str(sys.argv[1]) rospy.init_node('card_image_tweet') ps = read_and_tweet(filename) rospy.spin()
print "usage: tweet_card file_texts.yaml" sys.exit(2)
conditional_block
tweet_card.py
#! /usr/bin/env python import rospy import sys from time import sleep import actionlib import yaml from random import randint #from threading import Timer import strands_tweets.msg import image_branding.msg from std_msgs.msg import String from sensor_msgs.msg import Image #from cv_bridge import CvBridge, CvBridge...
self.msg_sub = rospy.Subscriber('/socialCardReader/commands', String, self.command_callback, queue_size=1) self.client = actionlib.SimpleActionClient('strands_tweets', strands_tweets.msg.SendTweetAction) self.brandclient = actionlib.SimpleActionClient('/image_branding', image_branding.msg.Imag...
def __init__(self, filename): # rospy.on_shutdown(self._on_node_shutdown)
random_line_split
tweet_card.py
#! /usr/bin/env python import rospy import sys from time import sleep import actionlib import yaml from random import randint #from threading import Timer import strands_tweets.msg import image_branding.msg from std_msgs.msg import String from sensor_msgs.msg import Image #from cv_bridge import CvBridge, CvBridge...
(self, msg): command_msg = msg.data if command_msg == 'PHOTO' : self.msg_sub.unregister() #/head_xtion/depth/image_rect_meters #store this try: msg = rospy.wait_for_message('/head_xtion/rgb/image_color', Image, timeout=1.0) except rospy.ROS...
command_callback
identifier_name
tweet_card.py
#! /usr/bin/env python import rospy import sys from time import sleep import actionlib import yaml from random import randint #from threading import Timer import strands_tweets.msg import image_branding.msg from std_msgs.msg import String from sensor_msgs.msg import Image #from cv_bridge import CvBridge, CvBridge...
def command_callback(self, msg): command_msg = msg.data if command_msg == 'PHOTO' : self.msg_sub.unregister() #/head_xtion/depth/image_rect_meters #store this try: msg = rospy.wait_for_message('/head_xtion/rgb/image_color', Image, timeout=1.0) ...
self.msg_sub = rospy.Subscriber('/socialCardReader/commands', String, self.command_callback, queue_size=1) self.client = actionlib.SimpleActionClient('strands_tweets', strands_tweets.msg.SendTweetAction) self.brandclient = actionlib.SimpleActionClient('/image_branding', image_branding.msg.ImageBranding...
identifier_body
fields.py
import re from django.db.models import fields from django.template.defaultfilters import slugify def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): slug_field = instance._meta.get_field(slug_field_name) slug_len = slug_field.max_length # Sort out the initial s...
"""Pre-save event""" current_slug = getattr(model_instance, self.attname) # Use current slug instead, if it is given. # Assumption: There are no empty slugs. if not (current_slug is None or current_slug == ""): slug = current_slug else: slug = sel...
identifier_body
fields.py
import re from django.db.models import fields from django.template.defaultfilters import slugify def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): slug_field = instance._meta.get_field(slug_field_name) slug_len = slug_field.max_length # Sort out the initial s...
slug = current_slug else: slug = self.prepopulate_separator.\ join(unicode(getattr(model_instance, prepop)) for prepop in self.prepopulate_from) if self.unique: return _unique_slugify(model_instance, value...
# Use current slug instead, if it is given. # Assumption: There are no empty slugs. if not (current_slug is None or current_slug == ""):
random_line_split
fields.py
import re from django.db.models import fields from django.template.defaultfilters import slugify def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): slug_field = instance._meta.get_field(slug_field_name) slug_len = slug_field.max_length # Sort out the initial s...
(value, separator=None): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ if separator == '-' or not se...
_slug_strip
identifier_name
fields.py
import re from django.db.models import fields from django.template.defaultfilters import slugify def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'): slug_field = instance._meta.get_field(slug_field_name) slug_len = slug_field.max_length # Sort out the initial s...
# Find a unique slug. If one matches, at '-2' to the end and try again # (then '-3', etc). next = 2 while not slug or queryset.filter(**{slug_field_name: slug}): slug = original_slug end = '-%s' % next if slug_len and len(slug) + len(end) > slug_len: slug = slug[:sl...
queryset = instance.__class__._default_manager.all() if instance.pk: queryset = queryset.exclude(pk=instance.pk)
conditional_block
serial.js
'use strict'; goog.provide('Blockly.JavaScript.serial'); goog.require('Blockly.JavaScript'); Blockly.JavaScript.serial_print = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"' var code = 'serial.writeString(\'\' + '+content+');\n'; return code...
}; Blockly.JavaScript.serial_readstr = function() { var code ="serial.readString()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readline = function() { var code ="serial.readLine()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readstr_unt...
var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';'; var branch = Blockly.JavaScript.statementToCode(this, 'DO'); Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marke...
random_line_split
material-checkbox.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { hasOwn } from './../../shared/utility.functions'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-checkbox-widget', template: ` <md-che...
}
{ this.data = this.jsf.data; let result: boolean = true; if (this.data && hasOwn(this.options, 'condition')) { const model = this.data; /* tslint:disable */ eval('result = ' + this.options.condition); /* tslint:enable */ } return result; }
identifier_body
material-checkbox.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { hasOwn } from './../../shared/utility.functions'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-checkbox-widget', template: ` <md-che...
return result; } }
random_line_split
material-checkbox.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { hasOwn } from './../../shared/utility.functions'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-checkbox-widget', template: ` <md-che...
() { this.options = this.layoutNode.options || {}; this.jsf.initializeControl(this); if (this.controlValue === null || this.controlValue === undefined) { this.controlValue = false; } } updateValue(event) { this.jsf.updateValue(this, event.checked ? this.trueValue : this.falseValue); } ...
ngOnInit
identifier_name