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 |
|---|---|---|---|---|
TftpContexts.py | # Metrics
self.metrics = TftpMetrics()
# Fluag when the transfer is pending completion.
self.pending_complete = False
# Time when this context last received any traffic.
# FIXME: does this belong in metrics?
self.last_update = 0
# The last packet we sent, ... | self.file_to_transfer = filename | random_line_split | |
TftpContexts.py | , to make resending easy.
self.last_pkt = None
# Count the number of retry attempts.
self.retry_count = 0
def getBlocksize(self):
"""Fetch the current blocksize for this session."""
return int(self.options.get("blksize", 512))
def __del__(self):
"""Simple destru... | self.fileobj = output
self.filelike_fileobj = True | conditional_block | |
TftpContexts.py | %d bytes from %s:%s", len(buffer), raddress, rport)
# And update our last updated time.
self.last_update = time.time()
# Decode it.
recvpkt = self.factory.parse(buffer)
# Check for known "connection".
if raddress != self.address:
log.warning(
... | """Finish up the context."""
TftpContext.end(self, not self.filelike_fileobj)
self.metrics.end_time = time.time()
log.debug("Set metrics.end_time to %s" % self.metrics.end_time)
self.metrics.compute() | identifier_body | |
mk.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | [
'недела', 'понеделник', 'вторник', 'среда', 'четврток',
'петок', 'сабота'
],
['нед.', 'пон.', 'вто.', 'сре.', 'чет.', 'пет.', 'саб.']
],
[
['ј', 'ф', 'м', 'а', 'м', 'ј', 'ј', 'а', 'с', 'о', 'н', 'д'],
[
'јан.', 'фев.', 'мар.', 'апр.', 'мај', 'јун.', 'јул.', 'авг.',
'сеп... | random_line_split | |
mk.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'mk',
[['претпл.', 'попл.'], u, ['претпладне', 'попладне']],
u,
[
['н', 'п', 'в', 'с', 'ч', 'п', 'с'],
['нед.', 'пон.', 'вт.', 'сре.', 'чет.', 'пет.', 'саб.'],
[
'недела', 'понеделник', 'вторник', 'среда', 'четврток',
'петок', 'сабота'
],
['нед.', 'пон.', 'вто.... | {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length,
f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0;
if (v === 0 && i % 10 === 1 && !(i % 100 === 11) || f % 10 === 1 && !(f % 100 === 11)) return 1;
return 5;
} | identifier_body |
mk.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length,
f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0;
if (v === 0 && i % 10 === 1 && !(i % 100 === 11) || f % 10 === 1 && !(f % 100 === 11)) return 1;
return 5;
}
export default [
'mk',
[['п... | plural | identifier_name |
convert.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (pname):
p1 = pname.find('/')
p2 = pname.rfind('/')
assert p1 != -1 and p2 != -1, 'param name = %s is not correct' % pname
if 'gamma' in pname:
suffix = 'weight'
elif 'beta' in pname:
suffix = 'bias'
elif 'mean' in pname:
suffix = 'running_mean'
elif 'var' in pname:
... | rename | identifier_name |
convert.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
else:
suffix = pname[p2 + 1:]
return pname[p1+1:p2] + '.' + suffix
if __name__ == '__main__':
parser = ArgumentParser(description='Convert params from torch to python'
'dict. ')
parser.add_argument("depth", type=int, choices=[121, 169, 201, 161])
parser.add_arg... | suffix = 'running_var' | conditional_block |
convert.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
try:
import cPickle as pickle
except ModuleNotFoundError:
import pickle
URL_PREFIX = 'https://download.pytorch.org/models/'
model_urls = {
'densenet121': URL_PREFIX + 'densenet121-a639ec97.pth',
'densenet169': URL_PREFIX + 'densenet169-b2777c0a.pth',
'densenet201': URL_PREFIX + 'densenet201-c11035... |
import model | random_line_split |
convert.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
if __name__ == '__main__':
parser = ArgumentParser(description='Convert params from torch to python'
'dict. ')
parser.add_argument("depth", type=int, choices=[121, 169, 201, 161])
parser.add_argument("outfile")
parser.add_argument('nb_classes', default=1000, type=int)
... | p1 = pname.find('/')
p2 = pname.rfind('/')
assert p1 != -1 and p2 != -1, 'param name = %s is not correct' % pname
if 'gamma' in pname:
suffix = 'weight'
elif 'beta' in pname:
suffix = 'bias'
elif 'mean' in pname:
suffix = 'running_mean'
elif 'var' in pname:
suffix... | identifier_body |
006_dns_records.py | # Copyright 2011 OpenStack Foundation
# 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 requ... | (migrate_engine):
meta.bind = migrate_engine
drop_tables([dns_records])
| downgrade | identifier_name |
006_dns_records.py | # Copyright 2011 OpenStack Foundation
# 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 requ... | dns_records = Table(
'dns_records', meta,
Column('name', String(length=255), primary_key=True),
Column('record_id', String(length=64)))
def upgrade(migrate_engine):
meta.bind = migrate_engine
create_tables([dns_records])
def downgrade(migrate_engine):
meta.bind = migrate_engine
drop_tabl... |
meta = MetaData()
| random_line_split |
006_dns_records.py | # Copyright 2011 OpenStack Foundation
# 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 requ... |
def downgrade(migrate_engine):
meta.bind = migrate_engine
drop_tables([dns_records])
| meta.bind = migrate_engine
create_tables([dns_records]) | identifier_body |
auth.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IUser } from './user.model';
@Injectable()
export class AuthService {
currentUser: IUser;
constructor(private http: Http) { }
checkAuthe... | })
.subscribe();
}
isAuthenticated() {
return !!this.currentUser;
}
login(username: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let info = { username: username.toLo... | .do(currentUser => {
if (!!currentUser.userName) {
this.currentUser = currentUser;
}
| random_line_split |
auth.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IUser } from './user.model';
@Injectable()
export class AuthService {
currentUser: IUser;
constructor(private http: Http) { }
checkAuthe... |
})
.do(currentUser => {
if (!!currentUser.userName) {
this.currentUser = currentUser;
}
})
.subscribe();
}
isAuthenticated() {
return !!this.currentUser;
}
login(username: string, password: string) {
let headers = new Headers({ 'Content... | {
return {};
} | conditional_block |
auth.service.ts | import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { IUser } from './user.model';
@Injectable()
export class AuthService {
currentUser: IUser;
constructor(private http: Http) { }
checkAuthe... | () {
this.currentUser = undefined;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/logout', {}, options);
}
updateCurrentUser(firstName: string, lastName: string) {
this.currentUse... | logout | identifier_name |
environment_hash.ts | import * as path from 'path';
import {Promise} from 'bluebird';
import {FileSystemCache} from '../file_system';
import {IncrementalStringHash} from '../common';
export interface environmentHashOptions {
root?: string;
files?: string[];
directories?: string[];
}
export function environmentHash(fileSystemCache: F... | (fileSystemCache: FileSystemCache, files: string[]): Promise<string> {
if (!files.length) {
return Promise.resolve('_');
}
const hashes = files.map((fileName) => fileSystemCache.readText(fileName));
const modifiedTimes = files.map((fileName) => fileSystemCache.readModifiedTime(fileName));
return Promise... | generateFilesHash | identifier_name |
environment_hash.ts | import * as path from 'path';
import {Promise} from 'bluebird';
import {FileSystemCache} from '../file_system';
import {IncrementalStringHash} from '../common';
export interface environmentHashOptions {
root?: string;
files?: string[];
directories?: string[];
}
export function environmentHash(fileSystemCache: F... |
}
export function generateFilesHash(fileSystemCache: FileSystemCache, files: string[]): Promise<string> {
if (!files.length) {
return Promise.resolve('_');
}
const hashes = files.map((fileName) => fileSystemCache.readText(fileName));
const modifiedTimes = files.map((fileName) => fileSystemCache.readModif... | {
return path.join(root, file);
} | conditional_block |
environment_hash.ts | import * as path from 'path'; | export interface environmentHashOptions {
root?: string;
files?: string[];
directories?: string[];
}
export function environmentHash(fileSystemCache: FileSystemCache, options?: environmentHashOptions): Promise<string> {
options = options || {};
const root = options.root || process.cwd();
const files = (op... | import {Promise} from 'bluebird';
import {FileSystemCache} from '../file_system';
import {IncrementalStringHash} from '../common';
| random_line_split |
environment_hash.ts | import * as path from 'path';
import {Promise} from 'bluebird';
import {FileSystemCache} from '../file_system';
import {IncrementalStringHash} from '../common';
export interface environmentHashOptions {
root?: string;
files?: string[];
directories?: string[];
}
export function environmentHash(fileSystemCache: F... |
export function generateDirectoriesHash(fileSystemCache: FileSystemCache, directories: string[]): Promise<string> {
if (!directories.length) {
return Promise.resolve('_');
}
const allContents = directories.map(directory => {
return fileSystemCache.readDirectoryContents(directory)
.then(contents =... | {
if (!files.length) {
return Promise.resolve('_');
}
const hashes = files.map((fileName) => fileSystemCache.readText(fileName));
const modifiedTimes = files.map((fileName) => fileSystemCache.readModifiedTime(fileName));
return Promise.all([
Promise.all(hashes),
Promise.all(modifiedTimes)
]).t... | identifier_body |
sistema.js | $(function(){
$('#telefone').mask('(99)9999-9999');
$('.editar').on({
click : function(){
var url = URI+"sistema/editar/"+$(this).attr('data-item');
window.location.href = url;
}
});
$('.deletar').on({
click : function(){
... |
else
{
pop_up('nenhum item selecionado');
}
}
});
$('#description').on('keyup',function(){
var alvo = $("#char-digitado");
var max = 140;
var digitados = $(this).val().length;
var restante ... | {
var $url = URI+"sistema/remover/";
if (window.confirm("deseja apagar os ("+$selecionados.length+") itens selecionados? "))
{
$.post($url, { 'selecionados': $selecionados}, function(data){
pop_up... | conditional_block |
sistema.js | $(function(){
$('#telefone').mask('(99)9999-9999');
$('.editar').on({
click : function(){
var url = URI+"sistema/editar/"+$(this).attr('data-item');
window.location.href = url;
}
});
$('.deletar').on({
click : function(){
... | }
}
});
$('#description').on('keyup',function(){
var alvo = $("#char-digitado");
var max = 140;
var digitados = $(this).val().length;
var restante = max - digitados;
if(digitados > max)
{
var v... | pop_up('nenhum item selecionado'); | random_line_split |
tinymce.spec.js | /*global describe, beforeEach, module, inject, it, spyOn, expect, $, angular, afterEach, runs, waits */
describe('uiTinymce', function () {
'use strict';
var scope, $compile, $timeout, element, directiveElement, id, text = '<p>Hello</p>';
beforeEach(module('ui.tinymce'));
beforeEach(function() {
// throw s... | function compile() {
element = $compile('<form><textarea ui-tinymce="{foo: \'bar\', setup: setupFooBar }" data-ng-model="foo"></textarea></form>')(scope);
angular.element(document.getElementsByTagName('body')[0]).append(element);
scope.$apply();
$timeout.flush();
directiveElement = element.find('t... |
/**
* Asynchronously runs the compilation.
*/ | random_line_split |
tinymce.spec.js | /*global describe, beforeEach, module, inject, it, spyOn, expect, $, angular, afterEach, runs, waits */
describe('uiTinymce', function () {
'use strict';
var scope, $compile, $timeout, element, directiveElement, id, text = '<p>Hello</p>';
beforeEach(module('ui.tinymce'));
beforeEach(function() {
// throw s... | () {
element = $compile('<form><textarea ui-tinymce="{foo: \'bar\', setup: setupFooBar }" data-ng-model="foo"></textarea></form>')(scope);
angular.element(document.getElementsByTagName('body')[0]).append(element);
scope.$apply();
$timeout.flush();
directiveElement = element.find('textarea');
id ... | compile | identifier_name |
tinymce.spec.js | /*global describe, beforeEach, module, inject, it, spyOn, expect, $, angular, afterEach, runs, waits */
describe('uiTinymce', function () {
'use strict';
var scope, $compile, $timeout, element, directiveElement, id, text = '<p>Hello</p>';
beforeEach(module('ui.tinymce'));
beforeEach(function() {
// throw s... |
it('should be pristine on load', function() {
compile();
expect(directiveElement.controller('form').$pristine).toBe(true);
expect(directiveElement.controller('ngModel').$pristine).toBe(true);
expect(directiveElement.controller('ngModel').$touched).toBe(false);
});
describe('compiling this direc... | {
element = $compile('<form><textarea ui-tinymce="{foo: \'bar\', setup: setupFooBar }" data-ng-model="foo"></textarea></form>')(scope);
angular.element(document.getElementsByTagName('body')[0]).append(element);
scope.$apply();
$timeout.flush();
directiveElement = element.find('textarea');
id = d... | identifier_body |
signal_handlers.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# This program 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 option) any later ver... | "key": webhook.key,
})
return webhooks
def on_new_history_entry(sender, instance, created, **kwargs):
if not settings.WEBHOOKS_ENABLED:
return None
if instance.is_hidden:
return None
model = history_service.get_model_from_key(instance.key)
pk = history_service... | webhooks.append({
"id": webhook.pk,
"url": webhook.url, | random_line_split |
signal_handlers.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# This program 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 option) any later ver... |
else:
task(*webhook_args)
| task.delay(*webhook_args) | conditional_block |
signal_handlers.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# This program 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 option) any later ver... | (task, webhooks_args):
for webhook_args in webhooks_args:
if settings.CELERY_ENABLED:
task.delay(*webhook_args)
else:
task(*webhook_args)
| _execute_task | identifier_name |
signal_handlers.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# This program 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 option) any later ver... | for webhook_args in webhooks_args:
if settings.CELERY_ENABLED:
task.delay(*webhook_args)
else:
task(*webhook_args) | identifier_body | |
py2_text.py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 23:10:40 2016
@author: zhouyu
"""
#%%
import pandas as pd
import numpy as np
import os
import re
import nltk
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing')
#%% step1: impor... | (model, feature_names, n_top_words):
res = []
for topic_idx, topic in enumerate(model.components_):
tags = " ".join([feature_names[i]
for i in topic.argsort()[:-n_top_words - 1:-1]])
res.append(tags)
return res
from sklearn.feature_extraction.text import TfidfVe... | get_top_words | identifier_name |
py2_text.py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 23:10:40 2016
@author: zhouyu
"""
#%%
import pandas as pd
import numpy as np
import os
import re
import nltk
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing')
#%% step1: impor... |
#%% use random forest
X_test_counts = count_vect.fit_transform(cleaned_test)
X_test_tf = tf_transformer.transform(X_test_counts)
result = forest.predict(X_test_counts)
# use max tf-idf
#%%
test_pred = []
for i in range(0,test_sz):
tf_test = X_test_tf.getrow(i).toarray()
# just return one tag
#tf_t... | print "Cleanning %d of %d\n" % (i+1,test_sz) | conditional_block |
py2_text.py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 23:10:40 2016
@author: zhouyu
"""
#%%
import pandas as pd
import numpy as np
import os
import re
import nltk
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing')
#%% step1: impor... | for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
cnf_matrix ... | """
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
... | identifier_body |
py2_text.py | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 23:10:40 2016
@author: zhouyu
"""
#%%
import pandas as pd
import numpy as np
import os
import re
import nltk
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing')
#%% step1: impor... | pred = rf.predict(X_train_tf)
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from collections import OrderedDict
import matplotlib.pyplot as plt
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
t... | from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators = 10)
forest = rf.fit(X_train_tf, cleaned_target)
#%% examine the result produced by METHOD 1: | random_line_split |
runtests.py | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_... | 'django.contrib.sessions',
'django.contrib.sites',
'registration',
),
'ROOT_URLCONF': 'registration.backends.default.urls',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(APP_DIR, 'db.sqlite3'),
},
... | 'INSTALLED_APPS': (
'django.contrib.auth',
'django.contrib.contenttypes', | random_line_split |
runtests.py | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_... | from django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import django
if hasattr(django, 'setup'):
django.setup()
# Now we instantiate a test runner...
from django.test.utils import get_r... | identifier_body | |
runtests.py | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_... | ():
# Making Django run this way is a two-step process. First, call
# settings.configure() to give Django settings to work with:
from django.conf import settings
settings.configure(**SETTINGS_DICT)
# Then, call django.setup() to initialize the application cache
# and other bits:
import djan... | run_tests | identifier_name |
runtests.py | """
A standalone test runner script, configuring the minimum settings
required for tests to execute.
Re-use at your own risk: many Django applications will require
different settings and/or templates to run their tests.
"""
import os
import sys
# Make sure the app is (at least temporarily) on the import path.
APP_... |
# Now we instantiate a test runner...
from django.test.utils import get_runner
TestRunner = get_runner(settings)
# And then we run tests and return the results.
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['registration.tests'])
sys.exit(bool(f... | django.setup() | conditional_block |
UIAsset.js | /**
* Symbol Art Editor
*
* @author malulleybovo (since 2021)
* @license GNU General Public License v3.0
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2021 Arthur Malulley B. de O.
*
*
* The JavaScript code in this page is free softwar... | && this.view[0] instanceof HTMLElement
&& this._resourceLoaded;
}
constructor({ filePath = null } = {}) {
super();
let path = filePath;
this.didLoad(_ => {
this.view.on('load', _ => {
this._resourceLoaded = true;
});
... | }
_resourceLoaded = false;
get loaded() {
return this.view instanceof jQuery | random_line_split |
UIAsset.js | /**
* Symbol Art Editor
*
* @author malulleybovo (since 2021)
* @license GNU General Public License v3.0
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2021 Arthur Malulley B. de O.
*
*
* The JavaScript code in this page is free softwar... |
}
});
});
}
}
| {
this._onTap(this);
} | conditional_block |
UIAsset.js | /**
* Symbol Art Editor
*
* @author malulleybovo (since 2021)
* @license GNU General Public License v3.0
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2021 Arthur Malulley B. de O.
*
*
* The JavaScript code in this page is free softwar... | () { return this._onTap }
set onTap(value) {
if (typeof value !== 'function' && value !== null) return;
this._onTap = value;
}
get assetFilePath() {
return this.view.attr('src');
}
_resourceLoaded = false;
get loaded() {
return this.view instanceof jQuery
... | onTap | identifier_name |
inits-1.rs | // General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `re... | ;
// `z` may be initialized here.
rustc_peek(&z);
// `y` is definitely uninitialized here.
rustc_peek(&y); //~ ERROR rustc_peek: bit not set
// `x` is still (definitely) initialized (replace above is a reborrow).
rustc_peek(&x);
::std::mem::drop(x);
// `x` is *definitely* uninitia... | {
z = y;
z
} | conditional_block |
inits-1.rs | // General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn | (test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `ret` starts off uninitialized, so we get an error report here.
rustc_peek(&ret); //~ ERROR rustc_peek: bit not set
// All function formal parameters start off initialized.
rustc_peek(&x);
rustc_peek(&y);
rustc_peek(&z);
ret ... | foo | identifier_name |
inits-1.rs | // General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `re... | fn main() {
foo(true, &mut S(13), S(14), S(15));
foo(false, &mut S(13), S(14), S(15));
} | random_line_split | |
scrape.py | # Functions to download yesterday's races and associated raceforms from host
import configparser
import requests
import re
import sys
import time
import pymongo
import random
from datetime import datetime, timedelta
from hracing.db import parse_racesheet
from hracing.db import mongo_insert_race
from hracing.tools imp... | ():
# get scraping target and login info from config file
configFile='../hracing_private/scraping_payload.ini'
pageConfig = configparser.ConfigParser()
pageConfig.read(configFile)
header=dict(pageConfig['header'])
payload=dict(pageConfig['payload'])
raceids, raceid_urls = download_list_of_races... | main | identifier_name |
scrape.py | # Functions to download yesterday's races and associated raceforms from host
import configparser
import requests
import re
import sys
import time
import pymongo
import random
from datetime import datetime, timedelta
from hracing.db import parse_racesheet
from hracing.db import mongo_insert_race
from hracing.tools imp... | raceids=[]
for tr_url in tr_urls:
url=baseurl+tr_url
temp_race=requests.get(url)
raceid_urls.extend(
re.findall(
'\<li\sclass\=\"raceli\s*status_.*\s*clearfix\"\s*data-url\=\"'
'(\/race\?id\=\d*\&country\=.+\&track\=.*\&date=\d\d\d\d-\d... | 'data-url\=\"(/meetings/meeting\?id\=\d+)\">',
tr_urls_raw[1])
# Loop through race-locations, get raceIDs and urls
raceid_urls=[] | random_line_split |
scrape.py | # Functions to download yesterday's races and associated raceforms from host
import configparser
import requests
import re
import sys
import time
import pymongo
import random
from datetime import datetime, timedelta
from hracing.db import parse_racesheet
from hracing.db import mongo_insert_race
from hracing.tools imp... | print("Time: " + d.strftime(('%Y-%m-%d-%H-%M')))
print("Import race IDs for " + datestr)
print("From " + url)
#Get list of race-locations (TR)
tr_urls_raw=re.split('\<div class\=\"dayHeader\"\>',tpage.text)
tr_urls=re.findall(
'\<div class\=\"meetingRaces\" '
'data-url\=\... | """ Fetch a list of all raceIDs and raceURLs listed on host for a given day.
Date is selected either as:
a) pastdays (e.g. pastdays=1 means yesterday).
OR
b) by specifying a datestr of the format YYYY-MM-DD.
Default is to download races from THREE DAYS AGO, which is useful for
data-base buildi... | identifier_body |
scrape.py | # Functions to download yesterday's races and associated raceforms from host
import configparser
import requests
import re
import sys
import time
import pymongo
import random
from datetime import datetime, timedelta
from hracing.db import parse_racesheet
from hracing.db import mongo_insert_race
from hracing.tools imp... |
yesterdayurl = '/races?date=' + datestr
baseurl = 'https://' + header['host']
url = baseurl + yesterdayurl
# Actual download
tpage=requests.get(url)
#Console feedback
print("Time: " + d.strftime(('%Y-%m-%d-%H-%M')))
print("Import race IDs for " + datestr)
print("From " + url)
... | d = datetime.today()-timedelta(days=int(pastdays))
datestr = d.strftime('%Y-%m-%d') | conditional_block |
image-to-gcode.py | spindle_speed, roughing_offset, roughing_delta,
roughing_feed):
self.image = image
self.units = units
self.tool = tool_shape
self.pixelsize = pixelsize
self.pixelstep = pixelstep
self.safetyheight = safetyheight
self.tolerance = tolerance
self... |
z1 = min(p1[2] + radius, conv.safetyheight)
| dx = di * pixelsize
i = i0 + cx * di
if i < 0 or i >= h1: break
z1 = conv.get_z(i, j0)
dz = (z1 - z0)
if dz <= 0: continue
if dz > dx:
conv.g.write("(case 1)")
radius = dx
... | conditional_block |
image-to-gcode.py | spindle_speed, roughing_offset, roughing_delta,
roughing_feed):
self.image = image
self.units = units
self.tool = tool_shape
self.pixelsize = pixelsize
self.pixelstep = pixelstep
self.safetyheight = safetyheight
self.tolerance = tolerance
self... | :
def __init__(self, feed, max_radius):
self.feed = feed
self.max_radius = max_radius
def __call__(self, conv, i0, j0, points):
if len(points) < 2:
p = points[0][1]
if self.feed:
conv.g.set_feed(self.feed)
conv.g.safety()
c... | ArcEntryCut | identifier_name |
image-to-gcode.py | spindle_speed, roughing_offset, roughing_delta,
roughing_feed):
self.image = image
self.units = units
self.tool = tool_shape
self.pixelsize = pixelsize
self.pixelstep = pixelstep
self.safetyheight = safetyheight
self.tolerance = tolerance
self... | milldata = (i, (x, y, self.get_z(i, j)),
self.get_dz_dx(i, j), self.get_dz_dy(i, j))
scan.append(milldata)
for flag, points in convert_scan(primary, scan):
if flag:
self.entry_cut(self, points[0][0], j, points)
... | y = (w1-j) * pixelsize
scan = []
for i in irange:
x = i * pixelsize | random_line_split |
image-to-gcode.py | return j + keep - j%keep
for i, (flag, span) in enumerate(self.converter(primary, items)):
subspan = []
a = None
for i, si in enumerate(span):
ki = si[idx]
if a is None:
if test(abs(ki), slope):
... | def __init__(self, converter, slope, keep):
self.converter = converter
self.slope = slope
self.keep = keep
def __call__(self, primary, items):
slope = self.slope
keep = self.keep
if primary:
idx = 3
test = operator.le
else:
... | identifier_body | |
panel.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | from openstack_dashboard.api import keystone
class Domains(horizon.Panel):
name = _("Domains")
slug = 'domains'
policy_rules = (("identity", "identity:get_domain"),
("identity", "identity:list_domains"))
@staticmethod
def can_register():
return keystone.VERSIONS.active... |
import horizon
| random_line_split |
panel.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 requir... |
request = context['request']
domain_token = request.session.get('domain_token')
return super(Domains, self).can_access(context) and domain_token
| return super(Domains, self).can_access(context) | conditional_block |
panel.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | (horizon.Panel):
name = _("Domains")
slug = 'domains'
policy_rules = (("identity", "identity:get_domain"),
("identity", "identity:list_domains"))
@staticmethod
def can_register():
return keystone.VERSIONS.active >= 3
def can_access(self, context):
if keyston... | Domains | identifier_name |
panel.py | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 requir... |
def can_access(self, context):
if keystone.VERSIONS.active < 3:
return super(Domains, self).can_access(context)
request = context['request']
domain_token = request.session.get('domain_token')
return super(Domains, self).can_access(context) and domain_token
| return keystone.VERSIONS.active >= 3 | identifier_body |
TestDataFormatterGlobals.py | """
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
class GlobalsDataFormatterTestCase(TestBase):
mydir = TestBase.compute_my... | (self):
"""Test that that file and class static variables display correctly."""
self.build()
self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line(
self, "main.cpp", self.line, num_expected_locations=1, loc_exac... | test_with_run_command | identifier_name |
TestDataFormatterGlobals.py | """
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
class GlobalsDataFormatterTestCase(TestBase):
mydir = TestBase.compute_my... | "type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point")
self.expect("target variable g_point",
substrs=['x='])
self.expect("target variable g_point_pointer",
substrs=['(Point *) g_point_pointer ... | self.runCmd( | random_line_split |
TestDataFormatterGlobals.py | """
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
class GlobalsDataFormatterTestCase(TestBase):
mydir = TestBase.compute_my... | substrs=['JustATest'])
self.expect("target variable g_point_pointer",
substrs=['(Point *) g_point_pointer ='])
# Print some information about the variables
# (we ignore the actual values)
self.runCmd(
"type summary add --summary-strin... | """Test that that file and class static variables display correctly."""
self.build()
self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line(
self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
... | identifier_body |
checkdatabaseschema.py | ##
# Copyright (c) 2014 Apple 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 la... |
def error(s):
sys.stderr.write("%s\n" % (s,))
sys.exit(1)
def main():
try:
(optargs, _ignore_args) = getopt(
sys.argv[1:], "d:hk:vx", [
"help",
"verbose",
],
)
except GetoptError, e:
usage(e)
verbose = False
... | pass | identifier_body |
checkdatabaseschema.py | ##
# Copyright (c) 2014 Apple 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 la... | DATABASENAME = "caldav"
PGSOCKETDIR = "127.0.0.1"
SCHEMADIR = "./txdav/common/datastore/sql_schema/"
# Executables:
PSQL = "../postgresql/_root/bin/psql"
def usage(e=None):
name = os.path.basename(sys.argv[0])
print("usage: %s [options] username" % (name,))
print("")
print(" Check calendar server post... | from twisted.python.filepath import FilePath
USERNAME = "caldav" | random_line_split |
checkdatabaseschema.py | ##
# Copyright (c) 2014 Apple 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 la... |
# Retrieve the db_version number of the installed schema
try:
db_version = getSchemaVersion(verbose=verbose)
except CheckSchemaError, e:
db_version = 0
# Retrieve the version number from the schema file
currentschema = FilePath(SCHEMADIR).child("current.sql")
try:
dat... | raise NotImplementedError(opt) | conditional_block |
checkdatabaseschema.py | ##
# Copyright (c) 2014 Apple 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 la... | (s):
sys.stderr.write("%s\n" % (s,))
sys.exit(1)
def main():
try:
(optargs, _ignore_args) = getopt(
sys.argv[1:], "d:hk:vx", [
"help",
"verbose",
],
)
except GetoptError, e:
usage(e)
verbose = False
global SCHEM... | error | identifier_name |
tsd.d.ts | /// <reference path="intern/intern.d.ts" />
declare module 'intern/dojo/Promise' {
import Promise = require('dojo/Promise');
export = Promise;
}
declare module 'intern/lib/util' {
export function getErrorMessage(error: any): string;
}
declare module 'intern/lib/reporters/Runner' {
import charm = require('charm')... | files(): string[];
}
export = Collector;
}
declare module 'istanbul/lib/report/json' {
import Collector = require('istanbul/lib/collector');
class JsonReporter {
constructor(options: any);
writeReport(collector: Collector, sync: boolean): void;
}
export = JsonReporter;
}
declare module 'istanbul/lib/ins... | declare module 'istanbul/lib/collector' {
class Collector {
add(coverage: any): void; | random_line_split |
tsd.d.ts | /// <reference path="intern/intern.d.ts" />
declare module 'intern/dojo/Promise' {
import Promise = require('dojo/Promise');
export = Promise;
}
declare module 'intern/lib/util' {
export function getErrorMessage(error: any): string;
}
declare module 'intern/lib/reporters/Runner' {
import charm = require('charm')... | {
constructor(options?: any);
instrumentSync(code: string, path: string): string;
lastFileCoverage(): any;
}
export = Instrumenter;
}
declare module 'istanbul/index' {
let result: any;
export = result;
}
declare module 'glob' {
const glob: {
(pattern: string, callback: (err: Error, matches: string[]) =... | Instrumenter | identifier_name |
borrowck-loan-rcvr-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
p.times(3);
}
fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p; //~ NOTE prior loan as mutable granted here
p + 3; // ok for... | {
self.x * self.y * z
} | identifier_body |
borrowck-loan-rcvr-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, z: &int) -> int {
self.x + self.y + (*z)
}
}
pub impl Point {
fn times(&self, z: int) -> int {
self.x * self.y * z
}
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
p.times(3);
}
fn b() {
let mut p = Point {x: 3, y: 4};
// H... | add | identifier_name |
borrowck-loan-rcvr-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p; //~ NOTE prior loan as mutable granted here
p + 3; // ok for pure fns
p.times(3); //~ ERROR loan of mutable local variable as immutable conflicts with prior loan
q.... | p.times(3);
}
| random_line_split |
tokio_server.rs | /* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" sig... |
// ...and a method inside the interface.
f.amethod("Hello", (), move |m| {
// This is the callback that will be called when another peer on the bus calls our method.
// the callback receives "MethodInfo" struct and can return either an error, or a list of
... | {
// Let's start by starting up a connection to the session bus and register a name.
let c = Rc::new(Connection::get_private(BusType::Session).unwrap());
c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap();
// The choice of factory tells us what type of tree we want,
... | identifier_body |
tokio_server.rs | /* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" sig... | () {
// Let's start by starting up a connection to the session bus and register a name.
let c = Rc::new(Connection::get_private(BusType::Session).unwrap());
c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap();
// The choice of factory tells us what type of tree we want,
... | main | identifier_name |
tokio_server.rs | /* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" sig... | core.run(server).unwrap();
} | // Make the server run forever
let server = server.for_each(|m| { println!("Unhandled message: {:?}", m); Ok(()) }); | random_line_split |
urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
#
# Copyright (c) 2008 University of Dundee.
#
# This program 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... | #
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008.
#
# Version: 1.0
#
from django.conf.urls import *
from omeroweb.webstart import views... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details. | random_line_split |
Divider.js | import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import { fade } from '../styles/colorManipulator';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
height: 1,
margin: 0, // Reset browse... | * If `true`, the divider will have a lighter color.
*/
light: PropTypes.bool,
/**
* The divider orientation.
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* @ignore
*/
role: PropTypes.string,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['fullWidth', 'in... | component: PropTypes.elementType,
/** | random_line_split |
TimelineSystem.js | var System = require('../entities/systems/System');
/**
* Manages entities with a TimelineComponent
* @example-link http://code.gooengine.com/latest/visual-test/goo/timelinepack/TimelineComponent/TimelineComponent-vtest.html Working example
*/
function TimelineSystem() {
System.call(this, 'TimelineSystem', ['Timel... | var entities = this._activeEntities;
for (var i = 0; i < entities.length; i++) {
var component = entities[i].timelineComponent;
component.pause();
}
};
/**
* Resumes updating the entities; an alias for `.play`
*/
TimelineSystem.prototype.resume = TimelineSystem.prototype.play;
/**
* Stop updating entities a... | * Stops updating the entities
*/
TimelineSystem.prototype.pause = function () {
this.passive = true; | random_line_split |
TimelineSystem.js | var System = require('../entities/systems/System');
/**
* Manages entities with a TimelineComponent
* @example-link http://code.gooengine.com/latest/visual-test/goo/timelinepack/TimelineComponent/TimelineComponent-vtest.html Working example
*/
function | () {
System.call(this, 'TimelineSystem', ['TimelineComponent']);
}
TimelineSystem.prototype = Object.create(System.prototype);
TimelineSystem.prototype.constructor = TimelineSystem;
TimelineSystem.prototype.process = function (entities, tpf) {
for (var i = 0; i < this._activeEntities.length; i++) {
var entity = t... | TimelineSystem | identifier_name |
TimelineSystem.js | var System = require('../entities/systems/System');
/**
* Manages entities with a TimelineComponent
* @example-link http://code.gooengine.com/latest/visual-test/goo/timelinepack/TimelineComponent/TimelineComponent-vtest.html Working example
*/
function TimelineSystem() |
TimelineSystem.prototype = Object.create(System.prototype);
TimelineSystem.prototype.constructor = TimelineSystem;
TimelineSystem.prototype.process = function (entities, tpf) {
for (var i = 0; i < this._activeEntities.length; i++) {
var entity = this._activeEntities[i];
entity.timelineComponent.update(tpf);
}... | {
System.call(this, 'TimelineSystem', ['TimelineComponent']);
} | identifier_body |
TimelineSystem.js | var System = require('../entities/systems/System');
/**
* Manages entities with a TimelineComponent
* @example-link http://code.gooengine.com/latest/visual-test/goo/timelinepack/TimelineComponent/TimelineComponent-vtest.html Working example
*/
function TimelineSystem() {
System.call(this, 'TimelineSystem', ['Timel... |
};
/**
* Resumes updating the entities
*/
TimelineSystem.prototype.play = function () {
this.passive = false;
var entities = this._activeEntities;
for (var i = 0; i < entities.length; i++) {
var component = entities[i].timelineComponent;
if (component.autoStart) {
component.start();
}
}
};
/**
* Stop... | {
var entity = this._activeEntities[i];
entity.timelineComponent.update(tpf);
} | conditional_block |
test_sourcepoint_interval.py | #!/usr/bin/env python
import glob
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness
from openmc.statepoint import StatePoint
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* files have been created."""
st... | harness = SourcepointTestHarness('statepoint.08.*')
harness.main() | conditional_block | |
test_sourcepoint_interval.py | #!/usr/bin/env python
import glob
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness
from openmc.statepoint import StatePoint | statepoint = glob.glob(os.path.join(os.getcwd(), 'statepoint.*'))
assert len(statepoint) == 5, '5 statepoint files must exist.'
assert statepoint[0].endswith('h5'), \
'Statepoint file is not a HDF5 file.'
def _get_results(self):
"""Digest info in the statepoint and retu... |
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* files have been created.""" | random_line_split |
test_sourcepoint_interval.py | #!/usr/bin/env python
import glob
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness
from openmc.statepoint import StatePoint
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* files have been created."""
st... |
if __name__ == '__main__':
harness = SourcepointTestHarness('statepoint.08.*')
harness.main()
| """Digest info in the statepoint and return as a string."""
# Read the statepoint file.
statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0]
sp = StatePoint(statepoint)
# Get the eigenvalue information.
outstr = TestHarness._get_results(self)
# Add the so... | identifier_body |
test_sourcepoint_interval.py | #!/usr/bin/env python
import glob
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness
from openmc.statepoint import StatePoint
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* files have been created."""
st... | (self):
"""Digest info in the statepoint and return as a string."""
# Read the statepoint file.
statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0]
sp = StatePoint(statepoint)
# Get the eigenvalue information.
outstr = TestHarness._get_results(self)
... | _get_results | identifier_name |
localization_manager.js | // Generated by CoffeeScript 1.9.3
var LocalizationManager, Polyglot, cozydb;
Polyglot = require('node-polyglot');
cozydb = require('cozydb');
LocalizationManager = (function() {
function | () {}
LocalizationManager.prototype.polyglot = null;
LocalizationManager.prototype.initialize = function(callback) {
if (callback == null) {
callback = function() {};
}
return this.ensureReady(callback);
};
LocalizationManager.prototype.setRenderer = function(renderer) {
return this.ren... | LocalizationManager | identifier_name |
localization_manager.js | // Generated by CoffeeScript 1.9.3
var LocalizationManager, Polyglot, cozydb;
Polyglot = require('node-polyglot');
cozydb = require('cozydb');
LocalizationManager = (function() {
function LocalizationManager() {}
LocalizationManager.prototype.polyglot = null;
LocalizationManager.prototype.initialize = functi... |
module.exports = new LocalizationManager(); | random_line_split | |
localization_manager.js | // Generated by CoffeeScript 1.9.3
var LocalizationManager, Polyglot, cozydb;
Polyglot = require('node-polyglot');
cozydb = require('cozydb');
LocalizationManager = (function() {
function LocalizationManager() {}
LocalizationManager.prototype.polyglot = null;
LocalizationManager.prototype.initialize = functi... |
return this.retrieveLocale((function(_this) {
return function(err, locale) {
var phrases;
if (err) {
return callback(err);
}
phrases = (function() {
try {
return require("../locales/" + locale);
} catch (_error) {
err = _er... | {
return callback(null, this.polyglot);
} | conditional_block |
localization_manager.js | // Generated by CoffeeScript 1.9.3
var LocalizationManager, Polyglot, cozydb;
Polyglot = require('node-polyglot');
cozydb = require('cozydb');
LocalizationManager = (function() {
function LocalizationManager() |
LocalizationManager.prototype.polyglot = null;
LocalizationManager.prototype.initialize = function(callback) {
if (callback == null) {
callback = function() {};
}
return this.ensureReady(callback);
};
LocalizationManager.prototype.setRenderer = function(renderer) {
return this.renderer... | {} | identifier_body |
dynamic_import_test.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | (LuigiTestCase):
def test_dynamic_loading(self):
interface = luigi.interface.DynamicArgParseInterface()
with tempfile.NamedTemporaryFile(dir='test/', prefix="_foo_module", suffix='.py') as temp_module_file:
temp_module_file.file.write(b'''
import luigi
class FooTask(luigi.Task):
x ... | CmdlineTest | identifier_name |
dynamic_import_test.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | self.assertEqual(task.x, 123)
temp_module = __import__(temp_module_name)
self.assertEqual(task.__class__, temp_module.FooTask)
self.assertEqual(task, temp_module.FooTask(x=123)) | random_line_split | |
dynamic_import_test.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
class CmdlineTest(LuigiTestCase):
def test_dynamic_loading(self):
interface = luigi.interface.DynamicArgParseInterface()
with tempfile.NamedTemporaryFile(dir='test/', prefix="_foo_module", suffix='.py') as temp_module_file:
temp_module_file.file.write(b'''
import luigi
class FooTask... | blah = luigi.Parameter(default=444) | identifier_body |
style.rs | // Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any... |
let (_, width) = Term::stdout().size();
let wrapper = Wrapper::new(width as usize)
.initial_indent(indent)
.subsequent_indent(indent);
wrapper.fill(msg)
}
| identifier_body | |
style.rs | // Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any... | //
// You should have received a copy of the GNU Lesser General Public License
// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.
//! Functions for setting styles on text, using console to make it look prettier.
use console::{style, StyledObject, Term};
use textwrap::Wrapper;
/// Displays a string ... | // Crowbook is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details. | random_line_split |
style.rs | // Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any... | msg: &str) -> StyledObject<&str> {
style(msg).cyan()
}
pub fn value(msg: &str) -> StyledObject<&str> {
style(msg).yellow()
}
pub fn fill(msg: &str, indent: &str) -> String {
let (_, width) = Term::stdout().size();
let wrapper = Wrapper::new(width as usize)
.initial_indent(indent)
.subs... | ipe( | identifier_name |
toolbar.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | constructor(toggleDropdownMenu: () => void) {
super(ToggleMenuAction.ID, nls.localize('more', "More"), null, true);
this.toggleDropdownMenu = toggleDropdownMenu;
}
public run(): TPromise<any> {
this.toggleDropdownMenu();
return TPromise.as(true);
}
public get menuActions() {
return this._menuActions;... | random_line_split | |
toolbar.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (container: HTMLElement, contextMenuProvider: IContextMenuProvider, options: IToolBarOptions = { orientation: ActionsOrientation.HORIZONTAL }) {
this.options = options;
this.lookupKeybindings = typeof this.options.getKeyBinding === 'function';
this.toggleMenuAction = new ToggleMenuAction(() => this.toggleMenuAct... | constructor | identifier_name |
toolbar.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
};
}
public dispose(): void {
this.actionBar.dispose();
this.toggleMenuAction.dispose();
if (this.toggleMenuActionItem) {
this.toggleMenuActionItem.dispose();
}
}
}
class ToggleMenuAction extends Action {
public static readonly ID = 'toolbar.toggle.more';
private _menuActions: IAction[];
privat... | {
this.actionBar.push(primaryAction, { icon: true, label: false, keybinding: this.getKeybindingLabel(primaryAction) });
} | conditional_block |
toolbar.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public getContainer(): Builder {
return this.actionBar.getContainer();
}
public setAriaLabel(label: string): void {
this.actionBar.setAriaLabel(label);
}
public setActions(primaryActions: IAction[], secondaryActions?: IAction[]): () => void {
return () => {
let primaryActionsToSet = primaryActions ? p... | {
this.actionBar.context = context;
if (this.toggleMenuActionItem) {
this.toggleMenuActionItem.setActionContext(context);
}
} | identifier_body |
main.py | # -*- coding: utf-8 -*-
"""
This plugin is 3rd party and not it is not part of the plexus-streams addon
Torrent-tv.ru (All categories)
"""
import sys,os
current_dir = os.path.dirname(os.path.realpath(__file__))
basename = os.path.basename(current_dir)
core_dir = current_dir.replace(basename,'').replace('parsers','... | else: categorie=match_cat[i]
if categorie not in dict_torrent.keys():
try:
dict_torrent[categorie] = [(channel_name[0],acehash)]
except: pass
else:
try:
dict_torrent[categorie].append(... | else:
if settings.getSetting('russian_translation') == "true": categorie = russiandictionary(match_cat[i]) | random_line_split |
main.py | # -*- coding: utf-8 -*-
"""
This plugin is 3rd party and not it is not part of the plexus-streams addon
Torrent-tv.ru (All categories)
"""
import sys,os
current_dir = os.path.dirname(os.path.realpath(__file__))
basename = os.path.basename(current_dir)
core_dir = current_dir.replace(basename,'').replace('parsers','... |
def torrenttv():
dict_torrent = {}
html_source = get_page_source(base_url)
match = re.compile('#EXTINF:-1,(.+?)\n(.*)').findall(html_source)
for title, acehash in match:
channel_name = re.compile('(.+?) \(').findall(title)
match_cat = re.compile('\((.+?)\)').findall(title)
for i in xrange(0,... | torrenttv_play(name,url) | conditional_block |
main.py | # -*- coding: utf-8 -*-
"""
This plugin is 3rd party and not it is not part of the plexus-streams addon
Torrent-tv.ru (All categories)
"""
import sys,os
current_dir = os.path.dirname(os.path.realpath(__file__))
basename = os.path.basename(current_dir)
core_dir = current_dir.replace(basename,'').replace('parsers','... | ():
dict_torrent = {}
html_source = get_page_source(base_url)
match = re.compile('#EXTINF:-1,(.+?)\n(.*)').findall(html_source)
for title, acehash in match:
channel_name = re.compile('(.+?) \(').findall(title)
match_cat = re.compile('\((.+?)\)').findall(title)
for i in xrange(0,len(match_cat)):
... | torrenttv | identifier_name |
main.py | # -*- coding: utf-8 -*-
"""
This plugin is 3rd party and not it is not part of the plexus-streams addon
Torrent-tv.ru (All categories)
"""
import sys,os
current_dir = os.path.dirname(os.path.realpath(__file__))
basename = os.path.basename(current_dir)
core_dir = current_dir.replace(basename,'').replace('parsers','... | dict_torrent[categorie].append((channel_name[0],acehash))
except: pass
for categories in dict_torrent.keys():
addDir(categories,str(dict_torrent),401,os.path.join(current_dir,"icon.png"),401,True,parser="torrenttvruall",parserfunction="channels")
def torrenttv_play
(name,url):
di... | dict_torrent = {}
html_source = get_page_source(base_url)
match = re.compile('#EXTINF:-1,(.+?)\n(.*)').findall(html_source)
for title, acehash in match:
channel_name = re.compile('(.+?) \(').findall(title)
match_cat = re.compile('\((.+?)\)').findall(title)
for i in xrange(0,len(match_cat)):
... | identifier_body |
tuple.rs |
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for... |
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {
let len = self.v.len();
if len == b.v.len() {
for i in 0..len {
let y = op_eq(env,&self.v[i],... | {
false
} | conditional_block |
tuple.rs | use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for ... | if self.v[i] != b.v[i] {return false;}
}
true
} else {
false
}
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {... | if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.