file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
email_test.py
import bountyfunding from bountyfunding.core.const import * from bountyfunding.core.data import clean_database from test import to_object from nose.tools import * USER = "bountyfunding" class Email_Test:
def setup(self): self.app = bountyfunding.app.test_client() clean_database() def test_email(self): eq_(len(self.get_emails()), 0) r = self.app.post('/issues', data=dict(ref=1, status='READY', title='Title', link='/issue/1')) eq_(r.status_code, 200) ...
identifier_body
talk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- DEBUG = True observer = None ser_port = None s = 0 ser = None #-------------------------------------------------------------------- import signal import sys import os def signal_handler(signal, frame): global s, ser print '\nYou pressed Ctrl+C!' ...
pass if tsk.lower() in ['crc']: str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" pass print hex(0x12ef ^ 0xabcd) print hex(int("12ef", 16) ^ in...
cnt_text = cnt_text * 1024 + bin_len dmp_text = False bin_file.close() print "big data length is: " + str(cnt_text) print "" cnt_text = 0
conditional_block
talk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- DEBUG = True observer = None ser_port = None s = 0 ser = None #-------------------------------------------------------------------- import signal import sys import os def signal_handler(signal, frame): global s, ser print '\nYou pressed Ctrl+C!' ...
def swapSerialData(data): l = len(data) #if l > 16: # print "-> " + str(l) + " bytes" #else: # print "-> " + binascii.b2a_hex(data) if len(data) > 0: ser.write(data) n = 0 while n < 1: n = ser.inWaiting() #time.sleep(1) data = ser.read(n) l = len(data) #pr...
res = 0 for i in range(length): res = res + ord(block[i]) #print str(res) return chr(res & int(0xFF))
identifier_body
talk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- DEBUG = True observer = None ser_port = None s = 0 ser = None #-------------------------------------------------------------------- import signal import sys import os def signal_handler(signal, frame): global s, ser print '\nYou pressed Ctrl+C!' ...
serialPost(ser, "A2".decode("hex")) elif s == 5: #if data[l-1] == chr(0x4f): # serialPost(ser, "530000000c".decode("hex")) # -> A2 - read command ACK # 80 01 00 00 - Configuration Register: Hardware Version Register serialPost(ser, "80010000".dec...
# A2 - read from memory
random_line_split
talk.py
#!/usr/bin/env python # -*- coding: utf-8 -*- DEBUG = True observer = None ser_port = None s = 0 ser = None #-------------------------------------------------------------------- import signal import sys import os def signal_handler(signal, frame): global s, ser print '\nYou pressed Ctrl+C!' ...
(str1, str2): return bool(str1) ^ bool(str2) #----- MAIN CODE ------------------------------------------- if __name__=='__main__': from sys import platform as _platform import os if _platform == "linux" or _platform == "linux2": # linux print "it is linux?" from hktool.hotplug ...
logical_xor
identifier_name
execWrapper.test.ts
#! /usr/bin/env jest import { ExecError, execWrapper } from "./execWrapper" describe("execWrapper()", () => { it("should resolve when there is a zero exit code", async () => {
code: 0, stdout: "it works\n", stderr: "", }) }) it("should reject when there is a non-zero exit code", async () => { try { await execWrapper(`echo "begin"; echo "fail" 1>&2; exit 1`, { silent: true, }) } catch ...
const result = await execWrapper(`echo "it works"; exit 0`, { silent: true, }) expect(result).toEqual({
random_line_split
execWrapper.test.ts
#! /usr/bin/env jest import { ExecError, execWrapper } from "./execWrapper" describe("execWrapper()", () => { it("should resolve when there is a zero exit code", async () => { const result = await execWrapper(`echo "it works"; exit 0`, { silent: true, }) expect(result).toEqual(...
} finally { expect.assertions(4) } }) })
{ expect(err.code).toEqual(1) expect(err.stdout).toEqual("begin\n") expect(err.stderr).toEqual("fail\n") }
conditional_block
package.js
// All other packages automatically depend on this one Package.describe({ summary: "Core Meteor environment", version: '1.2.18-beta.5' }); Package.registerBuildPlugin({ name: "basicFileTypes", sources: ['plugin/basic-file-types.js'] }); Npm.depends({ "meteor-deque": "2.1.0" }); Package.onUse(function (api...
});
api.addFiles('debug_test.js', 'client'); api.addFiles('bare_test_setup.js', 'client', {bare: true}); api.addFiles('bare_tests.js', 'client');
random_line_split
Lista.js
$(document).ready(function () { LlenarTabla(); //$(".Agregar").click(function () { // $('#ModalAgregarTipoPregunta').modal('show'); //}); }); function LlenarTabla() { $('#TablaTipoPreguntas').dataTable({ "processing": true, "serverSide": true, "bFilter": false, ...
#TablaTipoPreguntas').on('click', '.Detalle', function () { $('#ModalDetalleTipoPregunta').modal('show'); }); $('#TablaTipoPreguntas').on('click', '.Editar', function () { $('#ModalDetalleTipoPregunta').modal('show'); }); $('#TablaTipoPreguntas').on('click', '.Eliminar', function () { alert("click"); }); ...
var opc = "<button class='btn btn-info btn-xs Detalle' type='button'>Detalles</button> <button class='btn btn-warning btn-xs Editar' type='button'><i class='fa fa-pencil' aria-hidden='true'></i> Editar</button> <button class='btn btn-danger btn-xs eliminar' type='button'> <i class='fa fa-trash-o' aria-hidden='true'><...
identifier_body
Lista.js
$(document).ready(function () { LlenarTabla(); //$(".Agregar").click(function () { // $('#ModalAgregarTipoPregunta').modal('show'); //}); }); function LlenarTabla() { $('#TablaTipoPreguntas').dataTable({ "processing": true, "serverSide": true, "bFilter": false, ...
var opc = "<button class='btn btn-info btn-xs Detalle' type='button'>Detalles</button> <button class='btn btn-warning btn-xs Editar' type='button'><i class='fa fa-pencil' aria-hidden='true'></i> Editar</button> <button class='btn btn-danger btn-xs eliminar' type='button'> <i class='fa fa-trash-o' aria-hidden='true...
nes() {
identifier_name
Lista.js
$(document).ready(function () { LlenarTabla(); //$(".Agregar").click(function () { // $('#ModalAgregarTipoPregunta').modal('show'); //}); }); function LlenarTabla() { $('#TablaTipoPreguntas').dataTable({ "processing": true, "serverSide": true, "bFilter": false, ...
$('#TablaTipoPreguntas').on('click', '.Eliminar', function () { alert("click"); }); //function ActualizaListaPreguntas() { // $('#TbodyPreguntas').empty(); // for (var b = 0; b < Lista_preguntas.length; b++) { // $('#tablaPreguntas').append("<tr><td>" + Lista_preguntas[b].Nombre + "</td><td>" + List...
$('#ModalDetalleTipoPregunta').modal('show'); });
random_line_split
serializers.py
from rest_framework import serializers from csinterop.models import SharingProposal, Folder, User class SharingProposalSerializer(serializers.ModelSerializer): share_id = serializers.RelatedField(source='key') permission = serializers.CharField(source='get_permission', read_only=True) folder_name = serial...
: model = SharingProposal fields = ( 'share_id', 'recipient', 'resource_url', 'owner_name', 'owner_email', 'folder_name', 'permission', 'callback', 'protocol_version', 'status', 'created_at')
Meta
identifier_name
serializers.py
from rest_framework import serializers from csinterop.models import SharingProposal, Folder, User class SharingProposalSerializer(serializers.ModelSerializer): share_id = serializers.RelatedField(source='key') permission = serializers.CharField(source='get_permission', read_only=True) folder_name = serial...
proposal = SharingProposal(**attrs) proposal.key = self.context['request'].DATA['share_id'] owner = User() owner.name = self.context['request'].DATA['owner_name'] owner.email = self.context['request'].DATA['owner_email'] proposal.owner = owner folder = Folder()...
return instance
conditional_block
serializers.py
from rest_framework import serializers from csinterop.models import SharingProposal, Folder, User class SharingProposalSerializer(serializers.ModelSerializer): share_id = serializers.RelatedField(source='key') permission = serializers.CharField(source='get_permission', read_only=True) folder_name = serial...
class Meta: model = SharingProposal fields = ( 'share_id', 'recipient', 'resource_url', 'owner_name', 'owner_email', 'folder_name', 'permission', 'callback', 'protocol_version', 'status', 'created_at')
""" Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. """ if instance is not None: return instance proposal = SharingProposal(**attrs) proposal.key = self.context['request'].DATA['share...
identifier_body
serializers.py
from rest_framework import serializers from csinterop.models import SharingProposal, Folder, User class SharingProposalSerializer(serializers.ModelSerializer): share_id = serializers.RelatedField(source='key') permission = serializers.CharField(source='get_permission', read_only=True) folder_name = serial...
proposal.owner = owner folder = Folder() folder.name = self.context['request'].DATA['folder_name'] proposal.folder = folder write_access = True if self.context['request'].DATA['permission'].lower() is 'read-write' else False proposal.write_access = write_access pr...
owner.email = self.context['request'].DATA['owner_email']
random_line_split
parser.py
# -*- coding:utf-8 -*- from urllib.parse import urlparse from lxml import html from lxml.html.clean import Cleaner from .forms import FormWrapper from .helpers import ( match_form, filter_element ) class HtmlParser: """ Parses response content string to valid html using `lxml.html` """ def
(self, response, session=None, use_cleaner=None, cleaner_params=None): self._html_tree = html.fromstring(response.content) self.links = {} self._forms = [] self._cleaner = Cleaner(**cleaner_params) if use_cleaner else None self._session = session self._url = response.url ...
__init__
identifier_name
parser.py
# -*- coding:utf-8 -*- from urllib.parse import urlparse from lxml import html from lxml.html.clean import Cleaner from .forms import FormWrapper from .helpers import ( match_form, filter_element ) class HtmlParser: """ Parses response content string to valid html using `lxml.html` """ def __i...
def css(self, selector): """Select elements by css selectors""" return self._html_tree.cssselect(selector) if __name__ == '__main__': import doctest doctest.testmod()
"""Select elements using xpath selectors""" return self._html_tree.xpath(path)
identifier_body
parser.py
# -*- coding:utf-8 -*- from urllib.parse import urlparse from lxml import html from lxml.html.clean import Cleaner from .forms import FormWrapper from .helpers import ( match_form, filter_element ) class HtmlParser: """ Parses response content string to valid html using `lxml.html` """ def __i...
return self._forms def xpath(self, path): """Select elements using xpath selectors""" return self._html_tree.xpath(path) def css(self, selector): """Select elements by css selectors""" return self._html_tree.cssselect(selector) if __name__ == '__main__': import d...
wrapped_form = FormWrapper(form, session=self._session, url=self._url) if match_form(wrapped_form, filters): self._forms.append(wrapped_form)
conditional_block
parser.py
# -*- coding:utf-8 -*- from urllib.parse import urlparse from lxml import html from lxml.html.clean import Cleaner from .forms import FormWrapper from .helpers import ( match_form, filter_element ) class HtmlParser: """ Parses response content string to valid html using `lxml.html` """ def __i...
filters=filters, match=match ) if matched: self.links[url] = matched return self.links def find_forms(self, filters=None): """ Find forms and wraps them with class::`<FormWrapper>` object usage:: >>> import re...
tags=tags,
random_line_split
index.ts
import {Bounds, parseBounds, parseDocumentSize} from './css/layout/bounds'; import {COLORS, isTransparent, parseColor} from './css/types/color'; import {CloneConfigurations, CloneOptions, DocumentCloner, WindowOptions} from './dom/document-cloner'; import {isBodyElement, isHTMLElement, parseTree} from './dom/node-parse...
if (!defaultView) { throw new Error(`Document is not attached to a Window`); } const resourceOptions = { allowTaint: opts.allowTaint ?? false, imageTimeout: opts.imageTimeout ?? 15000, proxy: opts.proxy, useCORS: opts.useCORS ?? false }; const contextOptions...
random_line_split
index.ts
import {Bounds, parseBounds, parseDocumentSize} from './css/layout/bounds'; import {COLORS, isTransparent, parseColor} from './css/types/color'; import {CloneConfigurations, CloneOptions, DocumentCloner, WindowOptions} from './dom/document-cloner'; import {isBodyElement, isHTMLElement, parseTree} from './dom/node-parse...
const ownerDocument = element.ownerDocument; if (!ownerDocument) { throw new Error(`Element is not attached to a Document`); } const defaultView = ownerDocument.defaultView; if (!defaultView) { throw new Error(`Document is not attached to a Window`); } const resourceOpti...
{ return Promise.reject('Invalid element provided as first argument'); }
conditional_block
baBackTop.component.ts
import {Component, ViewChild, HostListener, Input, ElementRef} from '@angular/core';
<i #baBackTop class="fa fa-angle-up back-top ba-back-top" title="Back to Top"></i> ` }) export class BaBackTop { @Input() position:number = 400; @Input() showSpeed:number = 500; @Input() moveSpeed:number = 1000; @ViewChild('baBackTop') _selector:ElementRef; ngAfterViewInit () { this._onWindowScro...
@Component({ selector: 'ba-back-top', styleUrls: ['./baBackTop.scss'], template: `
random_line_split
baBackTop.component.ts
import {Component, ViewChild, HostListener, Input, ElementRef} from '@angular/core'; @Component({ selector: 'ba-back-top', styleUrls: ['./baBackTop.scss'], template: ` <i #baBackTop class="fa fa-angle-up back-top ba-back-top" title="Back to Top"></i> ` }) export class BaBackTop { @Input() position:numbe...
():void { let el = this._selector.nativeElement; window.scrollY > this.position ? jQuery(el).fadeIn(this.showSpeed) : jQuery(el).fadeOut(this.showSpeed); } }
_onWindowScroll
identifier_name
replicator.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
def delete_db(self, broker): """ Ensure that reconciler databases are only cleaned up at the end of the replication run. """ if (self.reconciler_cleanups is not None and broker.account == MISPLACED_OBJECTS_ACCOUNT): # this container shouldn't be h...
# replication broker.update_reconciler_sync(max_sync)
random_line_split
replicator.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
return None def get_reconciler_broker(self, timestamp): """ Get a local instance of the reconciler container broker that is appropriate to enqueue the given timestamp. :param timestamp: the timestamp of the row to be enqueued :returns: a local reconciler broker ...
return node
conditional_block
replicator.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
(self): """ Ensure any items merged to reconciler containers during replication are pushed out to correct nodes and any reconciler containers that do not belong on this node are removed. """ self.logger.info('Replicating %d reconciler containers', ...
replicate_reconcilers
identifier_name
replicator.py
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
def find_local_handoff_for_part(self, part): """ Look through devices in the ring for the first handoff device that was identified during job creation as available on this node. :returns: a node entry from the ring """ nodes = self.ring.get_part_nodes(part) ...
parent = super(ContainerReplicator, self) if is_success(response.status): remote_info = json.loads(response.data) if incorrect_policy_index(info, remote_info): status_changed_at = Timestamp(time.time()) broker.set_storage_policy_index( ...
identifier_body
aoj2400.py
while True: t, p, r = map(int, input().split()) if t == 0 and p == 0 and r == 0: break logs = [input().split() for _ in range(r)] score = [[0, 0, -i, [0] * p] for i in range(t)] c_n, pen, w_n = 0, 1, 3 for tid, pid, time, msg in logs: tid, pid, time = int(tid) - 1, int(pid) - 1, int(time...
score[tid][w_n][pid] += 1 elif msg == 'CORRECT': score[tid][c_n] += 1 score[tid][pen] -= (score[tid][w_n][pid] * 1200 + time) score[tid][w_n][pid] = 0 score = sorted(score, reverse=True) for c_n, pen, t, _ in score: print(abs(t) + 1 , c_n, abs(pen)...
random_line_split
aoj2400.py
while True: t, p, r = map(int, input().split()) if t == 0 and p == 0 and r == 0: break logs = [input().split() for _ in range(r)] score = [[0, 0, -i, [0] * p] for i in range(t)] c_n, pen, w_n = 0, 1, 3 for tid, pid, time, msg in logs: tid, pid, time = int(tid) - 1, int(pid) - 1, int(time...
print(abs(t) + 1 , c_n, abs(pen))
conditional_block
variables_9.js
var searchData= [
['statistics_2',['statistics',['../struct_vma_detailed_statistics.html#a13efbdb35bd1291191d275f43e96d360',1,'VmaDetailedStatistics::statistics()'],['../struct_vma_budget.html#a6d15ab3a798fd62d9efa3a1e1f83bf54',1,'VmaBudget::statistics()']]] ];
['size_0',['size',['../struct_vma_allocation_info.html#aac76d113a6a5ccbb09fea00fb25fd18f',1,'VmaAllocationInfo::size()'],['../struct_vma_virtual_block_create_info.html#a670ab8c6a6e822f3c36781d79e8824e9',1,'VmaVirtualBlockCreateInfo::size()'],['../struct_vma_virtual_allocation_create_info.html#aae08752b86817abd0d944c6...
random_line_split
dao.py
''' Created on Aug 29, 2015 @author: kevinchien ''' import datetime # from bson import ObjectId from tornado.gen import Task, Return from tornado.gen import coroutine from src.common.logutil import get_logger # from src.core.mongoutil import get_instance # # @coroutine # def update_auth(auth_info): # new_auth_in...
# result, error = yield Task(get_instance().auth_info.update, criteria, fields) # if error is not None: # raise error # # raise Return(result)
# # fields = {'$set': new_auth_info} #
random_line_split
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
# 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 License for the specific language governing pe...
# with the License. You may obtain a copy of the License at #
random_line_split
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
(): old_max_heap_size = clients.MAX_HEAP_SIZE clients.MAX_HEAP_SIZE = 2 try: log_link1 = "http://test1:8041/container/nonsense" log_link2 = "http://test2:8041/container/nonsense" log_link3 = "http://test3:8041/container/nonsense" c1 = clients.get_log_client(log_link1) c2 = clients.get_log_cli...
test_get_log_client
identifier_name
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
old_max_heap_size = clients.MAX_HEAP_SIZE clients.MAX_HEAP_SIZE = 2 try: log_link1 = "http://test1:8041/container/nonsense" log_link2 = "http://test2:8041/container/nonsense" log_link3 = "http://test3:8041/container/nonsense" c1 = clients.get_log_client(log_link1) c2 = clients.get_log_client(lo...
identifier_body
base_entity_manager.py
from __future__ import absolute_import import momoko from tornado import gen from psycopg2.extras import RealDictConnection def initialize_database(): db = momoko.Pool( dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''', size=5, connection_factory=RealDictConne...
(self, sql): ''' Executes an sql statement and returns the value ''' cursor = yield BaseEntityManager.db.execute(sql) raise gen.Return(cursor) def get_value(self, key): ''' Gets a value given dictionary like arguments''' params = {} if(self.request.method == 'GET'): ...
execute_sql
identifier_name
base_entity_manager.py
from __future__ import absolute_import import momoko from tornado import gen from psycopg2.extras import RealDictConnection def initialize_database(): db = momoko.Pool( dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''', size=5, connection_factory=RealDictConne...
elif(self.request.method == 'DELETE'): params = self.request.body_arguments if(key not in params): return None ''' Params will always be of the form key:[values] ''' return params.get(key)[0]
params = self.request.arguments
conditional_block
base_entity_manager.py
from __future__ import absolute_import import momoko from tornado import gen from psycopg2.extras import RealDictConnection def initialize_database(): db = momoko.Pool( dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''', size=5, connection_factory=RealDictConne...
def __init__(self, request): self.request = request @gen.coroutine def execute_sql(self, sql): ''' Executes an sql statement and returns the value ''' cursor = yield BaseEntityManager.db.execute(sql) raise gen.Return(cursor) def get_value(self, key): ''' Gets a...
random_line_split
base_entity_manager.py
from __future__ import absolute_import import momoko from tornado import gen from psycopg2.extras import RealDictConnection def initialize_database(): db = momoko.Pool( dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''', size=5, connection_factory=RealDictConne...
''' Gets a value given dictionary like arguments''' params = {} if(self.request.method == 'GET'): params = self.request.query_arguments elif(self.request.method == 'POST'): params = self.request.body_arguments elif(self.request.method == 'PUT'): params...
identifier_body
CollapsedBreadcrumbs.js
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Breadcrumbs from '@material-ui/core/Breadcrumbs'; import Typography from '@material-ui/core/Typography'; import Link from '@material-ui/cor...
function handleClick(event) { event.preventDefault(); alert('You clicked a breadcrumb.'); } export default function CollapsedBreadcrumbs() { const classes = useStyles(); return ( <Paper elevation={0} className={classes.paper}> <Breadcrumbs maxItems={2} aria-label="breadcrumb"> <Link color="i...
random_line_split
CollapsedBreadcrumbs.js
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Breadcrumbs from '@material-ui/core/Breadcrumbs'; import Typography from '@material-ui/core/Typography'; import Link from '@material-ui/cor...
export default function CollapsedBreadcrumbs() { const classes = useStyles(); return ( <Paper elevation={0} className={classes.paper}> <Breadcrumbs maxItems={2} aria-label="breadcrumb"> <Link color="inherit" href="#" onClick={handleClick}> Home </Link> <Link color="inh...
{ event.preventDefault(); alert('You clicked a breadcrumb.'); }
identifier_body
CollapsedBreadcrumbs.js
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Breadcrumbs from '@material-ui/core/Breadcrumbs'; import Typography from '@material-ui/core/Typography'; import Link from '@material-ui/cor...
(event) { event.preventDefault(); alert('You clicked a breadcrumb.'); } export default function CollapsedBreadcrumbs() { const classes = useStyles(); return ( <Paper elevation={0} className={classes.paper}> <Breadcrumbs maxItems={2} aria-label="breadcrumb"> <Link color="inherit" href="#" onC...
handleClick
identifier_name
planet.py
import mcpi.minecraft as minecraft import mcpi.block as block import mcpi.minecraftstuff as mcstuff from time import sleep class Planet(): def __init__(self, pos, radius, blockType, blockData = 0): self.mc = minecraft.Minecraft.create() self.pos = pos self.radius = radius ...
def destroy(self, delay): mcDraw = mcstuff.MinecraftDrawing(self.mc) #mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z, # self.radius, block.LAVA_STATIONARY.id) #sleep(delayLava) mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z,...
random_line_split
planet.py
import mcpi.minecraft as minecraft import mcpi.block as block import mcpi.minecraftstuff as mcstuff from time import sleep class Planet(): def __init__(self, pos, radius, blockType, blockData = 0): self.mc = minecraft.Minecraft.create() self.pos = pos self.radius = radius ...
(self, delay): mcDraw = mcstuff.MinecraftDrawing(self.mc) #mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z, # self.radius, block.LAVA_STATIONARY.id) #sleep(delayLava) mcDraw.drawHollowSphere(self.pos.x, self.pos.y, self.pos.z, ...
destroy
identifier_name
planet.py
import mcpi.minecraft as minecraft import mcpi.block as block import mcpi.minecraftstuff as mcstuff from time import sleep class Planet():
def __init__(self, pos, radius, blockType, blockData = 0): self.mc = minecraft.Minecraft.create() self.pos = pos self.radius = radius self.blockType = blockType self.blockData = blockData self._draw() def _draw(self): mcDraw = mcstuff.MinecraftDrawin...
identifier_body
TierSelect.tsx
import BungieImage from 'app/dim-ui/BungieImage'; import { t } from 'app/i18next-t'; import { useD2Definitions } from 'app/manifest/selectors'; import { AppIcon, dragHandleIcon } from 'app/shell/icons'; import { DestinyStatDefinition } from 'bungie-api-ts/destiny2'; import clsx from 'clsx'; import _ from 'lodash'; impo...
) => { const newTiers = { ...stats, [statHash]: { ...stats[statHash], ...changed }, }; onStatFiltersChanged(newTiers); }; const statDefs: { [statHash: number]: DestinyStatDefinition } = {}; for (const statHash of order) { statDefs[statHash] = defs.Stat.get(statHash); } const o...
const defs = useD2Definitions()!; const handleTierChange = ( statHash: number, changed: { min?: number; max?: number; ignored: boolean }
random_line_split
TierSelect.tsx
import BungieImage from 'app/dim-ui/BungieImage'; import { t } from 'app/i18next-t'; import { useD2Definitions } from 'app/manifest/selectors'; import { AppIcon, dragHandleIcon } from 'app/shell/icons'; import { DestinyStatDefinition } from 'bungie-api-ts/destiny2'; import clsx from 'clsx'; import _ from 'lodash'; impo...
const newOrder = reorder(order, result.source.index, result.destination.index); onStatOrderChanged(newOrder); }; return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="droppable"> {(provided) => ( <div ref={provided.innerRef}> {order.map((statHash:...
{ return; }
conditional_block
no071.py
#!/usr/bin/env python # neighbors # a/b < c/d
# for positive integers a,b,c and d with a < b and c < d then a/b and c/d # will be neighbours in the Farey sequence of order max(b,d). # By listing the set of reduced proper fractions for D <= 1,000,000 in # ascending order of size, find the numerator of the fraction immediately # to the left of 3/7. ###############...
# need bc - ad = 1 # The converse is also true. If # bc - ad = 1
random_line_split
no071.py
#!/usr/bin/env python # neighbors # a/b < c/d # need bc - ad = 1 # The converse is also true. If # bc - ad = 1 # for positive integers a,b,c and d with a < b and c < d then a/b and c/d # will be neighbours in the Farey sequence of order max(b,d). # By listing the set of reduced proper fractions for D <= 1,000,000 i...
(verbose=False): D = 10 ** 6 return 3 * int((D - 5) / 7.0) + 2 if __name__ == '__main__': print euler_timer(71)(main)(verbose=True)
main
identifier_name
no071.py
#!/usr/bin/env python # neighbors # a/b < c/d # need bc - ad = 1 # The converse is also true. If # bc - ad = 1 # for positive integers a,b,c and d with a < b and c < d then a/b and c/d # will be neighbours in the Farey sequence of order max(b,d). # By listing the set of reduced proper fractions for D <= 1,000,000 i...
print euler_timer(71)(main)(verbose=True)
conditional_block
no071.py
#!/usr/bin/env python # neighbors # a/b < c/d # need bc - ad = 1 # The converse is also true. If # bc - ad = 1 # for positive integers a,b,c and d with a < b and c < d then a/b and c/d # will be neighbours in the Farey sequence of order max(b,d). # By listing the set of reduced proper fractions for D <= 1,000,000 i...
if __name__ == '__main__': print euler_timer(71)(main)(verbose=True)
D = 10 ** 6 return 3 * int((D - 5) / 7.0) + 2
identifier_body
code_generator.py
# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # #...
(tpl_id, **kwargs): """ Return the template given by tpl_id, parsed through Cheetah """ return str(GRMTemplate(Templates[tpl_id], searchList=kwargs))
get_template
identifier_name
code_generator.py
# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # #...
import Cheetah.Template from util_functions import str_to_fancyc_comment from util_functions import str_to_python_comment from util_functions import strip_default_values from util_functions import strip_arg_types from util_functions import strip_arg_types_grc class GRMTemplate(Cheetah.Template.Template): """ An ex...
# Boston, MA 02110-1301, USA. # """ A code generator (needed by ModToolAdd) """ from templates import Templates
random_line_split
code_generator.py
# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # #...
else: self.include_dir_prefix = searchList['modname'] def get_template(tpl_id, **kwargs): """ Return the template given by tpl_id, parsed through Cheetah """ return str(GRMTemplate(Templates[tpl_id], searchList=kwargs))
self.include_dir_prefix = "gnuradio/" + searchList['modname']
conditional_block
code_generator.py
# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # #...
def get_template(tpl_id, **kwargs): """ Return the template given by tpl_id, parsed through Cheetah """ return str(GRMTemplate(Templates[tpl_id], searchList=kwargs))
""" An extended template class """ def __init__(self, src, searchList): self.grtypelist = { 'sync': 'sync_block', 'sink': 'sync_block', 'source': 'sync_block', 'decimator': 'sync_decimator', 'interpolator': 'sync_interpolator', ...
identifier_body
VideoResultsList.tsx
import * as React from "react"; import SearchRadioButtons from "./SearchRadioButtons"; import VideoLite, { VideoLiteProps } from "./VideoLite"; import VideoPlaceholder from "./VideoPlaceholder"; import VideoResultPreview from "./VideoResultPreview"; import { VideoResultPreviewEventHandlers } from "./VideoResultPreview"...
} render() { const fixedClass = this.state.fixVideo ? "results__push" : ""; return ( <div className="results"> <div className="results__inner-container"> <h1 className="results__heading">Search Results</h1> {this.state.factTurns.length === 0 ? ( <p className="t...
{ this.sortedResults = this.sortResults(nextProps.results); this.fetchFacts(); }
conditional_block
VideoResultsList.tsx
import * as React from "react"; import SearchRadioButtons from "./SearchRadioButtons"; import VideoLite, { VideoLiteProps } from "./VideoLite"; import VideoPlaceholder from "./VideoPlaceholder"; import VideoResultPreview from "./VideoResultPreview"; import { VideoResultPreviewEventHandlers } from "./VideoResultPreview"...
componentWillReceiveProps(nextProps: VideoResultsListProps) { if (!isEqual(this.props.results, nextProps.results)) { this.sortedResults = this.sortResults(nextProps.results); this.fetchFacts(); } } render() { const fixedClass = this.state.fixVideo ? "results__push" : ""; return ( ...
{ this.fetchFacts(); }
identifier_body
VideoResultsList.tsx
import * as React from "react"; import SearchRadioButtons from "./SearchRadioButtons"; import VideoLite, { VideoLiteProps } from "./VideoLite"; import VideoPlaceholder from "./VideoPlaceholder"; import VideoResultPreview from "./VideoResultPreview"; import { VideoResultPreviewEventHandlers } from "./VideoResultPreview"...
() { this.fetchFacts(); } componentWillReceiveProps(nextProps: VideoResultsListProps) { if (!isEqual(this.props.results, nextProps.results)) { this.sortedResults = this.sortResults(nextProps.results); this.fetchFacts(); } } render() { const fixedClass = this.state.fixVideo ? "results...
componentDidMount
identifier_name
VideoResultsList.tsx
import * as React from "react"; import SearchRadioButtons from "./SearchRadioButtons"; import VideoLite, { VideoLiteProps } from "./VideoLite"; import VideoPlaceholder from "./VideoPlaceholder"; import VideoResultPreview from "./VideoResultPreview"; import { VideoResultPreviewEventHandlers } from "./VideoResultPreview"...
return ( <VideoResultPreview key={idx.toString()} eventHandlers={eventHandlers} searchTerm={this.props.searchTerm} sortBy={this.state.selectedOption} turns={videoResult.turns} videoFact={videoResult...
}
random_line_split
customdicts.py
from imbroglio import InnerDict NULL = object() class CustomDict(InnerDict): def __repr__(self): return type(self).__name__ + super().__repr__() def copy(self): return type(self)(*self.items()) class CollisionError(ValueError): def __init__(self, key1, val1, key2, val2): txt = ...
if value not in self.inverse: self.inverse[value] = set() super().__setitem__(item, value) self.inverse[value].add(item) def __delitem__(self, item): value = self[item] self.inverse[value].remove(item) if not self.inverse[value]: del self.inv...
del self.inverse[old_value]
conditional_block
customdicts.py
from imbroglio import InnerDict NULL = object() class CustomDict(InnerDict): def __repr__(self): return type(self).__name__ + super().__repr__() def copy(self): return type(self)(*self.items()) class CollisionError(ValueError): def __init__(self, key1, val1, key2, val2): txt = ...
(self, item, value): if value in self.inverse and self.inverse[value] != item: item_val = self.get(item, NULL) raise CollisionError(item, item_val, self.inverse[value], value) if item in self: del self.inverse[self[item]] super().__setitem__(item, value) ...
__setitem__
identifier_name
customdicts.py
from imbroglio import InnerDict NULL = object() class CustomDict(InnerDict): def __repr__(self): return type(self).__name__ + super().__repr__() def copy(self): return type(self)(*self.items()) class CollisionError(ValueError): def __init__(self, key1, val1, key2, val2): txt = ...
def __delitem__(self, item): value = self[item] self.inverse[value].remove(item) if not self.inverse[value]: del self.inverse[value] super().__delitem__(item)
if item in self: old_value = self[item] self.inverse[old_value].remove(item) if not self.inverse[old_value]: del self.inverse[old_value] if value not in self.inverse: self.inverse[value] = set() super().__setitem__(item, value) self...
identifier_body
customdicts.py
from imbroglio import InnerDict NULL = object() class CustomDict(InnerDict): def __repr__(self): return type(self).__name__ + super().__repr__() def copy(self): return type(self)(*self.items()) class CollisionError(ValueError): def __init__(self, key1, val1, key2, val2): txt = ...
def clear(self): super().clear() self.inverse.clear() def __setitem__(self, item, value): if item in self: old_value = self[item] self.inverse[old_value].remove(item) if not self.inverse[old_value]: del self.inverse[old_value] ...
self.inverse = dict() super().__init__()
random_line_split
plot.ts
/// <reference path='typings/tsd.d.ts' /> 'use strict'; module oribir.plot { var PADDING = { top: 20, right: 30, bottom: 60, left: 80 }; export class Plot { private _parent; private _svg; private _panel; private _panel_background; ...
if (isNaN(width)) return; var panel_width = width - PADDING.left - PADDING.right; var panel_height = parseInt(this._panel.attr('height')); this._panel_background.attr('width', panel_width); this._scale_x.range([0, panel_width]); this._axis_x.call(t...
random_line_split
plot.ts
/// <reference path='typings/tsd.d.ts' /> 'use strict'; module oribir.plot { var PADDING = { top: 20, right: 30, bottom: 60, left: 80 }; export class Plot { private _parent; private _svg; private _panel; private _panel_background; ...
() { var width = parseInt(this._parent.style('width')); if (isNaN(width)) return; var panel_width = width - PADDING.left - PADDING.right; var panel_height = parseInt(this._panel.attr('height')); this._panel_background.attr('width', panel_width); th...
update_width
identifier_name
lib.rs
extern crate anduin; use anduin::logic::{Actable, lcm, Application}; use anduin::backends::vulkan; use anduin::core; use anduin::input::{InputProcessor, Key, InputType, InputEvent}; use anduin::graphics::Drawable; use anduin::audio::{music, sound, PlaybackController}; use anduin::logic::ApplicationListener; use anduin...
/*fn test_input() { match event { winit::Event::Moved(x, y) => { window.set_title(&format!("Window pos: ({:?}, {:?})", x, y)) } winit::Event::Resized(w, h) => { window.set_title(&format!("Window size: ({:?}, {:?})", w, h)) } winit::Event::Closed => { ...
random_line_split
lib.rs
extern crate anduin; use anduin::logic::{Actable, lcm, Application}; use anduin::backends::vulkan; use anduin::core; use anduin::input::{InputProcessor, Key, InputType, InputEvent}; use anduin::graphics::Drawable; use anduin::audio::{music, sound, PlaybackController}; use anduin::logic::ApplicationListener; use anduin...
; impl InputProcessor for InputProcessorStuct { fn process(&self, keyboard_event: InputEvent) { match keyboard_event.event_type { InputType::KeyDown => self.key_down(keyboard_event.key), InputType::KeyUp => self.key_up(keyboard_event.key), _ => (), } } f...
InputProcessorStuct
identifier_name
lib.rs
extern crate anduin; use anduin::logic::{Actable, lcm, Application}; use anduin::backends::vulkan; use anduin::core; use anduin::input::{InputProcessor, Key, InputType, InputEvent}; use anduin::graphics::Drawable; use anduin::audio::{music, sound, PlaybackController}; use anduin::logic::ApplicationListener; use anduin...
fn key_down(&self, key: Key) { println!("Key down {:?}", key) } fn key_up(&self, key: Key) { println!("Key up {:?}", key) } } struct Actor { } struct Image { } struct Control { } impl Actable for Actor { fn update(&self) { println!("Updating self"); } } impl Draw...
{ match keyboard_event.event_type { InputType::KeyDown => self.key_down(keyboard_event.key), InputType::KeyUp => self.key_up(keyboard_event.key), _ => (), } }
identifier_body
email_limit.py
""" Email limiter """ import logging from sqlalchemy import Column, BigInteger, DateTime, func from sqlalchemy.schema import ForeignKey import akiri.framework.sqlalchemy as meta from event_control import EventControl from manager import Manager from system import SystemKeys logger = logging.getLogger() class Email...
self._eventit() # Disable email alerts self.system[SystemKeys.ALERTS_ADMIN_ENABLED] = False self.system[SystemKeys.ALERTS_PUBLISHER_ENABLED] = False self.system[SystemKeys.EMAIL_SPIKE_DISABLED_ALERTS] = True meta.commit() return emails_...
# Don't sent this email alert # send an alert that we're disabling email alerts
random_line_split
email_limit.py
""" Email limiter """ import logging from sqlalchemy import Column, BigInteger, DateTime, func from sqlalchemy.schema import ForeignKey import akiri.framework.sqlalchemy as meta from event_control import EventControl from manager import Manager from system import SystemKeys logger = logging.getLogger() class Email...
(self, eventid): session = meta.Session() entry = EmailLimitEntry(envid=self.envid, eventid=eventid) session.add(entry) session.commit() def _prune(self): """Keep only the the ones in the last email-lookback-minutes period.""" email_lookback_minutes = sel...
_log_email
identifier_name
email_limit.py
""" Email limiter """ import logging from sqlalchemy import Column, BigInteger, DateTime, func from sqlalchemy.schema import ForeignKey import akiri.framework.sqlalchemy as meta from event_control import EventControl from manager import Manager from system import SystemKeys logger = logging.getLogger() class Email...
# Send this email alert return False def _eventit(self): """Send the EMAIL-SPIKE event.""" email_lookback_minutes = self.system[SystemKeys.EMAIL_LOOKBACK_MINUTES] email_max_count = self.system[SystemKeys.EMAIL_MAX_COUNT] data = {'email_lookback_minutes': email_loo...
self._eventit() # Disable email alerts self.system[SystemKeys.ALERTS_ADMIN_ENABLED] = False self.system[SystemKeys.ALERTS_PUBLISHER_ENABLED] = False self.system[SystemKeys.EMAIL_SPIKE_DISABLED_ALERTS] = True meta.commit() return emails_sent_recentl...
conditional_block
email_limit.py
""" Email limiter """ import logging from sqlalchemy import Column, BigInteger, DateTime, func from sqlalchemy.schema import ForeignKey import akiri.framework.sqlalchemy as meta from event_control import EventControl from manager import Manager from system import SystemKeys logger = logging.getLogger() class Email...
def _prune(self): """Keep only the the ones in the last email-lookback-minutes period.""" email_lookback_minutes = self.system[SystemKeys.EMAIL_LOOKBACK_MINUTES] stmt = ("DELETE from email_sent " "where creation_time < NOW() - INTERVAL '%d MINUTES'") % \ ...
session = meta.Session() entry = EmailLimitEntry(envid=self.envid, eventid=eventid) session.add(entry) session.commit()
identifier_body
RequestUtils.js
/* * RequestUtils * Visit http://createjs.com/ for documentation, updates and examples. * * * Copyright (c) 2012 gskinner.com, inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software ...
var query = []; var idx = src.indexOf('?'); if (idx != -1) { var q = src.slice(idx + 1); query = query.concat(q.split('&')); } if (idx != -1) { return src.slice(0, idx) + '?' + this.formatQueryString(data, query); } else { return src + '?' + this.formatQueryString(data, query); } }; /**...
{ return src; }
conditional_block
RequestUtils.js
/* * RequestUtils * Visit http://createjs.com/ for documentation, updates and examples. * * * Copyright (c) 2012 gskinner.com, inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software ...
} return info; }; /** * Formats an object into a query string for either a POST or GET request. * @method formatQueryString * @param {Object} data The data to convert to a query string. * @param {Array} [query] Existing name/value pairs to append on to this query. * @static */ s.formatQueryString = ...
} // Extension if (match = path.match(s.EXTENSION_PATT)) { info.extension = match[1].toLowerCase();
random_line_split
aarch64.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 ...
fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if !arg.layout.is_aggregate() { arg.extend_integer_width_to(32); return; } if let Some(uniform) = is_h...
{ if !ret.layout.is_aggregate() { ret.extend_integer_width_to(32); return; } if let Some(uniform) = is_homogeneous_aggregate(cx, ret) { ret.cast_to(uniform); return; } let size = ret.layout.size; let bits = size.bits(); if bits <= 128 { let unit = if b...
identifier_body
aarch64.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 ...
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { arg.layout.homogeneous_aggregate(cx).and_then(|unit| { let size = arg.layout.size; // Ensure we have at most four uniquely addressable members. if size > unit.size.checked_mul(4, cx).unwrap() { return ...
fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option<Uniform> where Ty: TyLayoutMethods<'a, C> + Copy,
random_line_split
aarch64.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 ...
<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if !fty.ret.is_ignore() { classify_ret_ty(cx, &mut fty.ret); } for arg in &mut fty.args { if arg.is_ignore() { continue; }...
compute_abi_info
identifier_name
categories.component.ts
import {Component, OnInit} from '@angular/core'; import {Category} from './models/category'; import {CategoryService} from './services/category.service'; import {Observable} from 'rxjs/Observable'; @Component({ selector: 'app-categories', template: ` <h3>Categories</h3> <input #searchBox class="search...
(categoryId: number): void { this.categoryService.deleteCategory(categoryId) .subscribe( () => this.loadCategories(), () => this.error = true); } loadCategories(): void { this.categoryService.get() .subscribe(cats => { this._categories = cats; this.search(null); ...
deleteCategory
identifier_name
categories.component.ts
import {Component, OnInit} from '@angular/core'; import {Category} from './models/category'; import {CategoryService} from './services/category.service'; import {Observable} from 'rxjs/Observable'; @Component({ selector: 'app-categories', template: ` <h3>Categories</h3> <input #searchBox class="search...
</table> ` }) export class CategoriesComponent implements OnInit { error = false; categories: Category[]; _categories: Category[]; search(searchTerm: string): void { this.categories = !searchTerm ? this._categories : this._categories.filter(c => c.categoryName.includes(searchTerm)); } con...
random_line_split
categories.component.ts
import {Component, OnInit} from '@angular/core'; import {Category} from './models/category'; import {CategoryService} from './services/category.service'; import {Observable} from 'rxjs/Observable'; @Component({ selector: 'app-categories', template: ` <h3>Categories</h3> <input #searchBox class="search...
constructor(private categoryService: CategoryService) {} deleteCategory(categoryId: number): void { this.categoryService.deleteCategory(categoryId) .subscribe( () => this.loadCategories(), () => this.error = true); } loadCategories(): void { this.categoryService.get() .su...
{ this.categories = !searchTerm ? this._categories : this._categories.filter(c => c.categoryName.includes(searchTerm)); }
identifier_body
test_ptp_clock_cdc_64.py
#!/usr/bin/env python """ Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
raise StopSimulation return instances() def test_bench(): sim = Simulation(bench()) sim.run() if __name__ == '__main__': print("Running test...") test_bench()
random_line_split
test_ptp_clock_cdc_64.py
#!/usr/bin/env python """ Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
(): yield delay(100000) yield clk.posedge rst.next = 1 input_rst.next = 1 output_rst.next = 1 yield clk.posedge yield clk.posedge yield clk.posedge input_rst.next = 0 output_rst.next = 0 yield clk.posedge yield delay(100000)...
check
identifier_name
test_ptp_clock_cdc_64.py
#!/usr/bin/env python """ Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
return instances() def test_bench(): sim = Simulation(bench()) sim.run() if __name__ == '__main__': print("Running test...") test_bench()
yield delay(100000) yield clk.posedge rst.next = 1 input_rst.next = 1 output_rst.next = 1 yield clk.posedge yield clk.posedge yield clk.posedge input_rst.next = 0 output_rst.next = 0 yield clk.posedge yield delay(100000) yie...
identifier_body
test_ptp_clock_cdc_64.py
#!/usr/bin/env python """ Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
input_stop_ts = input_ts/2**16*1e-9 output_stop_ts = output_ts/2**16*1e-9 print(input_stop_ts-output_stop_ts) assert abs(input_stop_ts-output_stop_ts) < 1e-8 yield delay(100000) yield clk.posedge print("test 4: Significantly faster") current_test.nex...
yield clk.posedge
conditional_block
http.py
# Copyright 2015 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 ag...
@property def method(self): return 'Insert' @property def resource_type(self): return 'healthChecks' def CreateRequests(self, args): """Returns the request necessary for adding the health check.""" health_check_ref = self.CreateGlobalReference( args.name, resource_type='healthChec...
return self.compute.healthChecks
identifier_body
http.py
# Copyright 2015 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 ag...
"""Create a HTTP health check to monitor load balanced instances.""" @staticmethod def Args(parser): health_checks_utils.AddHttpRelatedCreationArgs(parser) health_checks_utils.AddProtocolAgnosticCreationArgs(parser, 'HTTP') @property def service(self): return self.compute.healthChecks @proper...
random_line_split
http.py
# Copyright 2015 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 ag...
(Create): """Create a HTTP health check to monitor load balanced instances.""" @staticmethod def Args(parser): Create.Args(parser) health_checks_utils.AddHttpRelatedResponseArg(parser) def CreateRequests(self, args): """Returns the request necessary for adding the health check.""" requests = ...
CreateAlpha
identifier_name
debuggerTable.tsx
import * as React from "react"; export interface DebuggerTableProps { header: string; frozen?: boolean; } export class DebuggerTable extends React.Component<DebuggerTableProps> {
() { return <div className="ui varExplorer"> <div className="ui variableTableHeader"> {this.props.header} </div> <div className={`ui segment debugvariables ${this.props.frozen ? "frozen" : ""} ui collapsing basic striped table`}> {this.props.ch...
render
identifier_name
debuggerTable.tsx
import * as React from "react"; export interface DebuggerTableProps { header: string; frozen?: boolean; } export class DebuggerTable extends React.Component<DebuggerTableProps> { render() { return <div className="ui varExplorer"> <div className="ui variableTableHeader"> ...
onClick={this.props.onClick ? this.clickHandler : undefined}> <div className="variableAndValue"> <div className={`variable varname ${this.props.leftClass || ""}`} title={this.props.leftTitle} style={this.props.depth ? { marginLeft: (this.props.depth * 0.75) + "em" } : undefined}> ...
{ return <div role="listitem" className={`item ${this.props.rowClass || ""}`}
identifier_body
debuggerTable.tsx
import * as React from "react"; export interface DebuggerTableProps { header: string; frozen?: boolean; } export class DebuggerTable extends React.Component<DebuggerTableProps> { render() { return <div className="ui varExplorer"> <div className="ui variableTableHeader"> ...
}
random_line_split
query.service.ts
import { Injectable } from '@angular/core'; import {Query} from './model/query'; import {QueryCategory} from './model/query-category'; import {QueryPart} from './model/query-part'; @Injectable() export class QueryService { // String to separate category-names an the values private categoryValueSeparator = ': '; ...
} // Trim the query an add a whitespace only if the query is not empty newQuery = newQuery.trim(); newQuery += newQuery.length > 0 ? ' ' : ''; const value = appendPart.value.indexOf(' ') === -1 ? appendPart.value : '"' + appendPart.value + '"'; // Now that the current query is cleaned up, th...
{ // Remove the beginning of the category-name if it was typed const categoryName = appendPart.category.name; for (let i = categoryName.length; i > 0 ; i--) { if (newQuery.toLowerCase().endsWith(categoryName.toLowerCase().substr(0, i))) { newQuery = newQuery.slice(0, -i); ...
conditional_block
query.service.ts
import { Injectable } from '@angular/core'; import {Query} from './model/query'; import {QueryCategory} from './model/query-category'; import {QueryPart} from './model/query-part'; @Injectable() export class QueryService { // String to separate category-names an the values private categoryValueSeparator = ': '; ...
/** * Appends the provided query-part to the query-string and returns the combined query-string. * * @param categories * @param queryString * @param appendPart */ public appendQueryPartToQueryString(categories: Array<QueryCategory>, queryString: string, appendPart: QueryPart) { let lastPart:...
{ const lastPartRegexString = '([^\\s"\']*|("([^"]*)")|(\'([^\']*)\'))$'; // Try to match categories or the default category for (const category of categories.concat([null])) { const categoryPart = category ? category.name + this.categoryValueSeparator.trim() + '\\s*' : ''; const regexStr = c...
identifier_body
query.service.ts
import { Injectable } from '@angular/core'; import {Query} from './model/query'; import {QueryCategory} from './model/query-category'; import {QueryPart} from './model/query-part'; @Injectable() export class
{ // String to separate category-names an the values private categoryValueSeparator = ': '; /** * Creates a query-object from a query-string. The string can have the following syntax: * <CategoryName1>: <Value1> <CategoryName2>: <Value2> * * If the query-string starts with a string that is not in t...
QueryService
identifier_name
query.service.ts
import { Injectable } from '@angular/core'; import {Query} from './model/query'; import {QueryCategory} from './model/query-category'; import {QueryPart} from './model/query-part'; @Injectable() export class QueryService { // String to separate category-names an the values private categoryValueSeparator = ': '; ...
if (lastPart === null) { if (remainingQueryString.length > 0) { queryParts.unshift(new QueryPart(null, remainingQueryString)); } break; } queryParts.unshift(lastPart); } return new Query(queryParts); } /** * Extracts the last query-part and returns ...
while (true) { let lastPart: QueryPart; [lastPart, remainingQueryString] = this.popLastQueryPartFromString(categories, remainingQueryString);
random_line_split
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
rans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v...
t(l.t
identifier_name
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $t...
s(self, ctxt: &Context) -> Self { self.into
identifier_body
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to repla...
use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self ...
} impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self {
random_line_split
shared.js
"use strict";; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = __importDefault(require("./types")); function default_1(fork) { var types = fork.use(...
; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. var defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array ...
{ return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); }
identifier_body
shared.js
"use strict";; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = __importDefault(require("./types")); function default_1(fork) { var types = fork.use(...
return true; }, naiveIsPrimitive.toString()); return { geq: geq, defaults: defaults, isPrimitive: isPrimitive, }; } exports.default = default_1; module.exports = exports["default"];
{ return false; }
conditional_block
shared.js
"use strict";; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = __importDefault(require("./types")); function default_1(fork) { var types = fork.use(...
}, naiveIsPrimitive.toString()); return { geq: geq, defaults: defaults, isPrimitive: isPrimitive, }; } exports.default = default_1; module.exports = exports["default"];
if (type === "object" || type === "function") { return false; } return true;
random_line_split
shared.js
"use strict";; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var types_1 = __importDefault(require("./types")); function default_1(fork) { var types = fork.use(...
(than) { return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); } ; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. var defaults = { // Functions were used beca...
geq
identifier_name