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
pin-needed-to-poll-2.rs
use std::{ future::Future, pin::Pin, marker::Unpin, task::{Context, Poll}, }; struct Sleep(std::marker::PhantomPinned); impl Future for Sleep { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Poll::Ready(()) } } impl Drop for Sleep { ...
() -> Self { Self { sleep: sleep(), } } } impl Future for MyFuture { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.sleep).poll(cx) //~^ ERROR `PhantomPinned` cannot be unpinned } } fn ma...
new
identifier_name
pin-needed-to-poll-2.rs
use std::{ future::Future, pin::Pin, marker::Unpin, task::{Context, Poll}, }; struct Sleep(std::marker::PhantomPinned); impl Future for Sleep { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Poll::Ready(()) } } impl Drop for Sleep { ...
{}
identifier_body
connectionService.js
/*! * speedt * Copyright(c) 2015 speedt <13837186852@qq.com> * BSD 3 Licensed */ 'use strict'; var utils = require('speedt-utils'); var Service = function(app){ var self = this; // TODO self.serverId = app.getServerId(); self.connCount = 0; self.loginedCount = 0; self.logined = {}; }; module.exports = Serv...
proto.increaseConnectionCount = function(){ return ++this.connCount; }; proto.decreaseConnectionCount = function(uid){ var self = this; // TODO var result = [--self.connCount]; // TODO if(uid) result.push(removeLoginedUser.call(self, uid)); return result; }; proto.replaceLoginedUser = function(uid, info){ va...
var proto = Service.prototype;
random_line_split
stub.py
count=len(ns_records), arcount=len(ar), *args, **kwargs) self.header = header @classmethod def build_from_binstream(cls, binstream): header = DNSHeader.build_from_binstream(binstream) questions = tuple([DNSQuestion.build_from_binstream(binstream) for i in range(header.qdcount)]) an...
self.log(30, '{!a} got truncated dns response {!a} over TCP from {!a}. Ignoring.'.format(self, dns_frame, source)) return
conditional_block
stub.py
self.rdata = rdata @classmethod def build_from_binstream(cls, binstream): name = DomainName.build_from_binstream(binstream) tctl_str = binstream.read(10) if (len(tctl_str) < 10): raise ValueError('Insufficient data in binstream') (rtype, rclass, ttl, rdlength) = s...
self.ttl = ttl
random_line_split
stub.py
'recursion_desired', 'recursion_available', 'response_code', 'qdcount', 'ancount', 'nscount', 'arcount') def __init__(self, id, response=False, opcode=0, authoritative_answer=False, truncation=False, recursion_desired=True, recursion_available=False, response_code=0, qdcount=0, ancount=0, nsco...
(self): """Process a timeout on this query""" self.tt = None self.la.query_forget(self) try: self.failure_report() finally: self.la = None def failure_report(self): """Call callback handler with dummy results indicating lookup failure""" self.result_han...
timeout_process
identifier_name
stub.py
@classmethod def build_from_file(cls, fn=None): if (fn is None): fn = cls.DEFAULT_FN nameservers = [] try: f = open(fn, 'r') except IOError: pass else: for line in f: words = line.split() if (not words): cont...
return self.get_rr_bytypes((RDATA_MX.type,))
identifier_body
strcmp.rs
#[macro_export] macro_rules! strcmp_tests { ( $TestRegion:path ) => { use libc::{c_char, c_int, c_void, strcmp}; use lucet_runtime::vmctx::lucet_vmctx; use lucet_runtime::{lucet_hostcalls, Error, Limits, Region, Val, WASM_PAGE_SIZE}; use std::ffi::CString; use std::sync::Arc;...
.into_bytes_with_nul(); assert!(s1.len() + s2.len() < WASM_PAGE_SIZE as usize); let module = test_module_c("strcmp", "guest.c").expect("compile module"); let region = TestRegion::create(10, &Limits::default()).expect("region can be created"); let mut ins...
.into_bytes_with_nul(); let s2 = CString::new(s2) .expect("s2 is a valid CString")
random_line_split
filterManager.d.ts
import { AgPromise } from '../utils'; import { RowNode } from '../entities/rowNode'; import { Column } from '../entities/column'; import { ColumnEventType } from '../events'; import { IFilterComp, IFilterParams } from '../interfaces/iFilter'; import { ColDef } from '../entities/colDef'; import { BeanStub } from '../con...
extends BeanStub { private $compile; private $scope; private valueService; private columnController; private rowModel; private columnApi; private gridApi; private userComponentFactory; static QUICK_FILTER_SEPARATOR: string; private allAdvancedFilters; private activeAdvancedF...
FilterManager
identifier_name
filterManager.d.ts
import { AgPromise } from '../utils'; import { RowNode } from '../entities/rowNode'; import { Column } from '../entities/column'; import { ColumnEventType } from '../events'; import { IFilterComp, IFilterParams } from '../interfaces/iFilter'; import { ColDef } from '../entities/colDef'; import { BeanStub } from '../con...
private onNewColumnsLoaded; destroyFilter(column: Column, source?: ColumnEventType): void; private disposeFilterWrapper; protected destroy(): void; } export interface FilterWrapper { compiledElement: any; column: Column; filterPromise: AgPromise<IFilterComp> | null; scope: any; guiPr...
private createFilterInstance; createFilterParams(column: Column, colDef: ColDef, $scope?: any): IFilterParams; private createFilterWrapper; private putIntoGui;
random_line_split
wikulu.js
/******************************************************************************* * Copyright 2010-2016 Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as publ...
) { return 'http://www.w3.org/1999/xhtml'; } function findAndReplace(searchText, replacement, searchNode) { if (!searchText || typeof replacement === 'undefined') { // Throw error here if you want... return; } var regex = typeof searchText === 'string' ? new RegE...
esolver(
identifier_name
wikulu.js
/******************************************************************************* * Copyright 2010-2016 Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as publ...
return frag; })(); parent.insertBefore(frag, currentNode); parent.removeChild(currentNode); } } /* * Error handling */ function wikuluErrorHandler(data) { alert("Error: " + data); setBusy(false); }
frag.appendChild(wrap.firstChild); }
conditional_block
wikulu.js
/******************************************************************************* * Copyright 2010-2016 Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as publ...
} function loadCSS(file) { var fileref = document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", file) if (typeof fileref != "undefined") document.getElementsByTagName("head")[0].appendChild(fileref) } function resolver() ...
random_line_split
wikulu.js
/******************************************************************************* * Copyright 2010-2016 Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as publ...
/* * Helpers */ function loadJS(file) { var fileref = document.createElement('script') fileref.setAttribute("type", "text/javascript") fileref.setAttribute("src", file) if (typeof fileref != "undefined") document.getElementsByTagName("someFunctionhead")[0].appendChild(fileref) } function loadCSS(file) { var...
runFunc(pluginClass); }
identifier_body
text_run.rs
_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun ...
(font: &mut Font, text: &str, options: &ShapingOptions, breaker: &mut Option<LineBreakLeafIter>) -> (Vec<GlyphRun>, bool) { let mut glyphs = vec!(); let mut slice = 0..0; let mut finished = false; let mut break_at_zero = false; if breaker.is_none() { ...
break_and_shape
identifier_name
text_run.rs
_of_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun ...
}) } pub fn minimum_splittable_inline_size(&self, range: &Range<
debug!("iterated on {:?}[{:?}]", slice.offset, slice.range); max(max_piece_width, self.advance_for_range(&slice.range))
random_line_split
text_run.rs
_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { ...
*breaker = Some(LineBreakLeafIter::new(&text, 0)); } let breaker = breaker.as_mut().unwrap(); while !finished { let (idx, _is_hard_break) = breaker.next(text); if idx == text.len() { finished = true; } if idx == 0 { ...
{ return (glyphs, true) }
conditional_block
text_run.rs
_first_glyph_run_cache.get() { if text_run_ptr == (self as *const TextRun) { index_of_first_glyph_run_cache.set(None); } } }) } } /// A single series of glyphs within a text run. #[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { ...
pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<ByteIndex>) -> RunMetrics { RunMetrics::new(glyphs.advance_for_byte_range(slice_range, self.extra_word_spacing), self.font_metrics.ascent, self.font_metrics...
{ RunMetrics::new(self.advance_for_range(range), self.font_metrics.ascent, self.font_metrics.descent) }
identifier_body
cover.py
"""Platform for the Garadget cover component.""" import logging import requests import voluptuous as vol from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_COVERS, CONF_DEVICE, CONF_NAME, CONF_PASSWORD, CONF_USERNAM...
"""Return the class of this device, from component DEVICE_CLASSES.""" return "garage" def get_token(self): """Get new token for usage during this session.""" args = { "grant_type": "password", "username": self._username, "password": self._password...
@property def device_class(self):
random_line_split
cover.py
"""Platform for the Garadget cover component.""" import logging import requests import voluptuous as vol from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_COVERS, CONF_DEVICE, CONF_NAME, CONF_PASSWORD, CONF_USERNAM...
def _start_watcher(self, command): """Start watcher.""" _LOGGER.debug("Starting Watcher for command: %s ", command) if self._unsub_listener_cover is None: self._unsub_listener_cover = track_utc_time_change( self.hass, self._check_state ) def _ch...
"""Remove authorization token from API.""" url = f"{self.particle_url}/v1/access_tokens/{self.access_token}" ret = requests.delete(url, auth=(self._username, self._password), timeout=10) return ret.text
identifier_body
cover.py
"""Platform for the Garadget cover component.""" import logging import requests import voluptuous as vol from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_COVERS, CONF_DEVICE, CONF_NAME, CONF_PASSWORD, CONF_USERNAM...
(self, now): """Check the state of the service during an operation.""" self.schedule_update_ha_state(True) def close_cover(self, **kwargs): """Close the cover.""" if self._state not in ["close", "closing"]: ret = self._put_command("setState", "close") self._s...
_check_state
identifier_name
cover.py
"""Platform for the Garadget cover component.""" import logging import requests import voluptuous as vol from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_COVERS, CONF_DEVICE, CONF_NAME, CONF_PASSWORD, CONF_USERNAM...
if self.sensor is not None: data[ATTR_SENSOR_STRENGTH] = self.sensor if self.access_token is not None: data[CONF_ACCESS_TOKEN] = self.access_token return data @property def is_closed(self): """Return if the cover is closed.""" if self._state i...
data[ATTR_TIME_IN_STATE] = self.time_in_state
conditional_block
pla.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
/// The index for each input is the index of the corresponding AND term in the same PLA. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub struct XC2PLAOrTerm { /// Indicates whether a particular PLA AND term is a part of this OR term. /// /// `true` = part of or, `false` = not ...
/// Represents one single OR term in the PLA. Each OR term can perform an OR function on any subset of its inputs.
random_line_split
pla.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
else { self.input[i / 8] |= 1 << (i % 8); } } /// Sets whether the `i`th input complement is used in this AND term pub fn set_b(&mut self, i: usize, val: bool) { if !val { self.input_b[i / 8] &= !(1 << (i % 8)); } else { self.input_b[i / 8] |= ...
{ self.input[i / 8] &= !(1 << (i % 8)); }
conditional_block
pla.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
() -> Self { XC2PLAOrTerm { input: [0u8; ANDTERMS_PER_FB / 8], } } } impl XC2PLAOrTerm { /// Internal function that reads one single OR term from a block of fuses using logical fuse indexing pub fn from_jed(fuses: &[bool], block_idx: usize, term_idx: usize) -> XC2PLAOrTerm { ...
default
identifier_name
test_to_from_refined.py
import IMP import IMP.test import IMP.core class Tests(IMP.test.TestCase): """Tests copying derivatives to and from refined""" def _create_particle(self, m, ks): p = IMP.Particle(m) for k in ks:
return p def _setup(self): k0 = IMP.FloatKey("Key0") k1 = IMP.FloatKey("Key1") ks = IMP.FloatKeys() ks.append(k0) ks.append(k1) m = IMP.Model() p0 = self._create_particle(m, ks) p1 = self._create_particle(m, ks) p2 = self._create_part...
p.add_attribute(k, 0.0)
conditional_block
test_to_from_refined.py
import IMP import IMP.test import IMP.core class Tests(IMP.test.TestCase): """Tests copying derivatives to and from refined""" def _create_particle(self, m, ks): p = IMP.Particle(m) for k in ks: p.add_attribute(k, 0.0) return p def _setup(self): k0 = IMP.Floa...
if __name__ == '__main__': IMP.test.main()
"""Test copying derivatives from refined""" h0, h1, h2, p0, p1, p2, r, ks, m = self._setup() da = IMP.DerivativeAccumulator() p1.add_to_derivative(ks[0], 1, da) p1.add_to_derivative(ks[1], 2, da) p2.add_to_derivative(ks[0], 4, da) p2.add_to_derivative(ks[1], 8, da) ...
identifier_body
test_to_from_refined.py
import IMP import IMP.test import IMP.core class Tests(IMP.test.TestCase): """Tests copying derivatives to and from refined""" def _create_particle(self, m, ks): p = IMP.Particle(m)
p.add_attribute(k, 0.0) return p def _setup(self): k0 = IMP.FloatKey("Key0") k1 = IMP.FloatKey("Key1") ks = IMP.FloatKeys() ks.append(k0) ks.append(k1) m = IMP.Model() p0 = self._create_particle(m, ks) p1 = self._create_particle(m,...
for k in ks:
random_line_split
test_to_from_refined.py
import IMP import IMP.test import IMP.core class Tests(IMP.test.TestCase): """Tests copying derivatives to and from refined""" def _create_particle(self, m, ks): p = IMP.Particle(m) for k in ks: p.add_attribute(k, 0.0) return p def _setup(self): k0 = IMP.Floa...
(self): """Test copying derivatives from refined""" h0, h1, h2, p0, p1, p2, r, ks, m = self._setup() da = IMP.DerivativeAccumulator() p1.add_to_derivative(ks[0], 1, da) p1.add_to_derivative(ks[1], 2, da) p2.add_to_derivative(ks[0], 4, da) p2.add_to_derivative(ks[1...
test_from
identifier_name
rc.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/lib/mem/rc.rs //! Reference-counted shared allocation use core::{ops,fmt}; use super::grc::Grc; /// Non-atomic reference counted type pub struct Rc<T: ?Sized> { _inner: Grc<::core::cell::Cell<usize>, T>, } // Rc is not Send or Sync impl<T: ?Sized> !S...
} impl<T: ?Sized> Clone for Rc<T> { fn clone(&self) -> Rc<T> { Rc { _inner: self._inner.clone() } } } impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { <T as fmt::Display>::fmt(&**self, f) } } impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> { fn...
{ self._inner.is_same( &other._inner ) }
identifier_body
rc.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang)
use super::grc::Grc; /// Non-atomic reference counted type pub struct Rc<T: ?Sized> { _inner: Grc<::core::cell::Cell<usize>, T>, } // Rc is not Send or Sync impl<T: ?Sized> !Send for Rc<T> {} impl<T: ?Sized> !Sync for Rc<T> {} impl<T: ?Sized, U: ?Sized> ops::CoerceUnsized<Rc<U>> for Rc<T> where T: ::core::marker::U...
// // Core/lib/mem/rc.rs //! Reference-counted shared allocation use core::{ops,fmt};
random_line_split
rc.rs
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/lib/mem/rc.rs //! Reference-counted shared allocation use core::{ops,fmt}; use super::grc::Grc; /// Non-atomic reference counted type pub struct Rc<T: ?Sized> { _inner: Grc<::core::cell::Cell<usize>, T>, } // Rc is not Send or Sync impl<T: ?Sized> !S...
(&self, other: &Rc<T>) -> bool { self._inner.is_same( &other._inner ) } } impl<T: ?Sized> Clone for Rc<T> { fn clone(&self) -> Rc<T> { Rc { _inner: self._inner.clone() } } } impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { <T as fmt::Display>::fm...
is_same
identifier_name
mv.py
self.config = { "command": { "mv": { "function": self.mvScreams, "usage": "mv <user>", "help": "Le clavier y colle!" } }} return self.config def mvScreams(self, Morphux, infos): print(infos) if (le...
# -*- coding: utf8 -*- class Mv: def command(self):
random_line_split
mv.py
# -*- coding: utf8 -*- class Mv: def command(self): self.config = { "command": { "mv": { "function": self.mvScreams, "usage": "mv <user>", "help": "Le clavier y colle!" } }} return self.config def mvScreams(se...
elif (infos['args'][0] == "allow"): Morphux.sendMessage("ALLOW?", infos['nick']) elif (infos['args'][0] == "thunes"): Morphux.sendMessage("Money equals power", infos['nick']) elif (infos['args'][0] == "theodule"): Morphux.sendMessage("THEODUUULE", infos['nick...
Morphux.sendMessage("SARACE BOULBA", infos['nick'])
conditional_block
mv.py
# -*- coding: utf8 -*- class Mv: def command(self): self.config = { "command": { "mv": { "function": self.mvScreams, "usage": "mv <user>", "help": "Le clavier y colle!" } }} return self.config def
(self, Morphux, infos): print(infos) if (len(infos['args']) == 0 and infos['nick'] == "valouche"): Morphux.sendMessage("Ta mere la chauve", infos['nick']) elif (len(infos['args']) == 0 and infos['nick'] == "Ne02ptzero"): Morphux.sendMessage("TU VAS LA CHIER TA CHIASSE?", ...
mvScreams
identifier_name
mv.py
# -*- coding: utf8 -*- class Mv:
Morphux.sendMessage("ALLOW?", infos['nick']) elif (infos['args'][0] == "thunes"): Morphux.sendMessage("Money equals power", infos['nick']) elif (infos['args'][0] == "theodule"): Morphux.sendMessage("THEODUUULE", infos['nick']) elif (infos['args'][0] == "gg"): ...
def command(self): self.config = { "command": { "mv": { "function": self.mvScreams, "usage": "mv <user>", "help": "Le clavier y colle!" } }} return self.config def mvScreams(self, Morphux, infos): print(in...
identifier_body
request.throttler.spec.ts
import * as express from 'express'; import { Response, Request, NextFunction, Application } from 'express'; import * as chai from 'chai'; import { RequestThrottler } from '../request.throttler'; const { expect, request } = chai; describe('Request Throttler', () => { describe('Test throttler', () => { it ('shoul...
expect(res.status).to.equal(429); done(); }); }); }); it ('should throttle white list IP', (done) => { const options = { namespace: '', interval: 1000, maxInInterval: 1, minDifference: 0, whiteList: ['127.0.0.1'] }; co...
expect(res.status).to.equal(404); // 404 because throttle test app doesn't have any routes // send next request immediately and check it's getting throttled request(app).post('/user').set('Accept', 'application/json').send(data).end((err, res) => {
random_line_split
nowvideo.py
from __future__ import unicode_literals from .novamov import NovaMovIE class
(NovaMovIE): IE_NAME = 'nowvideo' IE_DESC = 'NowVideo' _VALID_URL = NovaMovIE._VALID_URL_TEMPLATE % {'host': 'nowvideo\.(?:ch|ec|sx|eu|at|ag|co|li)'} _HOST = 'www.nowvideo.ch' _FILE_DELETED_REGEX = r'>This file no longer exists on our servers.<' _FILEKEY_REGEX = r'var fkzd="([^"]+)";' _TI...
NowVideoIE
identifier_name
nowvideo.py
from __future__ import unicode_literals from .novamov import NovaMovIE class NowVideoIE(NovaMovIE):
} }
IE_NAME = 'nowvideo' IE_DESC = 'NowVideo' _VALID_URL = NovaMovIE._VALID_URL_TEMPLATE % {'host': 'nowvideo\.(?:ch|ec|sx|eu|at|ag|co|li)'} _HOST = 'www.nowvideo.ch' _FILE_DELETED_REGEX = r'>This file no longer exists on our servers.<' _FILEKEY_REGEX = r'var fkzd="([^"]+)";' _TITLE_REGEX = r'<h4...
identifier_body
nowvideo.py
from __future__ import unicode_literals from .novamov import NovaMovIE class NowVideoIE(NovaMovIE): IE_NAME = 'nowvideo' IE_DESC = 'NowVideo'
_VALID_URL = NovaMovIE._VALID_URL_TEMPLATE % {'host': 'nowvideo\.(?:ch|ec|sx|eu|at|ag|co|li)'} _HOST = 'www.nowvideo.ch' _FILE_DELETED_REGEX = r'>This file no longer exists on our servers.<' _FILEKEY_REGEX = r'var fkzd="([^"]+)";' _TITLE_REGEX = r'<h4>([^<]+)</h4>' _DESCRIPTION_REGEX = r'</h4>...
random_line_split
labels.ts
import _remove from 'lodash.remove' import mapboxgl from 'mapbox-gl' type LayerWithMeta = mapboxgl.CircleLayer & { metatdata: any } export default { removeStyleLabels(style: mapboxgl.Style): mapboxgl.Style { if ( style.layers && Array.isArray(style.layers) && style.layers.length > 0 ) { ...
if ( markerOptions.shape !== 'MAP_PIN' && markerOptions.shape !== 'SQUARE_PIN' ) { offset = offset + markerOptions.height / 2 } translate = [0, offset] } } break } ca...
{ let sourceLayer = 'data' let filter = ['in', '$type', 'Point'] let placement: mapboxgl.SymbolLayout['symbol-placement'] = 'point' let translate = [0, 0] switch (data_type) { case 'point': { translate = [0, -14] // if marker for (const layer of style...
conditional_block
labels.ts
import _remove from 'lodash.remove' import mapboxgl from 'mapbox-gl' type LayerWithMeta = mapboxgl.CircleLayer & { metatdata: any } export default {
(style: mapboxgl.Style): mapboxgl.Style { if ( style.layers && Array.isArray(style.layers) && style.layers.length > 0 ) { // treat style as immutable and return a copy style = JSON.parse(JSON.stringify(style)) _remove(style.layers, (layer) => { return layer.id.starts...
removeStyleLabels
identifier_name
labels.ts
import _remove from 'lodash.remove' import mapboxgl from 'mapbox-gl' type LayerWithMeta = mapboxgl.CircleLayer & { metatdata: any } export default { removeStyleLabels(style: mapboxgl.Style): mapboxgl.Style
, addStyleLabels( style: mapboxgl.Style, field: string, layer_id: number, shortid: string, data_type: string ): mapboxgl.Style { // treat style as immutable and return a copy style = JSON.parse(JSON.stringify(style)) style = this.removeStyleLabels(style) if ( style.layers...
{ if ( style.layers && Array.isArray(style.layers) && style.layers.length > 0 ) { // treat style as immutable and return a copy style = JSON.parse(JSON.stringify(style)) _remove(style.layers, (layer) => { return layer.id.startsWith('omh-label') }) } re...
identifier_body
labels.ts
import _remove from 'lodash.remove' import mapboxgl from 'mapbox-gl' type LayerWithMeta = mapboxgl.CircleLayer & { metatdata: any } export default { removeStyleLabels(style: mapboxgl.Style): mapboxgl.Style { if ( style.layers && Array.isArray(style.layers) && style.layers.length > 0 ) { ...
translate = [0, -14] // if marker for (const layer of style.layers as LayerWithMeta[]) { if ( layer.id.startsWith('omh-data-point') && layer.metadata && layer.metadata['maphubs:markers'] && layer.metadata['maphubs:markers'...
case 'point': {
random_line_split
dns_remove_reverse_record.py
import subprocess, os, sys from reverseZone_naming import reverseZone_name from netaddr import * zone_files_path="/etc/bind/zones" def remove_reverse_record(): host_name_to_be_removed= sys.argv[1] reverse_zone_file_name,reverse_zone_name=reverseZone_name() os.chdir(zone_files_path) readFiles = open(reverse_zone_f...
def main(): remove_reverse_record() main()
print "\nThe record you wanted to remove is already absent in the database!\n"
conditional_block
dns_remove_reverse_record.py
import subprocess, os, sys from reverseZone_naming import reverseZone_name from netaddr import * zone_files_path="/etc/bind/zones" def
(): host_name_to_be_removed= sys.argv[1] reverse_zone_file_name,reverse_zone_name=reverseZone_name() os.chdir(zone_files_path) readFiles = open(reverse_zone_file_name,'r') reverse_zone_file_content = readFiles.read() readFiles.close() readFiles = open(reverse_zone_file_name,'r') lines = readFiles.readlines() ...
remove_reverse_record
identifier_name
dns_remove_reverse_record.py
import subprocess, os, sys from reverseZone_naming import reverseZone_name from netaddr import * zone_files_path="/etc/bind/zones" def remove_reverse_record():
print "\nThe record you wanted to remove is already absent in the database!\n" def main(): remove_reverse_record() main()
host_name_to_be_removed= sys.argv[1] reverse_zone_file_name,reverse_zone_name=reverseZone_name() os.chdir(zone_files_path) readFiles = open(reverse_zone_file_name,'r') reverse_zone_file_content = readFiles.read() readFiles.close() readFiles = open(reverse_zone_file_name,'r') lines = readFiles.readlines() read...
identifier_body
dns_remove_reverse_record.py
import subprocess, os, sys from reverseZone_naming import reverseZone_name from netaddr import * zone_files_path="/etc/bind/zones" def remove_reverse_record(): host_name_to_be_removed= sys.argv[1] reverse_zone_file_name,reverse_zone_name=reverseZone_name() os.chdir(zone_files_path) readFiles = open(reverse_zone_f...
readFiles.close() if host_name_to_be_removed in reverse_zone_file_content: file_content = open(reverse_zone_file_name,'w') for line in lines: if not host_name_to_be_removed in line: file_content.write(line) file_content.close() print "\nThe reverse record that you entered has been removed!\n" else...
readFiles = open(reverse_zone_file_name,'r') lines = readFiles.readlines()
random_line_split
optable.py
import re
('constant', 0x10, True, 'constant'), ('list', 0x20, True, 'vreg*'), ('move', 0x30, False, 'vreg vreg'), ('call', 0x40, True, 'vreg vreg*'), ('not', 0x41, True, 'vreg'), ('contains', 0x42, True, 'vreg vreg'), ('callv', 0x45, True, 'vreg vreg vreg*'), ('isnull', ...
source = [ ('assert', 0x00, False, 'vreg'), ('raise', 0x05, False, 'vreg'),
random_line_split
optable.py
import re source = [ ('assert', 0x00, False, 'vreg'), ('raise', 0x05, False, 'vreg'), ('constant', 0x10, True, 'constant'), ('list', 0x20, True, 'vreg*'), ('move', 0x30, False, 'vreg vreg'), ('call', 0x40, True, 'vreg vreg*'), ('not', 0x41, True, 'vreg'), ('con...
assert opcode not in dec, opcode pattern = re.split(r"\s+", form.rstrip('*')) if form.endswith('*'): variadic = pattern.pop() else: variadic = None enc[opname] = opcode, has_result, pattern, variadic dec[opcode] = opname, has_result, pattern, variadic names[opcode] = opname
conditional_block
interconnect.rs
use cpu::cpu::CPU; use cpu::mem::MMU; use cpu::gpu::GPU; pub struct Interconnect { pub mmu: MMU, pub gpu: GPU, } impl Interconnect { pub fn new() -> Self { Interconnect { mmu: MMU::new(), gpu: GPU::new(), } } pub fn read_word(&mut self) -> u16 { ...
(&mut self, value: u8, location: u16) { match location { 0x0000 ... 0x00FF => { println!("Restart and Interrupt Vectors"); }, 0x0100 ... 0x014F => { println!("Cartridge Header Area") }, 0x0150 ... 0x3FFF => { println!("Cartridge ROM - Bank 0 (fi...
write_word
identifier_name
interconnect.rs
use cpu::cpu::CPU; use cpu::mem::MMU; use cpu::gpu::GPU; pub struct Interconnect { pub mmu: MMU, pub gpu: GPU, } impl Interconnect { pub fn new() -> Self { Interconnect { mmu: MMU::new(), gpu: GPU::new(), } } pub fn read_word(&mut self) -> u16 { ...
0x0000 ... 0x00FF => { println!("Restart and Interrupt Vectors"); }, 0x0100 ... 0x014F => { println!("Cartridge Header Area") }, 0x0150 ... 0x3FFF => { println!("Cartridge ROM - Bank 0 (fixed)") }, 0x4000 ... 0x7FFF => { println!("Cartridge ...
match location {
random_line_split
interconnect.rs
use cpu::cpu::CPU; use cpu::mem::MMU; use cpu::gpu::GPU; pub struct Interconnect { pub mmu: MMU, pub gpu: GPU, } impl Interconnect { pub fn new() -> Self { Interconnect { mmu: MMU::new(), gpu: GPU::new(), } } pub fn read_word(&mut self) -> u16 { ...
}
{ println!("I'm a carrot!"); }
identifier_body
index.js
module.exports = function (str) { var bytes = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) { var cn = str.charCodeAt(i + 1); if (cn >= 0xdc00 && cn <= 0xdfff) { var pt = (c - 0x...
continue; } } if (c >= 2048) { bytes.push( 0xe0 + Math.floor(c / 64 / 64), 0x80 + Math.floor(c / 64) % 64, 0x80 + c % 64 ); } else if (c >= 128) { bytes.push(0xc0 + Math.floor(...
0x80 + pt % 64 ); i += 1;
random_line_split
index.js
module.exports = function (str) { var bytes = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) { var cn = str.charCodeAt(i + 1); if (cn >= 0xdc00 && cn <= 0xdfff) { var pt = (c - 0x...
else bytes.push(c); } return bytes; };
{ bytes.push(0xc0 + Math.floor(c / 64), 0x80 + c % 64); }
conditional_block
VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
elf, algorithm, data): self.Log(f"{self.Time}: {', '.join(str(x) for x in data.Insights)}") def OnOrderEvent(self, orderEvent): self.Log(f"{self.Time}: {orderEvent}")
InsightsGenerated(s
identifier_name
VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
self.InsightsGenerated += self.OnInsightsGenerated def OnInsightsGenerated(self, algorithm, data): self.Log(f"{self.Time}: {', '.join(str(x) for x in data.Insights)}") def OnOrderEvent(self, orderEvent): self.Log(f"{self.Time}: {orderEvent}")
# using hourly rsi to generate more insights self.SetAlpha(RsiAlphaModel(14, Resolution.Hour)) self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel()) self.SetExecution(VolumeWeightedAveragePriceExecutionModel())
random_line_split
VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
def OnInsightsGenerated(self, algorithm, data): self.Log(f"{self.Time}: {', '.join(str(x) for x in data.Insights)}") def OnOrderEvent(self, orderEvent): self.Log(f"{self.Time}: {orderEvent}")
lf.UniverseSettings.Resolution = Resolution.Minute self.SetStartDate(2013,10,7) self.SetEndDate(2013,10,11) self.SetCash(1000000) self.SetUniverseSelection(ManualUniverseSelectionModel([ Symbol.Create('AIG', SecurityType.Equity, Market.USA), Symbol.Create('BAC',...
identifier_body
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
match self.inner { Mode::Tokio(ref remote) => remote.spawn(move |handle| { let future = f().into_future(); let timeout = Timeout::new(duration, handle).expect("Event loop is still up."); future.select(timeout.then(move |_| { on_timeout(); Ok(()) })).then(|_| Ok(())) }), Mode::Sync =...
{
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() -> Self { let (stop, stopped) = futures::oneshot(); let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || { let mut el = tokio_core::reactor::Core::new().expect("Creating an event loop should not fail."); tx.send(el.remote()).expect("Rx is blocking upper thread."); let _ = el.run(futures:...
spawn
identifier_name
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Synchronous remote, used mostly for tests. pub fn new_sync() -> Self { Remote { inner: Mode::Sync, } } /// Spawns a new thread for each future (use only for tests). pub fn new_thread_per_future() -> Self { Remote { inner: Mode::ThreadPerFuture, } } /// Spawn a future to this event loop pu...
{ Remote { inner: Mode::Tokio(remote), } }
identifier_body
IN.py
INTMAX_C(c): return c ## L def UINTMAX_C(c): return c ## UL def INTMAX_C(c): return c ## LL def UINTMAX_C(c): return c ## ULL # Included from sys/socket.h _SYS_SOCKET_H = 1 # Included from sys/uio.h _SYS_UIO_H = 1 # Included from sys/types.h _SYS_TYPES_H = 1 # Included from bits/types.h _BITS_TYPES_H = 1 __S32...
PF_X25 = 9 PF_INET6 = 10 PF_ROSE = 11
random_line_split
IN.py
255) UINT_LEAST16_MAX = (65535) UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) INT_FAST8_MIN = (-128) INT_FAST16_MIN = (-9223372036854775807L-1) INT_FAST32_MIN = (-9223372036854775807L-1) INT_FAST16_MIN = (-2147483647-1) INT_FAST32_MIN = (-2147483647-1) INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) INT_FA...
htobe32
identifier_name
IN.py
UINT_LEAST8_MAX = (255) UINT_LEAST16_MAX = (65535) UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) INT_FAST8_MIN = (-128) INT_FAST16_MIN = (-9223372036854775807L-1) INT_FAST32_MIN = (-9223372036854775807L-1) INT_FAST16_MIN = (-2147483647-1) INT_FAST32_MIN = (-2147483647-1) INT_FAST64_MIN = (-__INT64_C(92233720368...
def UINT8_C(c): return c def UINT16_C(c): return c def UINT32_C(c): return c ## U def UINT64_C(c): return c ## UL def UINT64_C(c): return c ## ULL def INTMAX_C(c): return c ## L def UINTMAX_C(c): return c ## UL def INTMAX_C(c): return c ## LL def UINTMAX_C(c): return c ## ULL # Included from sys/socket.h _S...
return c ## LL
identifier_body
picturePolyfill.js
() { var newImg = document.createElement('img'), pictures, firstPicture; pictures = document.getElementsByTagName('picture'); firstPicture = pictures[0]; if (!pictures.length) { // Can't determine support if no pictures are in the page. Worst case will do. return false; } try { firstPicture.a...
_detectAppendImageSupport
identifier_name
picturePolyfill.js
/** * Appends an image element to a picture element * @param element * @param attributes * @private */ _appendImg: function(element, attributes) { var newImg = document.createElement('img'); this._setAttrs(newImg, attributes); element.appendChild(newImg); }, /** * Set all the "attri...
} } return {
random_line_split
picturePolyfill.js
} return { /** * Appends an image element to a picture element * @param element * @param attributes * @private */ _appendImg: function(element, attributes) { var newImg = document.createElement('img'); this._setAttrs(newImg, attributes); element.appendChild(newImg); }, /** * Set...
{ var newImg = document.createElement('img'), pictures, firstPicture; pictures = document.getElementsByTagName('picture'); firstPicture = pictures[0]; if (!pictures.length) { // Can't determine support if no pictures are in the page. Worst case will do. return false; } try { firstPicture.appe...
identifier_body
picturePolyfill.js
_appendImg: function(element, attributes) { var newImg = document.createElement('img'); this._setAttrs(newImg, attributes); element.appendChild(newImg); }, /** * Set all the "attributes" to an "element" * @param element * @param attributes * @private */ _setAttrs: function(element, attrib...
else { density = parseFloat(srcSetElement[srcSetElement.length-1], 10); } source = srcSetElement[0]; ret.push({pxr: density, src: source}); } return ret.sort(function(hash1, hash2) { var pxr1 = hash1.pxr, pxr2 = hash2.pxr; if (pxr1 < pxr2) { return -1; } if (pxr1 > pxr2) { retur...
{ density = 1; }
conditional_block
compoundexpressionnode.component.ts
import { AfterViewChecked, Component, DoCheck, ElementRef, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewChildren, } from '@angular/core'; import { ExpressionNodeComponent, EXPRESSION_NODE_COMPONENT } from '../expressio...
get operator(): string { return this._expression.operator.toString(); } set operator(value: string) { this.expression = this.expression.setOperator(parseInt(value, 10)); } get leftExpression(): Expression { return this._expression.left; } set leftExpression(express...
{ return this._expression; }
identifier_body
compoundexpressionnode.component.ts
import { AfterViewChecked, Component, DoCheck, ElementRef, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewChildren, } from '@angular/core'; import { ExpressionNodeComponent, EXPRESSION_NODE_COMPONENT } from '../expressio...
(changes: SimpleChanges) { if (!!this.flasher) { this._log.log(new NgOnChangesCalled(this.flasher), !this._logPlayback.isPlayingBack); } } ngDoCheck() { if (!!this.flasher) { this._log.log(new NgDoCheckCalled(this.flasher), !this._logPlayback.isPlayingBack); ...
ngOnChanges
identifier_name
compoundexpressionnode.component.ts
import { AfterViewChecked, Component, DoCheck, ElementRef, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewChildren, } from '@angular/core'; import { ExpressionNodeComponent, EXPRESSION_NODE_COMPONENT } from '../expressio...
this._expression = value; this.expressionChange.emit(this._expression); } get expression(): CompoundExpression { return this._expression; } get operator(): string { return this._expression.operator.toString(); } set operator(value: string) { this.expres...
{ this._log.log(new ExpressionChanged(this.flasher, this._expression, value), !this._logPlayback.isPlayingBack); }
conditional_block
compoundexpressionnode.component.ts
import { AfterViewChecked, Component, DoCheck, ElementRef, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, TemplateRef, ViewChild, ViewChildren, } from '@angular/core'; import { ExpressionNodeComponent, EXPRESSION_NODE_COMPONENT } from '../expressio...
@ViewChild('nodeElementRef', {read: ElementRef}) nodeElementRef: ElementRef; @ViewChild(FlasherComponent) flasher: FlasherComponent; @ViewChildren('leftExpressionNode, rightExpressionNode', {read: EXPRESSION_NODE_COMPONENT}) childExpressions: QueryList<ExpressionNodeComponent>; get childNodes(): Expres...
random_line_split
tapioca_instagram.py
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = 'https://api.instagram.com/v1/'
api_params, *args, **kwargs) params.setdefault('params', {}).update( {'access_token': api_params.get('access_token', '')} ) return params def get_iterator_list(self, response_data): return response_data['data'] def get_iterator_next_request_kwargs(self, ...
resource_mapping = RESOURCE_MAPPING def get_request_kwargs(self, api_params, *args, **kwargs): params = super(InstagramClientAdapter, self).get_request_kwargs(
random_line_split
tapioca_instagram.py
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = 'https://api.instagram.com/v1/' resource_mapping = RESOURCE_MAP...
(self, response_data): return response_data['data'] def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): paging = response_data.get('pagination') if not paging: return url = paging.get('nex...
get_iterator_list
identifier_name
tapioca_instagram.py
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = 'https://api.instagram.com/v1/' resource_mapping = RESOURCE_MAP...
Instagram = generate_wrapper_from_adapter(InstagramClientAdapter)
return {'url': url}
conditional_block
tapioca_instagram.py
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter):
if url: return {'url': url} Instagram = generate_wrapper_from_adapter(InstagramClientAdapter)
api_root = 'https://api.instagram.com/v1/' resource_mapping = RESOURCE_MAPPING def get_request_kwargs(self, api_params, *args, **kwargs): params = super(InstagramClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) params.setdefault('params', {}).update( ...
identifier_body
mysql.rs
//! MySQL Driver implementation use std::path::PathBuf; use mysql::conn::{MyOpts, pool}; use configreader::ConfigReader; #[derive(Clone)] pub struct
{ pub pool: pool::MyPool, } fn get_opts(config: &mut ConfigReader) -> MyOpts { MyOpts { user: Some(config.get_value_or::<String>("MySQL.username", "root".to_string())), pass: Some(config.get_value_or::<String>("MySQL.password", "DidRPwfMySQL".to_string())), db_name: Some("reservat...
MySQL
identifier_name
mysql.rs
//! MySQL Driver implementation use std::path::PathBuf; use mysql::conn::{MyOpts, pool}; use configreader::ConfigReader; #[derive(Clone)] pub struct MySQL { pub pool: pool::MyPool, } fn get_opts(config: &mut ConfigReader) -> MyOpts { MyOpts { user: Some(config.get_value_or::<String>("MySQL.user...
}
{ let opts = get_opts(config); MySQL { pool: pool::MyPool::new(opts).unwrap(), } }
identifier_body
mysql.rs
//! MySQL Driver implementation use std::path::PathBuf; use mysql::conn::{MyOpts, pool}; use configreader::ConfigReader; #[derive(Clone)] pub struct MySQL { pub pool: pool::MyPool,
} fn get_opts(config: &mut ConfigReader) -> MyOpts { MyOpts { user: Some(config.get_value_or::<String>("MySQL.username", "root".to_string())), pass: Some(config.get_value_or::<String>("MySQL.password", "DidRPwfMySQL".to_string())), db_name: Some("reservator".to_string()), tcp_a...
random_line_split
results_model.py
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-...
def delta_values(self): return self.model.delta_values @delta_values.setter def delta_values(self, value): self.model.delta_values = value # --- Events def appWillSavePrefs(self): self.model.columns.save_columns() # --- model --> view def invalidate_markings(self):...
@power_marker.setter def power_marker(self, value): self.model.power_marker = value @property
random_line_split
results_model.py
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-...
elif role == Qt.EditRole: if column.name == "name": return row.data[column.name] return None def _getFlags(self, row, column): flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if column.name == "marked": if row.markable: flags |...
font = QFont(self.view.font()) if self.prefs.reference_bold_font: font.setBold(row.isref) return font
conditional_block
results_model.py
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-...
(self, row, column): flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable if column.name == "marked": if row.markable: flags |= Qt.ItemIsUserCheckable elif column.name == "name": flags |= Qt.ItemIsEditable return flags def _setData(self, row, column...
_getFlags
identifier_name
results_model.py
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2015 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-...
def mouseDoubleClickEvent(self, event): self.doubleClicked.emit(QModelIndex()) # We don't call the superclass' method because the default behavior is to rename the cell. # --- Signals spacePressed = pyqtSignal()
if event.text() == " ": self.spacePressed.emit() return super().keyPressEvent(event)
identifier_body
xpah.py
#!/usr/bin/python import urllib import libxml2 #download VO activation XML url = urllib.urlopen("http://myosg.grid.iu.edu/voactivation/xml?datasource=activation&start_type=7daysago&start_date=10%2F09%2F2009&end_type=now&end_date=10%2F09%2F2009&all_vos=on&active_value=1") vo_activation = url.read() url.close() #downlo...
ctxt_activation = doc_activation.xpathNewContext() doc_summary = libxml2.parseDoc(vo_summary) ctxt_summary = doc_summary.xpathNewContext() #pull whichever the activation section that I am interested in.. vos = ctxt_activation.xpathEval("//VOActivation/Active/VO") #vos = ctxt.xpathEval("//VOActivation/Enabled") #vos = ...
#Parse XMLs doc_activation = libxml2.parseDoc(vo_activation)
random_line_split
xpah.py
#!/usr/bin/python import urllib import libxml2 #download VO activation XML url = urllib.urlopen("http://myosg.grid.iu.edu/voactivation/xml?datasource=activation&start_type=7daysago&start_date=10%2F09%2F2009&end_type=now&end_date=10%2F09%2F2009&all_vos=on&active_value=1") vo_activation = url.read() url.close() #downlo...
print "\t\t\t" + contact.content
conditional_block
version.util.js
extension. If so, the user is * notified. A call to this function starts a process * that will check the status every so often, as defined by the * extension_version_check_interval preference. * @name CROWDLOGGER.version.util.check_for_new_extension_version * @function * * @param {int} initial_timeout The time...
// Check if the pass phrase is set. If not, add a notification for that. if( CROWDLOGGER.preferences.get_char_pref( 'pass_phrase', '' ) === '' ){ CROWDLOGGER.notifications.set_notification( 'set_passphrase' ); } else { // Create a notification about updating settings. ...
{ CROWDLOGGER.notifications.set_notification( 'register' ); }
conditional_block
version.util.js
extension. If so, the user is * notified. A call to this function starts a process * that will check the status every so often, as defined by the * extension_version_check_interval preference. * @name CROWDLOGGER.version.util.check_for_new_extension_version * @function * * @param {int} initial_timeout The time...
* extension. */ CROWDLOGGER.version.util.launch_welcome_page = function() { var browser_name = CROWDLOGGER.version.info.get_browser_name(); var extension_version = CROWDLOGGER.version.info.get_extension_version(); // The page to load.
/** * Opens a new tab with a welcome page for the current version of the
random_line_split
email.example.ts
import { Email } from '../../src/property-decorators'; export class
{ @Email() simpleEmail: string; @Email({ protect: false }) nonProtectedEmail: string; @Email({ throwError: true }) throwableEmail: string; } let exampleClass = new EmailExampleClass(); exampleClass.simpleEmail = 'a@a.com'; console.log('\nAssiging a valid address: ', exampleClass.simpleEmai...
EmailExampleClass
identifier_name
email.example.ts
import { Email } from '../../src/property-decorators';
@Email() simpleEmail: string; @Email({ protect: false }) nonProtectedEmail: string; @Email({ throwError: true }) throwableEmail: string; } let exampleClass = new EmailExampleClass(); exampleClass.simpleEmail = 'a@a.com'; console.log('\nAssiging a valid address: ', exampleClass.simpleEmail); ...
export class EmailExampleClass {
random_line_split
create_terrain.py
, ofs_north, ofs_east): '''add offset in meters to a position''' dlat = int(float(ofs_north) * LOCATION_SCALING_FACTOR_INV) dlng = int((float(ofs_east) * LOCATION_SCALING_FACTOR_INV) / longitude_scale(lat_e7*1.0e-7)) return (int(lat_e7+dlat), int(lon_e7+dlng)) def east_blocks(lat_e7, lon_e7): '''wo...
'''create data file for one degree lat/lon''' lat_int = int(math.floor(lat)) lon_int = int(math.floor((lon))) tiles = {} dfile = DataFile(lat_int, lon_int) print("Creating for %d %d" % (lat_int, lon_int)) total_blocks = east_blocks(lat_int*1e7, lon_int*1e7) * TERRAIN_GRID_BLOCK_SIZE_Y f...
identifier_body
create_terrain.py
, 0, 2*GRID_SPACING*TERRAIN_GRID_BLOCK_SIZE_Y) offset = get_distance_NE_e7(lat_e7, lon_e7, lat2_e7, lon2_e7) return int(offset[1] / (GRID_SPACING*TERRAIN_GRID_BLOCK_SPACING_Y)) def pos_from_file_offset(lat_degrees, lon_degrees, file_offset): '''return a lat/lon in 1e7 format given a file offset''' ref...
(lat_e7, lon_e7) = pos_from_file_offset(lat_int, lon_int, blocknum * IO_BLOCK_SIZE) lat = lat_e7 * 1.0e-7 lon = lon_e7 * 1.0e-7 grid = GridBlock(lat_int, lon_int, lat, lon) if grid.blocknum() != blocknum: continue if not args.force and dfile.check_filled(grid): ...
conditional_block
create_terrain.py
precision float''' return struct.unpack('f', struct.pack('f',f))[0] LOCATION_SCALING_FACTOR = to_float32(0.011131884502145034) LOCATION_SCALING_FACTOR_INV = to_float32(89.83204953368922) def longitude_scale(lat): '''get longitude scale factor''' scale = to_float32(math.cos(to_float32(math.radians(lat))))...
def add_offset(lat_e7, lon_e7, ofs_north, ofs_east): '''add offset in meters to a position''' dlat = int(float(ofs_north) * LOCATION_SCALING_FACTOR_INV) dlng = int((float(ofs_east) * LOCATION_SCALING_FACTOR_INV) / longitude_scale(lat_e7*1.0e-7)) return (int(lat_e7+dlat), int(lon_e7+dlng)) def east_bloc...
random_line_split
create_terrain.py
precision float''' return struct.unpack('f', struct.pack('f',f))[0] LOCATION_SCALING_FACTOR = to_float32(0.011131884502145034) LOCATION_SCALING_FACTOR_INV = to_float32(89.83204953368922) def longitude_scale(lat): '''get longitude scale factor''' scale = to_float32(math.cos(to_float32(math.radians(lat))))...
(lat_degrees, lon_degrees, file_offset): '''return a lat/lon in 1e7 format given a file offset''' ref_lat = int(lat_degrees*10*1000*1000) ref_lon = int(lon_degrees*10*1000*1000) stride = east_blocks(ref_lat, ref_lon) blocks = file_offset // IO_BLOCK_SIZE grid_idx_x = blocks // stride grid_...
pos_from_file_offset
identifier_name
auth.js
import { SIGN_IN, SIGN_IN_SUCCESS, SIGN_IN_ERROR, SIGN_OUT, SIGN_OUT_SUCCESS, USER_LOGGED, USER_UNLOGGED } from '../../constants/action-types'; const INITIAL_STATE = { isUserSignedIn: false, isSignOutInProgress: false, isInProgress: null, hasError: false, errorMessage: '', userIsLogged: null,...
userIsLogged: true, user: { ...action.payload, } }; case USER_UNLOGGED: return { ...state, userIsLogged: false, user: {} }; case SIGN_IN_SUCCESS: return { ...state, isUserSignedIn: true, isInProgress: false...
random_line_split
mti880.py
#! /usr/bin/env python # Copyright (C) 2012 Club Capra - capra.etsmtl.ca # # This file is part of CapraVision. # # CapraVision 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 versio...
else: self.notify_output_observers('0\n') return image def detect_biggest_area(self, gray): cnt, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxarea = 0 maxcnt = None for c in cnt: approx = cv2.app...
hull = cv2.convexHull(c) cv2.drawContours(image, [hull],-1, (255,255,255), -1) self.notify_output_observers(str(self.calc_return_value(area)) + "\n")
conditional_block
mti880.py
#! /usr/bin/env python # Copyright (C) 2012 Club Capra - capra.etsmtl.ca # # This file is part of CapraVision. # # CapraVision 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 versio...
(self, gray): cnt, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maxarea = 0 maxcnt = None for c in cnt: approx = cv2.approxPolyDP(c, 0, False) area = np.abs(cv2.contourArea(c)) if area > maxarea: maxarea = area ...
detect_biggest_area
identifier_name
mti880.py
#! /usr/bin/env python # Copyright (C) 2012 Club Capra - capra.etsmtl.ca # # This file is part of CapraVision. # # CapraVision 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 versio...
def calibrate_normal_hand(self, area): if self._capture_normal_hand: self.accumulate.append(area) if len(self.accumulate) == 10: total = 0 for val in self.accumulate: total += val self._capture_normal_hand = False self.norma...
random_line_split
mti880.py
#! /usr/bin/env python # Copyright (C) 2012 Club Capra - capra.etsmtl.ca # # This file is part of CapraVision. # # CapraVision 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 versio...
def remove_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for obs in self.observers: obs() def execute(self, image): image = cv2.cvtColor(image, cv2.cv.CV_BGR2HSV) h, _, _ = cv2.split(image) ...
self.observers.append(observer)
identifier_body
Point.js
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with th...
return region.contains(this); }, /** * Compare this point with another point when the x and y values of both points are rounded. E.g: * [100.3,199.8] will equals to [100, 200] * @param {Ext.util.Point/Object} p The point to compare with, either an instance * of Ext.util.Point or an...
{ region = Ext.get(region.el || region).getRegion(); }
conditional_block
Point.js
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with th...
* of Ext.util.Point or an object with x and y properties * @return {Boolean} */ roundedEquals: function(p) { return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y)); } }, function() { /** * @method * Alias for {@link #translateBy} * @inhe...
random_line_split