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
events.ts
import { Table, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from 'typeorm'; import NotificationRead from './notification'; export enum EventType { WORK_CREATED, PROFILE_CREATED, TITLE_ASSIGNED, TITLE_REVOKED, LICENSE_OFFERED, LICENSE_BOUGHT, LICENSE_SOLD, SELF_LICENSE, WORK_MODIFIED, WOR...
{ @PrimaryGeneratedColumn() id: string @Column() type: EventType @Column() timestamp: number @Column({ nullable: true }) claimReference: string @Column({ nullable: true }) workId?: string @Column({ nullable: true }) workDisplayName?: string @Column({ nullable: true }) actorId?: strin...
Event
identifier_name
cms_form.py
############################################################################## # # Copyright (C) 2019-2020 Compassion CH (http://www.compassion.ch) # @author: Christopher Meier <dev@c-meier.ch> # # The licence is in the file __manifest__.py # ####################################################################...
@http.route() def cms_form(self, model, model_id=None, **kw): return http.request.render("website.404") class UnwantedCMSWizardFormController(CMSWizardFormController): @http.route() def cms_wiz(self, wiz_model, model_id=None, **kw): return http.request.render("website.404") class Unw...
class UwantedCMSFormController(CMSFormController):
random_line_split
cms_form.py
############################################################################## # # Copyright (C) 2019-2020 Compassion CH (http://www.compassion.ch) # @author: Christopher Meier <dev@c-meier.ch> # # The licence is in the file __manifest__.py # ####################################################################...
class UnwantedCMSWizardFormController(CMSWizardFormController): @http.route() def cms_wiz(self, wiz_model, model_id=None, **kw): return http.request.render("website.404") class UnwantedCMSSearchFormController(CMSSearchFormController): @http.route() def cms_form(self, model, **kw): r...
@http.route() def cms_form(self, model, model_id=None, **kw): return http.request.render("website.404")
identifier_body
cms_form.py
############################################################################## # # Copyright (C) 2019-2020 Compassion CH (http://www.compassion.ch) # @author: Christopher Meier <dev@c-meier.ch> # # The licence is in the file __manifest__.py # ####################################################################...
(CMSSearchFormController): @http.route() def cms_form(self, model, **kw): return http.request.render("website.404")
UnwantedCMSSearchFormController
identifier_name
encryption.rs
mod builder_key; mod message; mod origin_key; mod service_key; mod user_key; pub use builder_key::{generate_builder_encryption_key, BuilderSecretEncryptionKey, BUILDER_KEY_NAME}; pub use message::{AnonymousBox,
OriginPublicEncryptionKey, OriginSecretEncryptionKey}; pub use service_key::{generate_service_encryption_key_pair, ServicePublicEncryptionKey, ServiceSecretEncryptionKey}; pub use user_key::{generate_user_encryption_key_pair, ...
SignedBox}; pub use origin_key::{generate_origin_encryption_key_pair,
random_line_split
concatMap.d.ts
import { Observable, ObservableInput } from '../Observable'; /** * Projects each source value to an Observable which is merged in the output * Observable, in a serialized fashion waiting for each one to complete before * merging the next. * * <span class="informal">Maps each value to an Observable, then flattens a...
* Observable. * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector] * A function to produce the value on the output Observable based on the values * and the indices of the source (outer) emission and the inner Observable * emission. The arguments passed to ...
* @see {@link mergeMap} * @see {@link switchMap} * * @param {function(value: T, ?index: number): Observable} project A function * that, when applied to an item emitted by the source Observable, returns an
random_line_split
aff_validator.py
# coding: utf-8 import os from difflib import SequenceMatcher from unicodedata import normalize def remove_diacritics(s): try: s = normalize('NFKD', s) except TypeError: s = normalize('NFKD', unicode(s, "utf-8")) finally: return s.encode('ASCII', 'ignore').decode('ASCII') def rem...
STATES = States() def has_conflicts(original_aff, normaff): if original_aff: conflicts = [] for label in ["country_iso_3166", "state", "city"]: original = original_aff.get(label) normalized = normaff.get(label) if original and normalized: stat...
iginal = normalize_value(original) normalized = normalize_value(normalized) if original == normalized: return True if similarity_ratio(original, normalized) > 0.8: return True if states and hasattr(states, 'normalize'): original = states.normalize(original) normalized =...
identifier_body
aff_validator.py
# coding: utf-8 import os from difflib import SequenceMatcher from unicodedata import normalize def remove_diacritics(s): try: s = normalize('NFKD', s) except TypeError: s = normalize('NFKD', unicode(s, "utf-8")) finally: return s.encode('ASCII', 'ignore').decode('ASCII') def rem...
def __init__(self): self._states = {} self.load() def load(self): with open(os.path.dirname(os.path.realpath(__file__)) + "/assets/states_abbrev.csv") as fp: for row in fp.readlines(): row = row.strip() if "," in row: name,...
class States:
random_line_split
aff_validator.py
# coding: utf-8 import os from difflib import SequenceMatcher from unicodedata import normalize def remove_diacritics(s): try: s = normalize('NFKD', s) except TypeError: s = normalize('NFKD', unicode(s, "utf-8")) finally: return s.encode('ASCII', 'ignore').decode('ASCII') def rem...
riginal_aff, normaff): if original_aff: conflicts = [] for label in ["country_iso_3166", "state", "city"]: original = original_aff.get(label) normalized = normaff.get(label) if original and normalized: states = STATES if label == "state" else Non...
s_conflicts(o
identifier_name
aff_validator.py
# coding: utf-8 import os from difflib import SequenceMatcher from unicodedata import normalize def remove_diacritics(s): try: s = normalize('NFKD', s) except TypeError: s = normalize('NFKD', unicode(s, "utf-8")) finally: return s.encode('ASCII', 'ignore').decode('ASCII') def rem...
return conflicts
iginal = original_aff.get(label) normalized = normaff.get(label) if original and normalized: states = STATES if label == "state" else None if is_a_match(original, normalized, states): continue conflicts.append((label, original...
conditional_block
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
return u'%s' % th[5].find('a').text def iter_results(self, product=None): price = None product.name = self.get_product_name() for tr in self.document.getroot().cssselect('table#tab_resultat tr'): tds = self.parser.select(tr, 'td') if tds and len(tds) == 9...
th = self.document.getroot().cssselect('table#tab_resultat tr th') if th and len(th) == 9:
random_line_split
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
f get_info(self): return self.parser.tostring(self.parser.select(self.document.getroot(), 'div.infos', 1))
identifier_body
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
age): def get_info(self): return self.parser.tostring(self.parser.select(self.document.getroot(), 'div.infos', 1))
opInfoPage(P
identifier_name
pages.py
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
class ShopInfoPage(Page): def get_info(self): return self.parser.tostring(self.parser.select(self.document.getroot(), 'div.infos', 1))
price = Price('%s.%s' % (product.id, tr.attrib['id'])) price.product = product price.cost = Decimal(tds[5].text.replace(',', '.')) price.currency = u'€' shop = Shop(price.id) shop.name = unicode(tds[3].text.strip()) shop....
conditional_block
a04485.js
var a04485 = [
[ "Backward", "a04485.html#a2ded8b7c997ed868a02df44445701712", null ], [ "DeSerialize", "a04485.html#a2ab11ec1c218c57b43a825f6657597b9", null ], [ "Forward", "a04485.html#ae955c429d72219f43a4f0596df809179", null ], [ "Serialize", "a04485.html#afa04786afd07e333635f7c77ea43de91", null ], [ "spec", "a0...
[ "Convolve", "a04485.html#a43dc5a3ee340111a240b29c201291351", null ], [ "~Convolve", "a04485.html#afe4bdcfc64bd500237175b1d30f3bdfb", null ],
random_line_split
commentd.py
#!/usr/bin/env python from builtins import zip, map import struct import collections import sys import logging import os from gevent import monkey; monkey.patch_all() import gevent import gevent.server import leveldb # Ref: ../../include/pttstruct.h IDLEN = 12 FNLEN = 28 COMMENTLEN = 80 # Ref: ../../include/daemon...
def open_database(db_path): global g_db class LevelDBWrapper(object): def __init__(self, db): self.db = db def get(self, key): try: return self.db.Get(key) except KeyError: return None def set(self, key, value): ...
key = i[0] #if '#' in key: # continue logging.info(' %s', key)
conditional_block
commentd.py
#!/usr/bin/env python from builtins import zip, map import struct import collections import sys import logging import os from gevent import monkey; monkey.patch_all() import gevent import gevent.server import leveldb # Ref: ../../include/pttstruct.h IDLEN = 12 FNLEN = 28 COMMENTLEN = 80 # Ref: ../../include/daemon...
def get(self, key): try: return self.db.Get(key) except KeyError: return None def set(self, key, value): self.db.Put(key, value) def RangeIter(self, **args): return self.db.RangeIter(*args) g_db = LevelDBWra...
self.db = db
identifier_body
commentd.py
#!/usr/bin/env python from builtins import zip, map import struct import collections import sys import logging import os from gevent import monkey; monkey.patch_all() import gevent import gevent.server import leveldb # Ref: ../../include/pttstruct.h IDLEN = 12 FNLEN = 28 COMMENTLEN = 80 # Ref: ../../include/daemon...
fd.write(struct.pack('I', num)) logging.debug('response: %d', num) elif req.operation == REQ_QUERY_BODY: blob = fd.read(struct.calcsize(QueryFormatString)) comment = LoadComment(UnpackQuery(blob)) logging.debug('Got comment %r', comment) if...
blob = fd.read(struct.calcsize(QueryFormatString)) num = LoadCommentCount(UnpackQuery(blob))
random_line_split
commentd.py
#!/usr/bin/env python from builtins import zip, map import struct import collections import sys import logging import os from gevent import monkey; monkey.patch_all() import gevent import gevent.server import leveldb # Ref: ../../include/pttstruct.h IDLEN = 12 FNLEN = 28 COMMENTLEN = 80 # Ref: ../../include/daemon...
(db_path): global g_db class LevelDBWrapper(object): def __init__(self, db): self.db = db def get(self, key): try: return self.db.Get(key) except KeyError: return None def set(self, key, value): self.db.Pu...
open_database
identifier_name
test_threading.py
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else: numThreads = 5 if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def Run(threadNum):
cx_Logging.StartLogging("test_threading.log", level = cx_Logging.DEBUG, maxFiles = 10, maxFileSize = 5 * 1024 * 1024, prefix = "[%i] %t") cx_Logging.Debug("Testing logging with %s threads.", numThreads) threads = [] for i in range(numThreads): thread = threading.Thread(target = Run, args = (i + 1,)) t...
cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLeft = numIterations while iterationsLeft > 0: numFiles = len(os.listdir(".")) cx_Logging.Debug("Thread-%d: counted %d files, %d iterations left", threadNum, numFiles, iterationsLeft) iterationsLeft -= 1
identifier_body
test_threading.py
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else: numThreads = 5 if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def
(threadNum): cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLeft = numIterations while iterationsLeft > 0: numFiles = len(os.listdir(".")) cx_Logging.Debug("Thread-%d: counted %d files, %d iterations left", threadNum, numFiles, iterationsLeft) iterations...
Run
identifier_name
test_threading.py
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else: numThreads = 5 if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def Run(threadNum): cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLe...
for thread in threads: thread.join()
random_line_split
test_threading.py
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else:
if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def Run(threadNum): cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLeft = numIterations while iterationsLeft > 0: numFiles = len(os.listdir(".")) cx_Logging.Debug("Thread-%d: counted %d ...
numThreads = 5
conditional_block
test_build_scripts.py
"""Tests for distutils.command.build_scripts.""" import os import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest class BuildScriptsTestCase(suppor...
if __name__ == "__main__": run_unittest(test_suite())
return unittest.makeSuite(BuildScriptsTestCase)
identifier_body
test_build_scripts.py
"""Tests for distutils.command.build_scripts.""" import os import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest class BuildScriptsTestCase(suppor...
(self, dir, name, text): f = open(os.path.join(dir, name), "w") try: f.write(text) finally: f.close() def test_version_int(self): source = self.mkdtemp() target = self.mkdtemp() expected = self.write_sample_scripts(source) ...
write_script
identifier_name
test_build_scripts.py
"""Tests for distutils.command.build_scripts.""" import os import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest
class BuildScriptsTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_default_settings(self): cmd = self.get_build_scripts_cmd("/foo/bar", []) self.assertTrue(not cmd.force) self.assertTrue(cmd.b...
random_line_split
test_build_scripts.py
"""Tests for distutils.command.build_scripts.""" import os import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest class BuildScriptsTestCase(suppor...
built = os.listdir(target) for name in expected: self.assertTrue(name in built) def test_suite(): return unittest.makeSuite(BuildScriptsTestCase) if __name__ == "__main__": run_unittest(test_suite())
sysconfig._CONFIG_VARS['VERSION'] = old
conditional_block
jquery.elastic.min.js
/** * @name Elastic * @descripton Elastic is jQuery plugin that grow and shrink your textareas automatically * @version 1.6.11 * @requires jQuery 1.2.6+ * * @author Jan Jarfalk * @author-email jan.jarfalk@unwrongest.com * @author-website http://www.unwrongest.com * * @licenc...
(height,overflow){curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow});}} function update(){var textareaContent=$textarea.val().replace(/&/g,'&amp;').replace(/ /g,'&nbsp;').replace(/<|>/g,'&gt;').replace(/\n/g,'<br />')...
setHeightAndOverflow
identifier_name
jquery.elastic.min.js
/** * @name Elastic * @descripton Elastic is jQuery plugin that grow and shrink your textareas automatically * @version 1.6.11 * @requires jQuery 1.2.6+ * * @author Jan Jarfalk * @author-email jan.jarfalk@unwrongest.com * @author-website http://www.unwrongest.com * * @licenc...
function update(){var textareaContent=$textarea.val().replace(/&/g,'&amp;').replace(/ /g,'&nbsp;').replace(/<|>/g,'&gt;').replace(/\n/g,'<br />');var twinContent=$twin.html();if(textareaContent+'&nbsp;'!=twinContent){$twin.html(textareaContent+'&nbsp;');if(Math.abs($twin.height()+lineHeight-$textarea.height())>3){va...
{curratedHeight=Math.floor(parseInt(height,10));if($textarea.height()!=curratedHeight){$textarea.css({'height':curratedHeight+'px','overflow':overflow});}}
identifier_body
jquery.elastic.min.js
/** * @name Elastic * @descripton Elastic is jQuery plugin that grow and shrink your textareas automatically * @version 1.6.11 * @requires jQuery 1.2.6+ * * @author Jan Jarfalk * @author-email jan.jarfalk@unwrongest.com * @author-website http://www.unwrongest.com * * @licenc...
}} $textarea.css({'overflow':'hidden'});$textarea.keyup(function(){update();});$textarea.live('input paste',function(e){setTimeout(update,250);});update();});}});})(jQuery);
{var goalheight=$twin.height()+lineHeight;if(goalheight>=maxheight){setHeightAndOverflow(maxheight,'auto');}else if(goalheight<=minheight){setHeightAndOverflow(minheight,'hidden');}else{setHeightAndOverflow(goalheight,'hidden');}}
conditional_block
jquery.elastic.min.js
/** * @name Elastic * @descripton Elastic is jQuery plugin that grow and shrink your textareas automatically * @version 1.6.11 * @requires jQuery 1.2.6+
* @author-website http://www.unwrongest.com * * @licence MIT License - http://www.opensource.org/licenses/mit-license.php */ (function(jQuery){jQuery.fn.extend({elastic:function(){var mimics=['paddingTop','paddingRight','paddingBottom','paddingLeft','fontSize','lineHeight','fontFamily','width','fontWeight'...
* * @author Jan Jarfalk * @author-email jan.jarfalk@unwrongest.com
random_line_split
variational_autoencoder_deconv.py
'''This script demonstrates how to build a variational autoencoder with Keras and deconvolution layers. Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114 ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatte...
decoder_deconv_3_upsamp = Conv2DTranspose(filters, kernel_size=(3, 3), strides=(2, 2), padding='valid', activation='relu') decoder_mean_squash = Conv2D...
output_shape = (batch_size, 29, 29, filters)
conditional_block
variational_autoencoder_deconv.py
'''This script demonstrates how to build a variational autoencoder with Keras and deconvolution layers. Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114 ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatte...
def vae_loss(self, x, x_decoded_mean_squash): x = K.flatten(x) x_decoded_mean_squash = K.flatten(x_decoded_mean_squash) xent_loss = img_rows * img_cols * metrics.binary_crossentropy(x, x_decoded_mean_squash) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_va...
self.is_placeholder = True super(CustomVariationalLayer, self).__init__(**kwargs)
identifier_body
variational_autoencoder_deconv.py
'''This script demonstrates how to build a variational autoencoder with Keras and deconvolution layers. Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114 ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatte...
original_img_size = (img_chns, img_rows, img_cols) else: original_img_size = (img_rows, img_cols, img_chns) latent_dim = 2 intermediate_dim = 128 epsilon_std = 1.0 epochs = 5 x = Input(batch_shape=(batch_size,) + original_img_size) conv_1 = Conv2D(img_chns, kernel_size=(2, 2), p...
if K.image_data_format() == 'channels_first':
random_line_split
variational_autoencoder_deconv.py
'''This script demonstrates how to build a variational autoencoder with Keras and deconvolution layers. Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114 ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatte...
(self, x, x_decoded_mean_squash): x = K.flatten(x) x_decoded_mean_squash = K.flatten(x_decoded_mean_squash) xent_loss = img_rows * img_cols * metrics.binary_crossentropy(x, x_decoded_mean_squash) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) ...
vae_loss
identifier_name
size_of.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use script::test::size_of; // Macro so that we can stringify type names // I'd really prefer the tests themselve...
let new = size_of::$t(); let old = $known_size; if new < old { panic!("Your changes have decreased the stack size of commonly used DOM struct {} from {} to {}. \ Good work! Please update the size in tests/unit/script/size_of.rs.", ...
($testname: ident, $t: ident, $known_size: expr) => ( #[test] fn $testname() {
random_line_split
util.ts
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors ma...
( memcached: Memcached, key: string, value: string|Buffer|Promise<string|Buffer>|any, lifetime?: number): Promise<void> { await new Promise(async(resolve, reject) => { try { let v = await value; if (Buffer.isBuffer(v)) { v = v.toString('utf8'); } ...
save
identifier_name
util.ts
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors ma...
else { resolve(); } }); }); } static get(memcached: Memcached, key: string): Promise<any> { return new Promise((resolve, reject) => { const start = +new Date(); memcached.get(key, (err, data) => { if (err) { reject(err); } else { cons...
{ reject(err); }
conditional_block
util.ts
/**
* The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://poly...
* @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt
random_line_split
archive_link.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from flask i...
(Resource): endpoint_name = 'archive_link' resource_title = endpoint_name schema = { 'link_id': Resource.rel('archive', embeddable=False, type='string'), 'desk': Resource.rel('desks', embeddable=False) } url = 'archive/<{0}:target_id>/link'.format(item_url) resource_methods = ...
ArchiveLinkResource
identifier_name
archive_link.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from flask i...
Validates the article to be linked :param target: article to be linked :param target_id: id of the article to be linked :raises: SuperdeskApiError """ if not target: raise SuperdeskApiError.notFoundError(message='Cannot find the target item with id {}.'.format...
"""
random_line_split
archive_link.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from flask i...
if get_resource_service('published').is_rewritten_before(target['_id']): raise SuperdeskApiError.badRequestError(message='Article has been rewritten before !')
raise SuperdeskApiError.badRequestError("Takes can't be created for an Item having Embargo")
conditional_block
archive_link.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from flask i...
""" Validates the article to be linked :param target: article to be linked :param target_id: id of the article to be linked :raises: SuperdeskApiError """ if not target: raise SuperdeskApiError.notFoundError(message='Cannot find the target item with id {}.'.fo...
identifier_body
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn new_from_file(p: Path) -> IoResult<Lexer<File>> { Ok(Lexer::new_from_reader(try!(File::open(&p)))) } pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>> { Lexer::new_from_reader(BufReader::new(s.as_bytes())) } } fn main() {}
{ Lexer{reader: BufferedReader::new(r)}
random_line_split
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>> { Lexer::new_from_reader(BufReader::new(s.as_bytes())) } } fn main() {}
{ Ok(Lexer::new_from_reader(try!(File::open(&p)))) }
identifier_body
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(r: R) -> Lexer<R> { Lexer{reader: BufferedReader::new(r)} } pub fn new_from_file(p: Path) -> IoResult<Lexer<File>> { Ok(Lexer::new_from_reader(try!(File::open(&p)))) } pub fn new_from_str<'a>(s: &'a str) -> Lexer<BufReader<'a>> { Lexer::new_from_reader(BufReader::n...
new_from_reader
identifier_name
package_helper.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
(mod_name): try: from importlib import import_module return import_module(mod_name) except Exception as e: system_log.error("*" * 30) system_log.error("Mod Import Error: {}, error: {}", mod_name, e) system_log.error("*" * 30) raise
import_mod
identifier_name
package_helper.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0
# See the License for the specific language governing permissions and # limitations under the License. from rqalpha.utils.logger import system_log def import_mod(mod_name): try: from importlib import import_module return import_module(mod_name) except Exception as e: system_log.error(...
# # 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.
random_line_split
package_helper.py
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
try: from importlib import import_module return import_module(mod_name) except Exception as e: system_log.error("*" * 30) system_log.error("Mod Import Error: {}, error: {}", mod_name, e) system_log.error("*" * 30) raise
identifier_body
day22.rs
extern crate dotenv; extern crate lettre; extern crate uuid; use std::env; use lettre::email::{EmailBuilder, SendableEmail}; use lettre::transport::EmailTransport; use lettre::transport::smtp; struct
{ contents: String, recipient: String, } impl SendableEmail for Report { fn from_address(&self) -> String { "complicated.report.system@gmail.com".to_string() } fn to_addresses(&self) -> Vec<String> { vec![self.recipient.clone()] } fn message(&self) -> String { for...
Report
identifier_name
day22.rs
extern crate dotenv; extern crate lettre; extern crate uuid; use std::env; use lettre::email::{EmailBuilder, SendableEmail}; use lettre::transport::EmailTransport; use lettre::transport::smtp;
contents: String, recipient: String, } impl SendableEmail for Report { fn from_address(&self) -> String { "complicated.report.system@gmail.com".to_string() } fn to_addresses(&self) -> Vec<String> { vec![self.recipient.clone()] } fn message(&self) -> String { format...
struct Report {
random_line_split
mergesort.rs
// Author : Thomas Minier // Apply Merge sort on two slices fn merge(left : &[i32], right : &[i32]) -> Vec<i32> { let mut res = vec!(); let (mut left_set, mut right_set) = (left, right); while (!left_set.is_empty()) && (!right_set.is_empty()) { let (left_head, left_tail) = left_set.split_first().un...
(list : &[i32]) -> Vec<i32> { if list.len() <= 1 { return list.to_vec(); } let (left, right) = list.split_at(list.len() / 2); return merge(&merge_sort(left), &merge_sort(right)); } #[test] fn test_merge_sort() { let v = vec!(5,1,4,3,2,6); let w = merge_sort(&v); assert_eq!(vec!(1,2,...
merge_sort
identifier_name
mergesort.rs
// Author : Thomas Minier // Apply Merge sort on two slices fn merge(left : &[i32], right : &[i32]) -> Vec<i32> { let mut res = vec!(); let (mut left_set, mut right_set) = (left, right); while (!left_set.is_empty()) && (!right_set.is_empty()) { let (left_head, left_tail) = left_set.split_first().un...
let (left, right) = list.split_at(list.len() / 2); return merge(&merge_sort(left), &merge_sort(right)); } #[test] fn test_merge_sort() { let v = vec!(5,1,4,3,2,6); let w = merge_sort(&v); assert_eq!(vec!(1,2,3,4,5,6), w); }
{ return list.to_vec(); }
conditional_block
mergesort.rs
// Author : Thomas Minier // Apply Merge sort on two slices fn merge(left : &[i32], right : &[i32]) -> Vec<i32> { let mut res = vec!(); let (mut left_set, mut right_set) = (left, right); while (!left_set.is_empty()) && (!right_set.is_empty()) { let (left_head, left_tail) = left_set.split_first().un...
#[test] fn test_merge_sort() { let v = vec!(5,1,4,3,2,6); let w = merge_sort(&v); assert_eq!(vec!(1,2,3,4,5,6), w); }
{ if list.len() <= 1 { return list.to_vec(); } let (left, right) = list.split_at(list.len() / 2); return merge(&merge_sort(left), &merge_sort(right)); }
identifier_body
mergesort.rs
// Author : Thomas Minier // Apply Merge sort on two slices fn merge(left : &[i32], right : &[i32]) -> Vec<i32> { let mut res = vec!(); let (mut left_set, mut right_set) = (left, right); while (!left_set.is_empty()) && (!right_set.is_empty()) { let (left_head, left_tail) = left_set.split_first().un...
// drain collections for x in left_set { res.push(*x); } for x in right_set { res.push(*x); } res } // Sort a slice using the Merge Sort algorithm pub fn merge_sort(list : &[i32]) -> Vec<i32> { if list.len() <= 1 { return list.to_vec(); } let (left, right) = ...
} else { res.push(*right_head); right_set = right_tail; } }
random_line_split
mobile_user_agent.user.js
// @grant none // @homepage http://ford-rt.com // @include https://mail.yandex.ru/* // @include http://www.rbc.ru/* // @name mua // @namespace http://ford-rt.com // @run-at document-start // @updateURL https://github.com/ford153focus/userscripts/raw/master/mobile_user_agent.user...
// ==UserScript== // @author frt.ford153focus // @description switch ua to mobile
random_line_split
ptr_offset.rs
extern crate crucible; use std::ptr; use crucible::*; use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals}; fn f(ptr: *mut u8) { unsafe { ptr::swap(ptr, ptr.add(1)) }; } #[crux_test] fn f_test() { clobber_globals(); let mut x = <[u8; 2]>::symbolic("x"); crucible_assume!(x[0] > 0...
}
random_line_split
ptr_offset.rs
extern crate crucible; use std::ptr; use crucible::*; use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals}; fn f(ptr: *mut u8) { unsafe { ptr::swap(ptr, ptr.add(1)) }; } #[crux_test] fn f_test()
fn f_spec() -> MethodSpec { let mut x = <[u8; 2]>::symbolic("x"); crucible_assume!(x[0] > 0); crucible_assume!(x[1] == 0); let mut msb = MethodSpecBuilder::new(f); msb.add_arg(& &mut x[0]); msb.gather_assumes(); // Call happens here crucible_assert!(x[1] > 0); msb.set_return(&()...
{ clobber_globals(); let mut x = <[u8; 2]>::symbolic("x"); crucible_assume!(x[0] > 0); f(&mut x[0]); crucible_assert!(x[1] > 0); }
identifier_body
ptr_offset.rs
extern crate crucible; use std::ptr; use crucible::*; use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals}; fn f(ptr: *mut u8) { unsafe { ptr::swap(ptr, ptr.add(1)) }; } #[crux_test] fn f_test() { clobber_globals(); let mut x = <[u8; 2]>::symbolic("x"); crucible_assume!(x[0] > 0...
() { f_spec().enable(); let a = u8::symbolic("a"); let b = u8::symbolic("b"); let x = u8::symbolic("x"); let y = u8::symbolic("y"); crucible_assume!(0 < a && a < 10); crucible_assume!(b == 0); let mut arr = [x, a, b, y]; f(&mut arr[1]); let [x2, a2, b2, y2] = arr; crucible_a...
use_f
identifier_name
twistedtools.py
""" Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted_ event loop. You must import this module *before* importing anything from Twisted itself! Example:: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): ...
# Catch exceptions raised in the test body (from the # Twisted thread) except: q.put(sys.exc_info()) reactor.callFromThread(g) try: error = q.get(timeout=timeout) except Empty: raise T...
def wrapper(*args, **kargs): q = Queue() def callback(value): q.put(None) def errback(failure): # Retrieve and save full exception info try: failure.raiseException() except: q.put(...
identifier_body
twistedtools.py
""" Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted_ event loop. You must import this module *before* importing anything from Twisted itself! Example:: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): ...
# Check for common syntax mistake # (otherwise, tests can be silently ignored # if one writes "@deferred" instead of "@deferred()") try: timeout is None or timeout + 0 except TypeError: raise TypeError("'timeout' argument must be a number or None") def decorate(func): d...
raise ImportError("twisted is not available or could not be imported")
conditional_block
twistedtools.py
""" Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted_ event loop. You must import this module *before* importing anything from Twisted itself! Example:: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): ...
(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. ...
deferred
identifier_name
twistedtools.py
""" Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted_ event loop. You must import this module *before* importing anything from Twisted itself! Example:: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): ...
@deferred(timeout=5.0) def test_resolve(): d = reactor.resolve("www.python.org") def check_ip(ip): assert ip == "67.15.36.43" d.addCallback(check_ip) return d .. _Twisted: http://twistedmatrix.com/trac/ """ import sys from Queue import Queue, Empty from nose.tools import make_dec...
random_line_split
htmllinkelement.rs
PreInvoke}; use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use std::mem; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::media_queries::{MediaQueryList, parse_media_query_list}; use...
} fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_...
}
random_line_split
htmllinkelement.rs
::HTML_SPACE_CHARACTERS; no_jsmanaged_fields!(Stylesheet); #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scri...
{ if status.is_err() { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); return; } let data = mem::replace(&mut self.data, vec!()); let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }...
identifier_body
htmllinkelement.rs
PreInvoke}; use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use std::mem; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::media_queries::{MediaQueryList, parse_media_query_list}; use...
(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if !self.upcast::<Node>().is_in_doc() || mutation == Attribu...
super_type
identifier_name
utils.js
'use strict'; /*global require*/ var assert = require('assert'), utils = require('./../public/src/utils.js'); describe('Utility Methods', function(){ describe('username validation', function(){ it('accepts latin-1 characters', function(){ var username = "John\"'-. Doeäâèéë1234"; assert(utils.isUserNameVali...
}); describe('email validation', function(){ it('accepts sample address', function(){ var email = 'sample@example.com'; assert(utils.isEmailValid(email), 'invalid email'); }); it('rejects empty address', function(){ var email = ''; assert.ifError(utils.isEmailValid(email), 'accepted as valid email'...
var username = ''; assert.ifError(utils.isUserNameValid(username), 'accepted as valid username'); });
random_line_split
treasureen_scraper.py
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
(self, video): return self._blog_get_url(video) @classmethod def get_settings(cls): settings = super(cls, cls).get_settings() settings = scraper_utils.disable_sub_check(settings) name = cls.get_name() settings.append(' <setting id="%s-filter" type="slider" range=...
get_url
identifier_name
treasureen_scraper.py
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout self.base_url = kodi.get_setting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.MOVIE]) @classmethod def get_name(cls): return 'treasureen' ...
class Scraper(scraper.Scraper): base_url = BASE_URL
random_line_split
treasureen_scraper.py
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
host = urlparse.urlparse(source).hostname quality = scraper_utils.height_get_quality(meta.get('height', 480)) hoster = {'multi-part': False, 'host': host, 'class': self, 'views': None, 'url': source, 'rating': None, 'quality': quality, 'direct': True} if ...
continue
conditional_block
treasureen_scraper.py
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
def get_sources(self, video): source_url = self.get_url(video) hosters = [] if not source_url or source_url == FORCE_NO_MATCH: return hosters url = scraper_utils.urljoin(self.base_url, source_url) html = self._http_get(url, require_debrid=False, cache_limit=.5) titl...
return 'treasureen'
identifier_body
full0.py
import tensorflow as tf from tensorflow.contrib import slim as slim from avb.ops import * import math def
(x, config, is_training=True): df_dim = config['df_dim'] z_dim = config['z_dim'] a_dim = config['iaf_a_dim'] # Center x at 0 x = 2*x - 1 net = flatten_spatial(x) net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_0") net = slim.fully_connected(net, 300, activa...
encoder
identifier_name
full0.py
import tensorflow as tf from tensorflow.contrib import slim as slim from avb.ops import * import math def encoder(x, config, is_training=True):
df_dim = config['df_dim'] z_dim = config['z_dim'] a_dim = config['iaf_a_dim'] # Center x at 0 x = 2*x - 1 net = flatten_spatial(x) net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_0") net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_1...
identifier_body
full0.py
import tensorflow as tf from tensorflow.contrib import slim as slim from avb.ops import * import math
a_dim = config['iaf_a_dim'] # Center x at 0 x = 2*x - 1 net = flatten_spatial(x) net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_0") net = slim.fully_connected(net, 300, activation_fn=tf.nn.softplus, scope="fc_1") zmean = slim.fully_connected(net, z_dim, activ...
def encoder(x, config, is_training=True): df_dim = config['df_dim'] z_dim = config['z_dim']
random_line_split
tarteaucitron.it.js
/*global tarteaucitron */ tarteaucitron.lang = { "adblock": "Benvenuto! Questo sito ti permette di attivare i servizi di terzi di tua scelta.", "adblock_call": "Disabilita il tuo adblocker per iniziare la navigazione.", "reload": "Aggiorna la pagina", "alertBigScroll": "Continuando a scorrere,", ...
"all": "Preferenze per tutti i servizi", "info": "Tutela della privacy", "disclaimer": "Abilitando l'uso dei servizi di terze parti, accetti la ricezione dei cookies e l'uso delle tecnologie analitici necessarie al loro funzionamento.", "allow": "Consenti", "deny": "Blocca", "noCookie"...
"alertSmall": "Gestione dei servizi", "acceptAll": "Ok, accetta tutto", "personalize": "Personalizza", "close": "Chiudi",
random_line_split
CompatibilityCheck.js
/* * Licensed under BSD http://en.wikipedia.org/wiki/BSD_License * Copyright (c) 2010, Duponchel David * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source cod...
/*DEBUG_END*/ xmlCompat = izpack.compatibility.xml = { w3c : typeof XMLSerializer !== "undefined" && document.implementation && document.implementation.createDocument && typeof document.implementation.createDocument !== "undefined", ie : typeof window.ActiveXObject !== "undefined" }; if (!xmlCompat.w3c &&...
{ // IE 8 implements console.log in his "developer tools" but not console.debug... console.debug = console.log; }
conditional_block
CompatibilityCheck.js
/* * Licensed under BSD http://en.wikipedia.org/wiki/BSD_License * Copyright (c) 2010, Duponchel David * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met:
* * Neither the name of the GraouPack nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED...
* * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation an...
random_line_split
2.py
# # Written by Luke Kenneth Casson Leighton <lkcl@lkcl.net> # This theme is demonstrates how to #this import statement allows access to the karamba functions import karamba drop_txt = None #this is called when you widget is initialized def initWidget(widget): # this resets the text to "" so we know we've nev...
# this is a pain. in order to avoid memory-related threading problems, # and also locking, with the communication between themes, the # communication is done asynchronously. so you have to POLL for the # information, by reading getIncomingData(). # # therefore, you must set an interval=time_in_ms in your receiving ...
karamba.setIncomingData(widget, name, "") karamba.redrawWidget(widget)
random_line_split
2.py
# # Written by Luke Kenneth Casson Leighton <lkcl@lkcl.net> # This theme is demonstrates how to #this import statement allows access to the karamba functions import karamba drop_txt = None #this is called when you widget is initialized def initWidget(widget): # this resets the text to "" so we know we've nev...
(widget): global expected_seq # i hate globals. please write better code than this example. # get the "message"... disp = karamba.getIncomingData(widget) if disp == "": return # decode it... (seq, x, y, button) = eval(disp) # if it's been seen before, skip it... if seq <= ex...
widgetUpdated
identifier_name
2.py
# # Written by Luke Kenneth Casson Leighton <lkcl@lkcl.net> # This theme is demonstrates how to #this import statement allows access to the karamba functions import karamba drop_txt = None #this is called when you widget is initialized def initWidget(widget): # this resets the text to "" so we know we've nev...
# decode it... (seq, x, y, button) = eval(disp) # if it's been seen before, skip it... if seq <= expected_seq: pass expected_seq += 1 message = "seq:%d x:%d y:%d btn:%d" % (seq, x, y, button) # delete previous text if exists. global drop_txt if drop_txt is not None: ...
return
conditional_block
2.py
# # Written by Luke Kenneth Casson Leighton <lkcl@lkcl.net> # This theme is demonstrates how to #this import statement allows access to the karamba functions import karamba drop_txt = None #this is called when you widget is initialized def initWidget(widget): # this resets the text to "" so we know we've nev...
karamba.deleteText(widget, drop_txt) # display it... drop_txt = karamba.createText(widget, 0, 20, 300, 20, message) karamba.changeTextColor(widget, drop_txt, 252,252,252) karamba.redrawWidget(widget) pass # This will be printed when the widget loads. print "Loaded my python 2.py extensi...
global expected_seq # i hate globals. please write better code than this example. # get the "message"... disp = karamba.getIncomingData(widget) if disp == "": return # decode it... (seq, x, y, button) = eval(disp) # if it's been seen before, skip it... if seq <= expected_seq: ...
identifier_body
path119.py
import zstackwoodpecker.test_state as ts_header TestAction = ts_header.TestAction def
(): return dict(initial_formation="template4",\ path_list=[[TestAction.delete_volume, "vm1-volume1"], \ [TestAction.reboot_vm, "vm1"], \ [TestAction.create_volume, "volume1", "=scsi"], \ [TestAction.attach_volume, "vm1", "volume1"], \ [TestAction.create_volume_backup, "volume1", "backup1"], ...
path
identifier_name
path119.py
import zstackwoodpecker.test_state as ts_header TestAction = ts_header.TestAction def path(): return dict(initial_formation="template4",\ path_list=[[TestAction.delete_volume, "vm1-volume1"], \ [TestAction.reboot_vm, "vm1"], \ [TestAction.create_volume, "volume1", "=scsi"], \ [TestAction.attac...
[TestAction.stop_vm, "vm1"], \ [TestAction.use_volume_backup, "backup1"], \ [TestAction.start_vm, "vm1"], \ [TestAction.reboot_vm, "vm1"]])
[TestAction.start_vm, "vm1"], \ [TestAction.create_volume_snapshot, "volume1", 'snapshot1'], \ [TestAction.detach_volume, "volume1"], \ [TestAction.clone_vm, "vm1", "vm2", "=full"], \ [TestAction.attach_volume, "vm1", "volume1"], \
random_line_split
path119.py
import zstackwoodpecker.test_state as ts_header TestAction = ts_header.TestAction def path():
return dict(initial_formation="template4",\ path_list=[[TestAction.delete_volume, "vm1-volume1"], \ [TestAction.reboot_vm, "vm1"], \ [TestAction.create_volume, "volume1", "=scsi"], \ [TestAction.attach_volume, "vm1", "volume1"], \ [TestAction.create_volume_backup, "volume1", "backup1"], \ [Tes...
identifier_body
shadow.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
} _ => { } } } enum t<T> { none, some(T), } pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
{ for c.each |i| { debug!(a); let a = 17; b += ~[a]; }
conditional_block
shadow.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
match none::<int> { some::<int>(_) => { for c.each |i| { debug!(a); let a = 17; b += ~[a]; } } _ => { } } } enum t<T> { none, some(T), } pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
let mut b: ~[int] = ~[];
random_line_split
shadow.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
} enum t<T> { none, some(T), } pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
{ let a: int = 5; let mut b: ~[int] = ~[]; match none::<int> { some::<int>(_) => { for c.each |i| { debug!(a); let a = 17; b += ~[a]; } } _ => { } }
identifier_body
shadow.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
() { let x = 10; let x = x + 20; assert!((x == 30)); foo(~[]); }
main
identifier_name
camera.rs
extern crate cgmath; use {Mat4, Vec3, Vec4}; use cgmath::*; use geometry; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Camera { pub at: Vec3, pub pitch: Rad<f64>, pub viewport: (u32, u32), pub pixels_per_unit: f64, } impl Camera { pub fn view(&self) -> Mat4 { view(self.pitch, self....
else { None } }
{ let n_x = (x as f64) / (width as f64) * 2.0 - 1.0; let n_y = ((y as f64) / (height as f64) * 2.0 - 1.0) * -1.0; let front = Vec4::new(n_x, n_y, -1.0, 1.0); let back = Vec4::new(n_x, n_y, 1.0, 1.0); let front_world = inverse_view_projection * front; let back_world = in...
conditional_block
camera.rs
extern crate cgmath; use {Mat4, Vec3, Vec4}; use cgmath::*; use geometry; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Camera { pub at: Vec3, pub pitch: Rad<f64>, pub viewport: (u32, u32), pub pixels_per_unit: f64, } impl Camera { pub fn view(&self) -> Mat4 { view(self.pitch, self....
pub fn view(pitch: Rad<f64>, at: Vec3) -> Mat4 { Mat4::from_angle_x(pitch) * Mat4::from_translation(at * -1.0) } pub fn projection(width:u32, height:u32, pixels_per_unit: f64) -> Mat4 { let effective_width = (width as f64) / (pixels_per_unit); let effective_height = (height as f64) / (pixels_per_unit) / (...
random_line_split
camera.rs
extern crate cgmath; use {Mat4, Vec3, Vec4}; use cgmath::*; use geometry; #[derive(PartialEq, Debug, Copy, Clone)] pub struct Camera { pub at: Vec3, pub pitch: Rad<f64>, pub viewport: (u32, u32), pub pixels_per_unit: f64, } impl Camera { pub fn view(&self) -> Mat4 { view(self.pitch, self....
(&self) -> f64 { 1.0 / self.pixels_per_unit } pub fn view_projection(&self) -> Mat4 { self.projection() * self.view() } pub fn inverse_view_projection(&self) -> Option<Mat4> { use cgmath::SquareMatrix; let vp = self.view_projection(); vp.invert() } pub ...
units_per_pixel
identifier_name
datacollect.py
if osname: self.os_search_path.append(osname) self.collectors = {} # dictionary of collectors and their associated objects def import_module(self, module): """Return a reference to the imported module, or none if the import failed. """ mod...
_checkCache
identifier_name
datacollect.py
can't start with digit self.osname = osname self.osver = osver self.osarch = osarch # most specific to least specific self.os_search_path = [] if osname and osver and osarch: self.os_search_path.append('.'.join([osname, osver, osarch])) self.os_...
""" if self.max_level > 0: if len(self.historical_data) > self.max_level: # remove oldest data self.historical_data = self.historical_data[:-1] self.historical_data.insert(0, data) def length(self): """Returns the current length of t...
and removing oldest data from list. If max_level is 0, no history is required, so nothing is done.
random_line_split
datacollect.py
can't start with digit self.osname = osname self.osver = osver self.osarch = osarch # most specific to least specific self.os_search_path = [] if osname and osver and osarch: self.os_search_path.append('.'.join([osname, osver, osarch])) self.os_...
def update(self, data): """Update data history by adding new data object to history list and removing oldest data from list. If max_level is 0, no history is required, so nothing is done. """ if self.max_level > 0: if len(self.historical_data) > self.max_level...
"""Overloaded [] to return the historical data, num is the age of the data. num can be 0 which is the current data; 1 is the previous data, etc. e.g., d = history[5] would assign d the Data object from 5 'collection periods' ago. """ try: data = self.historical_data[...
identifier_body
datacollect.py
module for ospath in self.os_search_path: try: modparent = __import__( '.'.join(['boristool', 'arch', ospath]), globals(), locals(), [module], ) modobj = getattr(modparent...
log.log("<datacollect>DataCollect._checkCache(): refreshing data", 7) self._refresh()
conditional_block
oneshot.rs
order to upgrade a oneshot channel, an upgrade is considered a disconnect /// on behalf of the channel side of things (it can be mentally thought of as /// consuming the port). This upgrade is then also stored in the shared packet. /// The one caveat to consider is that when a port sees a disconnected channel /// it m...
(&mut self, task: BlockedTask) -> SelectionResult<T> { let n = unsafe { task.cast_to_uint() }; match self.state.compare_and_swap(
start_selection
identifier_name
oneshot.rs
a oneshot that's already sent on "), } assert!(self.data.is_none()); self.data = Some(t); self.upgrade = SendUsed; match self.state.swap(DATA, atomic::SeqCst) { // Sent the data, no one was waiting EMPTY => Ok(()), // Couldn't send the data,...
{ let state = match self.state.load(atomic::SeqCst) { // Each of these states means that no further activity will happen // with regard to abortion selection s @ EMPTY | s @ DATA | s @ DISCONNECTED => s, // If we've got a blocked task, the...
identifier_body
oneshot.rs
/// is created. /// /// Another possible optimization would be to not use an Arc box because /// in theory we know when the shared packet can be deallocated (no real need /// for the atomic reference counting), but I was having trouble how to destroy /// the data early in a drop of a Port. /// /// # Implementation /// ...
/// /// This is the initial flavor of channels/ports used for comm module. This is /// an optimization for the one-use case of a channel. The major optimization of /// this type is to have one and exactly one allocation when the chan/port pair
random_line_split
oneshot.rs
order to upgrade a oneshot channel, an upgrade is considered a disconnect /// on behalf of the channel side of things (it can be mentally thought of as /// consuming the port). This upgrade is then also stored in the shared packet. /// The one caveat to consider is that when a port sees a disconnected channel /// it m...
// If someone's waiting, we gotta wake them up n => UpWoke(unsafe { BlockedTask::cast_from_uint(n) }) } } pub fn drop_chan(&mut self) { match self.state.swap(DISCONNECTED, atomic::SeqCst) { DATA | DISCONNECTED | EMPTY => {} // If someone's wait...
{ self.upgrade = prev; UpDisconnected }
conditional_block
bootstrap_commands.py
os.rename(frm, to) os.rmdir(movedir) os.remove(src) @CommandProvider class MachCommands(CommandBase): @Command('env', description='Print environment setup commands', category='bootstrap') def env(self): env = self.build_env() print("export PATH=%s" % env...
check_call( ["git", "submodule", "--quiet", "sync", "--recursive"]) check_call( ["git", "submodule", "update", "--init", "--recursive"])
random_line_split