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 |
|---|---|---|---|---|
array_ops.py | u.ndim == 1:
sqmag = u.dot(u)
if sqmag >= EPS:
u /= sqmag ** 0.5
else:
if axis == 1:
sqmag = np.einsum("...ij,...ij->...i", u, u)
else:
sqmag = np.einsum("...ij,...ij->...j", u, u)
sqmag[sqmag < EPS] = 1.0
u /= np.expand_dims(np.s... |
def project_to_plane(vec_arr, norm):
"""Project array of vectors to plane with normal `norm`.
Parameters
----------
vec_arr : Nx3 array
Array of N 3D vectors.
norm : 1x3 array
Normal vector to plane.
Returns
-------
Nx3 array
Array of vectors projected onto p... | shape = list(a.shape)
shape[axis] -= 1
return a[: shape[0], : shape[1]] | conditional_block |
array_ops.py | .ndim == 1:
sqmag = u.dot(u)
if sqmag >= EPS:
u /= sqmag ** 0.5
else:
if axis == 1:
sqmag = np.einsum("...ij,...ij->...i", u, u)
else:
sqmag = np.einsum("...ij,...ij->...j", u, u)
sqmag[sqmag < EPS] = 1.0
u /= np.expand_dims(np.sqr... | (a, axis=1):
"""Return `a` with row removed along `axis`.
Parameters
----------
a : ndarray
Array from which to remove row
axis : int, optional
Axis from which to remove row
Returns
-------
ndarray
Unpadded array.
"""
if a.ndim == 1:
return a[:-1... | unpad_array | identifier_name |
ipynb.py | # -*- coding: utf-8 -*-
# Copyright © 2013-2015 Damián Avila, Chris Warrick and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
#... | elf, site):
"""Set Nikola site."""
self.logger = get_logger('compile_ipynb', STDERR_HANDLER)
super(CompileIPynb, self).set_site(site)
def compile_html_string(self, source, is_two_file=True):
"""Export notebooks as HTML strings."""
if flag is None:
req_missing(['i... | t_site(s | identifier_name |
ipynb.py | # -*- coding: utf-8 -*-
# Copyright © 2013-2015 Damián Avila, Chris Warrick and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
#... | metadata = {}
metadata.update(self.default_metadata)
metadata.update(kw)
makedirs(os.path.dirname(path))
if content.startswith("{"):
# imported .ipynb file, guaranteed to start with "{" because it’s JSON.
nb = nbformat.reads(content, current_nbformat)
... | # is_page is not needed to create the file
kw.pop('is_page', False)
| random_line_split |
ipynb.py | # -*- coding: utf-8 -*-
# Copyright © 2013-2015 Damián Avila, Chris Warrick and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
#... | at.write(nb, fd, 'ipynb')
| conditional_block | |
ipynb.py | # -*- coding: utf-8 -*-
# Copyright © 2013-2015 Damián Avila, Chris Warrick and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
#... | def compile_html(self, source, dest, is_two_file=True):
"""Compile source file into HTML and save as dest."""
makedirs(os.path.dirname(dest))
with io.open(dest, "w+", encoding="utf8") as out_file:
out_file.write(self.compile_html_string(source, is_two_file))
def read_metadat... | "Export notebooks as HTML strings."""
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
HTMLExporter.default_template = 'basic'
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
with io.open(so... | identifier_body |
overload.js | (function () {
'use strict';
// Processes overloads for a set of arguments. Should be called as
// via overload(arguments). You can pass it an array of arguments, but just using
// the built in arguments object is the intended use.
var Overload = function (args, expectedType) {
var _overload = this;
... |
}
return true;
}
function matchType(obj, typ) {
if (typeof typ === 'string' &&
typ.toUpperCase() === 'ANY') {
return true;
}
if (typeof typ === 'function' &&
(obj.constructor === typ || obj instanceof typ)) {
return true;
}
retur... | {
if (!matchType(test[i], types[i])) {
return false;
}
} | conditional_block |
overload.js | (function () {
'use strict';
// Processes overloads for a set of arguments. Should be called as
// via overload(arguments). You can pass it an array of arguments, but just using
// the built in arguments object is the intended use.
var Overload = function (args, expectedType) {
var _overload = this;
... | } else {
argArray.push(args[i]);
}
}
if (paramArray.length > 0) {
argArray.push(paramArray);
}
result = callback.apply(args.caller, argArray);
hasResult = true;
}
return _overload;
... | for (var i in args) {
if (lastAsArray && i >= types.length -1) {
paramArray.push(args[i]); | random_line_split |
overload.js | (function () {
'use strict';
// Processes overloads for a set of arguments. Should be called as
// via overload(arguments). You can pass it an array of arguments, but just using
// the built in arguments object is the intended use.
var Overload = function (args, expectedType) {
var _overload = this;
... |
};
function overload(args, expectedType) {
return new Overload(args, expectedType);
}
if (typeof window !== 'undefined') {
window.overload = overload;
} else {
module.exports = overload;
}
})(); | {
if (typeof typ === 'string' &&
typ.toUpperCase() === 'ANY') {
return true;
}
if (typeof typ === 'function' &&
(obj.constructor === typ || obj instanceof typ)) {
return true;
}
return false;
} | identifier_body |
overload.js | (function () {
'use strict';
// Processes overloads for a set of arguments. Should be called as
// via overload(arguments). You can pass it an array of arguments, but just using
// the built in arguments object is the intended use.
var Overload = function (args, expectedType) {
var _overload = this;
... | (types, test, extend) {
if (!extend && types.length !== test.length) {
return false;
}
if (types.length > test.length) {
return false;
}
for (var i in test) {
if (extend && i >= types.length) {
if (!matchType(test[i], types[types.length - 1])) {
... | matchTypes | identifier_name |
dnd.py | # -*- coding: utf-8 -*-
#===============================================================================
#
# Copyright 2013 Horacio Guillermo de Oro <hgdeoro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | app = wx.App(False)
frame = DnDFrame()
app.MainLoop() | conditional_block | |
dnd.py | # -*- coding: utf-8 -*-
#===============================================================================
#
# Copyright 2013 Horacio Guillermo de Oro <hgdeoro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | #
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
import datetime
import os
import wx
from gmp.garnisher import do_garnish, BORDER_SIZE_BOT... | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. | random_line_split |
dnd.py | # -*- coding: utf-8 -*-
#===============================================================================
#
# Copyright 2013 Horacio Guillermo de Oro <hgdeoro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | max_size=[int(x) for x in GMP_DEFAULT_MAX_SIZE.split('x')],
title=GMP_TITLE,
title_img=GMP_TITLE_IMAGE,
year=datetime.date.today().year,
technical_info=True,
exif_copyright=GMP_EXIF_COPYRIGHT,
rotate=0,
... | """
When files are dropped, write where they were dropped and then
the file paths themselves
"""
self.window.SetInsertionPointEnd()
self.window.clearText()
for filepath in filenames:
self.window.updateText(filepath + '\n')
self.window.updateText("... | identifier_body |
dnd.py | # -*- coding: utf-8 -*-
#===============================================================================
#
# Copyright 2013 Horacio Guillermo de Oro <hgdeoro@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | (self):
wx.Frame.__init__(self, parent=None, title="DnD for GMP")
panel = DnDPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = DnDFrame()
app.MainLoop()
| __init__ | identifier_name |
edit-project-dialog.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { Project, ProjectVariable } from '../../../models/project';
import { Server } from '../../../models/server';
import { Proj... |
addVariable() {
if (this.variableFormGroup.valid) {
let variable: ProjectVariable = {
name: this.variableFormGroup.get('name').value,
value: this.variableFormGroup.get('value').value,
};
this.variables = this.variables.concat([variable]);
} else {
this.toasterService.... | {
this.formGroup.controls['projectName'].setValue(this.project.name);
this.formGroup.controls['width'].setValue(this.project.scene_width);
this.formGroup.controls['height'].setValue(this.project.scene_height);
this.formGroup.controls['nodeGridSize'].setValue(this.project.grid_size);
this.formGroup.c... | identifier_body |
edit-project-dialog.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { Project, ProjectVariable } from '../../../models/project';
import { Server } from '../../../models/server';
import { Proj... | this.project.auto_close = !this.auto_close;
this.projectService.update(this.server, this.project).subscribe((project: Project) => {
this.toasterService.success(`Project ${project.name} updated.`);
this.onNoClick();
});
} else {
this.toasterService.error(`Fill all required fi... | this.project.scene_height = this.formGroup.get('height').value;
this.project.drawing_grid_size = this.formGroup.get('drawingGridSize').value;
this.project.grid_size = this.formGroup.get('nodeGridSize').value;
this.project.variables = this.variables;
| random_line_split |
edit-project-dialog.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { Project, ProjectVariable } from '../../../models/project';
import { Server } from '../../../models/server';
import { Proj... | else {
this.toasterService.error(`Fill all required fields with correct values.`);
}
}
}
| {
this.project.name = this.formGroup.get('projectName').value;
this.project.scene_width = this.formGroup.get('width').value;
this.project.scene_height = this.formGroup.get('height').value;
this.project.drawing_grid_size = this.formGroup.get('drawingGridSize').value;
this.project.grid_size ... | conditional_block |
edit-project-dialog.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { Project, ProjectVariable } from '../../../models/project';
import { Server } from '../../../models/server';
import { Proj... | () {
if (this.formGroup.valid) {
this.project.name = this.formGroup.get('projectName').value;
this.project.scene_width = this.formGroup.get('width').value;
this.project.scene_height = this.formGroup.get('height').value;
this.project.drawing_grid_size = this.formGroup.get('drawingGridSize').v... | onYesClick | identifier_name |
testplay.py | import alsaaudio
from math import pi, sin, pow
import getch
SAMPLE_RATE = 44100
FORMAT = alsaaudio.PCM_FORMAT_U8
PERIOD_SIZE = 512
N_SAMPLES = 1024
notes = "abcdefg"
frequencies = {}
for i, note in enumerate(notes):
frequencies[note] = 440 * pow(pow(2, 1/2), i)
# Generate the sine wave, centered at y=128 with 10... | (wave, frequency):
step = N_SAMPLES * frequency // SAMPLE_RATE
w = []
for i in range(0, PERIOD_SIZE):
w.append(wave[(step * i * N_SAMPLES // PERIOD_SIZE) % N_SAMPLES])
return w
if __name__ == '__main__':
main()
| make_wave | identifier_name |
testplay.py | import alsaaudio
from math import pi, sin, pow
import getch
SAMPLE_RATE = 44100
FORMAT = alsaaudio.PCM_FORMAT_U8
PERIOD_SIZE = 512
N_SAMPLES = 1024
notes = "abcdefg"
frequencies = {}
for i, note in enumerate(notes):
frequencies[note] = 440 * pow(pow(2, 1/2), i)
# Generate the sine wave, centered at y=128 with 10... |
if __name__ == '__main__':
main()
| step = N_SAMPLES * frequency // SAMPLE_RATE
w = []
for i in range(0, PERIOD_SIZE):
w.append(wave[(step * i * N_SAMPLES // PERIOD_SIZE) % N_SAMPLES])
return w | identifier_body |
testplay.py | import alsaaudio
from math import pi, sin, pow
import getch
SAMPLE_RATE = 44100
FORMAT = alsaaudio.PCM_FORMAT_U8
PERIOD_SIZE = 512
N_SAMPLES = 1024
notes = "abcdefg"
frequencies = {}
for i, note in enumerate(notes):
frequencies[note] = 440 * pow(pow(2, 1/2), i)
# Generate the sine wave, centered at y=128 with 10... |
elif char == '5':
buf = bytearray(w_half)
dev.write(buf)
dev.write(buf)
dev.write(buf)
last = char
char = getch.getch()
return 0
#def load_buf(buf, frequency):
# step = N_SAMPLES * frequency // SAMPLE_RATE
# for i in range(0, PERIOD_SIZE)... | w = [x//2 + 128 for x in make_wave(triangle_wave, 440)]
buf = bytearray(w) | conditional_block |
testplay.py | import alsaaudio
from math import pi, sin, pow
import getch
SAMPLE_RATE = 44100
FORMAT = alsaaudio.PCM_FORMAT_U8
PERIOD_SIZE = 512
N_SAMPLES = 1024
notes = "abcdefg"
frequencies = {}
for i, note in enumerate(notes):
frequencies[note] = 440 * pow(pow(2, 1/2), i)
# Generate the sine wave, centered at y=128 with 10... | if __name__ == '__main__':
main() | w.append(wave[(step * i * N_SAMPLES // PERIOD_SIZE) % N_SAMPLES])
return w
| random_line_split |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | bifurcateOwn( obj, { 'returns': {} }, predicate ); // $ExpectError
bifurcateOwn( obj, { 'returns': ( x: number ): number => x }, predicate ); // $ExpectError
}
// The compiler throws an error if the function is provided an invalid number of arguments...
{
const obj = new Foo();
bifurcateOwn(); // $ExpectError
bif... | random_line_split | |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | {
/**
* String property.
*/
a: string;
/**
* String property.
*/
b: string;
constructor() {
this.a = 'beep';
this.b = 'boop';
}
}
// TESTS //
// The function return an array of arrays...
{
const obj = new Foo();
bifurcateOwn( obj, predicate ); // $ExpectType any[][]
bifurcateOwn( {}, predicate );... | Foo | identifier_name |
15.4.4.15-3-16.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | return Array.prototype.lastIndexOf.call(obj, 2573) === 2573 &&
Array.prototype.lastIndexOf.call(obj, 0x000A0E) === -1;
}
runTestCase(testcase); | random_line_split | |
15.4.4.15-3-16.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... |
runTestCase(testcase);
| {
var obj = { 2573: 2573, 2574: 0x000A0E, length: "0x000A0E" };
return Array.prototype.lastIndexOf.call(obj, 2573) === 2573 &&
Array.prototype.lastIndexOf.call(obj, 0x000A0E) === -1;
} | identifier_body |
15.4.4.15-3-16.js | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this n... | () {
var obj = { 2573: 2573, 2574: 0x000A0E, length: "0x000A0E" };
return Array.prototype.lastIndexOf.call(obj, 2573) === 2573 &&
Array.prototype.lastIndexOf.call(obj, 0x000A0E) === -1;
}
runTestCase(testcase);
| testcase | identifier_name |
comment_editor.py | # -*- coding: utf-8 -*-
# wpcdesk - WordPress Comment Desktop
# Copyright (C) 2012 Eka Putra - ekaputra@balitechy.com
#
# 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 ... | self.delete_comment_thread.is_success.connect(self.delete_status)
def set_validator(self):
# Email Validator
email_pattern = QtCore.QRegExp( r"^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$" )
email_validator = QtGui.QRegExpValidator(email_pattern , self )
... | def __init__(self, parent=None, data=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_CommentWindow()
self.ui.setupUi(self)
self.ui.progressBar.hide()
self.set_validator()
self.parent = parent
self.data = data
self.fill_form(self.data)
Qt... | identifier_body |
comment_editor.py | # -*- coding: utf-8 -*-
# wpcdesk - WordPress Comment Desktop
# Copyright (C) 2012 Eka Putra - ekaputra@balitechy.com
#
# 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 ... |
else:
self.ui.cb_status.setChecked(False)
def saveComment(self):
data = {}
if self.ui.cb_status.isChecked():
data['status'] = 'approve'
else:
data['status'] = 'hold'
data['content'] = str(self.ui.edit_comment.toPlainText())
data['... | self.ui.cb_status.setChecked(True) | conditional_block |
comment_editor.py | # -*- coding: utf-8 -*-
# wpcdesk - WordPress Comment Desktop
# Copyright (C) 2012 Eka Putra - ekaputra@balitechy.com
#
# 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 ... | (self, status):
if status:
self.parent.loadComments()
QtGui.QMessageBox.information(self, 'Comment updated!','Comment successfuly updated.', QtGui.QMessageBox.Ok)
else:
QtGui.QMessageBox.warning(self, 'Failed!','Failed to update comment.', QtGui.QMessageBox.Ok)
d... | edit_status | identifier_name |
comment_editor.py | # -*- coding: utf-8 -*-
# wpcdesk - WordPress Comment Desktop
# Copyright (C) 2012 Eka Putra - ekaputra@balitechy.com
#
# 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 ... | # Email Validator
email_pattern = QtCore.QRegExp( r"^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$" )
email_validator = QtGui.QRegExpValidator(email_pattern , self )
self.ui.edit_email.setValidator(email_validator)
def fill_form(self, data):
self.comment_i... | random_line_split | |
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... | org/std/primitive.array.html
fn main() {
let nr_tel = stdinln_i32() as usize;
let mut tels: Vec<i32> = Vec::new();
for i in 0..nr_tel {
tels.push(stdinln_i32());
}
let mut problem = TelBox::new_from_vec_i32(tels, nr_tel);
// TelBox::get_most()를 완성해주세요!
println!("{:04}", problem.get_most());
} | i in 1..10000 {
if self.cntbox[i] > self.cntbox[biggest] {
biggest = i;
}else if self.cntbox[i] == self.cntbox[biggest] {
if i < biggest {
biggest = i;
}
}
}
biggest as u32
// End of TelBox::get_most()
}
}
// Rust에서는 array사용시 컴파일시간내에서만 결정되어야한다.
// 이 문제같은 경우 0~10000이라는 조건이 컴파일 시간이전에 결정... | identifier_body |
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... | identifier_name | ||
main.rs | use std::io;
fn stdinln_i32() -> i32 {
// 이 함수는 하나의 줄을 stdin으로 받아 단 하나의 integer를 리턴합니다.
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).expect("Failed to read stdin.");
buffer.trim().parse::<i32>().unwrap()
}
fn stdinln_vec_i32() -> Vec<i32> {
// 이 함수는 하나의 줄을 stdin으로 받아 여러개의 integer 을 vec... |
struct TelBox {
data: Vec<i32>,
nr_tel: usize,
cntbox: [u32; 10000], // 컴파일 시간내에 사이즈가 결정되는 어레이, Vector보다 빠르다
}
impl TelBox {
fn new_from_vec_i32(inputs: Vec<i32>, len: usize) -> TelBox {
TelBox{data:inputs, nr_tel:len, cntbox:[0; 10000]}
}
fn get_most(&mut self) -> u32 {
// TelBox::get_most() 를 완성해주세요!
f... | ret
} | random_line_split |
jcf.radio.js | /*!
* JavaScript Custom Forms : Radio Module
*
* Copyright 2014 PSD2HTML (http://psd2html.com)
* Released under the MIT license (LICENSE.txt)
*
* Version: 1.0.2
*/
;(function($, window) {
'use strict';
jcf.addModule({
name: 'Radio',
selector: 'input[type="radio"]',
options: {
wrapNative: true,
ch... |
},
getLabelFor: function() {
var parentLabel = this.realElement.closest('label'),
elementId = this.realElement.prop('id');
if(!parentLabel.length && elementId) {
parentLabel = $('label[for="' + elementId + '"]');
}
return parentLabel.length ? parentLabel : null;
},
refreshRadioGroup: funct... | {
return radio;
} | conditional_block |
jcf.radio.js | /*!
* JavaScript Custom Forms : Radio Module
*
* Copyright 2014 PSD2HTML (http://psd2html.com)
* Released under the MIT license (LICENSE.txt)
*
* Version: 1.0.2
*/
;(function($, window) {
'use strict';
jcf.addModule({
name: 'Radio',
selector: 'input[type="radio"]',
options: {
wrapNative: true,
ch... | },
getCurrentActiveRadio: function() {
return this.getRadioGroup(this.realElement).filter(':checked');
},
getRadioGroup: function(radio) {
// find radio group for specified radio button
var name = radio.attr('name'),
parentForm = radio.parents('form');
if(name) {
if(parentForm.length) {
... | this.doc.off('jcf-pointerup', this.onRelease); | random_line_split |
os.rs | use yaml_rust::{Yaml};
use yaml;
use regex::Regex;
///`OS` contains the operating system information from the user agent.
#[derive(Debug, PartialEq, Eq)]
pub struct OS {
pub family: String,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<Stri... | {
pub regex: Regex,
pub family: Option<String>,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<String>,
}
impl OSParser {
pub fn from_yaml(y: &Yaml) -> Option<OSParser> {
yaml::string_from_map(y, "regex")
.ma... | OSParser | identifier_name |
os.rs | use yaml_rust::{Yaml};
use yaml;
use regex::Regex;
///`OS` contains the operating system information from the user agent.
#[derive(Debug, PartialEq, Eq)]
pub struct OS {
pub family: String,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<Stri... | pub regex: Regex,
pub family: Option<String>,
pub major: Option<String>,
pub minor: Option<String>,
pub patch: Option<String>,
pub patch_minor: Option<String>,
}
impl OSParser {
pub fn from_yaml(y: &Yaml) -> Option<OSParser> {
yaml::string_from_map(y, "regex")
.map(|... | }
#[derive(Debug)]
pub struct OSParser { | random_line_split |
networking.py | !panic (later kernel!assfail):
0x20 e80b6c1400 CALL 0xff80091eeba0
# This is where it starts initializing the linked list:
0x25 48c70548e94000000000 MOV QWORD [RIP+0x40e948], 0x0
00
0x30 488d0d0e812900 LEA RCX, [RIP+0x29810e]
"""
name = "disassembled_llinfo_arp"
PA... | """Check IP Filters for hooks."""
__name = "ip_filters"
def render(self, renderer):
renderer.table_header([
("Context", "context", "10"),
("Filter", "filter", "16"),
("Handler", "handler", "[addrpad]"),
("Symbol", "symbol", "20")])
resolver = se... | identifier_body | |
networking.py | = "open_sockets"
type_name = "socket"
def collect(self):
for fileproc in self.session.plugins.collect("fileproc"):
if fileproc.fg_type == "DTYPE_SOCKET":
|
class DarwinNetstat(common.AbstractDarwinCommand):
"""Prints all open sockets we know about, from any source.
Netstat will display even connections that lsof doesn't know about, because
they were either recovered from an allocation zone, or found through a
secondary mechanism (like system call handl... | yield [fileproc.autocast_fg_data()] | conditional_block |
networking.py | = "open_sockets"
type_name = "socket"
def collect(self):
for fileproc in self.session.plugins.collect("fileproc"):
if fileproc.fg_type == "DTYPE_SOCKET":
yield [fileproc.autocast_fg_data()]
class DarwinNetstat(common.AbstractDarwinCommand):
"""Prints all open sockets ... | methods = []
for subclass in common.AbstractDarwinProducer.classes.itervalues():
# We look for a plugin which is a producer and a darwin command.
if (issubclass(subclass, common.AbstractDarwinCommand) and
issubclass(subclass, plugin.Producer) and
... | @classmethod
def methods(cls):
"""Return the names of available socket enumeration methods."""
# Find all the producers that collect procs and inherit from
# AbstractDarwinCachedProducer. | random_line_split |
networking.py | if (llinfo_arp_zone == NULL)
panic("%s: failed allocating llinfo_arp_zone", __func__);
zone_change(llinfo_arp_zone, Z_EXPAND, TRUE);
zone_change(llinfo_arp_zone, Z_CALLERACCT, FALSE);
arpinit_done = 1;
}
Disassembled, the first few instructions look like this:
... | calculate | identifier_name | |
fallback_chooser.py | """Pure TTY chooser UI"""
from __future__ import print_function, absolute_import
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "GNU GPL 2 or later"
import os
# Use readline if available but don't depend on it
try:
import readline
# Shut PyFlakes up
readline # pylint: disable=pointl... |
else:
print("Invalid result index: %d" % index)
return output, enqueue
| output.append(results[index - 1]) | conditional_block |
fallback_chooser.py | """Pure TTY chooser UI"""
from __future__ import print_function, absolute_import
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "GNU GPL 2 or later"
import os
# Use readline if available but don't depend on it
try:
import readline
# Shut PyFlakes up
readline # pylint: disable=pointl... | print("Not an integer or range: %s" % x)
return choices
# TODO: Document and, if necessary, refactor
def choose(results, strip_path, enqueue):
# Draw the menu
for pos, val in enumerate(results):
val = strip_path and os.path.basename(val) or val
print("%3d) %s" % (po... | """Parse a string containing one or more integers or Python ranges
separated by commas.
@returns: A list of integers
@attention: Unlike Python, this treats ranges as inclusive of the upper
bound.
"""
try:
return [int(in_str)]
except ValueError:
choices = []
for ... | identifier_body |
fallback_chooser.py | """Pure TTY chooser UI"""
from __future__ import print_function, absolute_import
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "GNU GPL 2 or later"
import os
# Use readline if available but don't depend on it
try:
import readline
# Shut PyFlakes up
readline # pylint: disable=pointl... | except ValueError:
print("Not an integer or range: %s" % x)
return choices
# TODO: Document and, if necessary, refactor
def choose(results, strip_path, enqueue):
# Draw the menu
for pos, val in enumerate(results):
val = strip_path and os.path.basename(val) or... | except ValueError:
try:
first, last = [int(y) for y in x.split(':', 1)]
choices.extend(range(first, last + 1)) | random_line_split |
fallback_chooser.py | """Pure TTY chooser UI"""
from __future__ import print_function, absolute_import
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "GNU GPL 2 or later"
import os
# Use readline if available but don't depend on it
try:
import readline
# Shut PyFlakes up
readline # pylint: disable=pointl... | (in_str):
"""Parse a string containing one or more integers or Python ranges
separated by commas.
@returns: A list of integers
@attention: Unlike Python, this treats ranges as inclusive of the upper
bound.
"""
try:
return [int(in_str)]
except ValueError:
choices = [... | parse_choice | identifier_name |
align.py | #!/usr/bin/env python3
"""
Copyright 2017 Ryan Wick (rrwick@gmail.com)
https://github.com/rrwick/Porechop
Porechop makes use of C++ functions which are compiled in cpp_functions.so. This module uses ctypes
to wrap them in similarly named Python functions.
This file is part of Porechop. Porechop is free software: you... | full_multiple_seq = [seq_full for seq_full in full_multiple_seq_all if len(seq_full) > int(min_length)]
if len(full_multiple_seq) > 1:
for split_seq in full_multiple_seq:
count += 1
sequence_new = Seq... | seq = str(sequence.seq)
sequence_match = seq[int(position[0]):int(position[1])]
multiple_seq = seq.split(sequence_match)
full_multiple_seq_all = [seq_full for seq_full in multiple_seq if seq_full != ""] | random_line_split |
align.py | #!/usr/bin/env python3
"""
Copyright 2017 Ryan Wick (rrwick@gmail.com)
https://github.com/rrwick/Porechop
Porechop makes use of C++ functions which are compiled in cpp_functions.so. This module uses ctypes
to wrap them in similarly named Python functions.
This file is part of Porechop. Porechop is free software: you... |
#print(dict_aln)
with ThreadPool(int(threads)) as pool:
for out in pool.imap(align, tqdm.tqdm(list_run)):
out_list = out.split(",")
#print(out_list)
if dict_aln[out_list[0]] != "":
if (float(out.split(",")[9])) > float(dict_aln[out_list[0]].split(",... | match_score = scoring_scheme_vals[0]
mismatch_score = scoring_scheme_vals[1]
gap_open_score = scoring_scheme_vals[2]
gap_extend_score = scoring_scheme_vals[3]
list_run.append([str(sequence.seq).encode('utf-8'), str(adapter.seq).encode('utf-8'), match_score,
... | conditional_block |
align.py | #!/usr/bin/env python3
"""
Copyright 2017 Ryan Wick (rrwick@gmail.com)
https://github.com/rrwick/Porechop
Porechop makes use of C++ functions which are compiled in cpp_functions.so. This module uses ctypes
to wrap them in similarly named Python functions.
This file is part of Porechop. Porechop is free software: you... | (command_in):
ptr = C_LIB.adapterAlignment(str(command_in[0]).encode('utf-8'), str(command_in[1]).encode('utf-8'),
command_in[2], command_in[3], command_in[4], command_in[5])
result_string = c_string_to_python_string(ptr)
single_result_string = result_string.split(",")
... | align | identifier_name |
align.py | #!/usr/bin/env python3
"""
Copyright 2017 Ryan Wick (rrwick@gmail.com)
https://github.com/rrwick/Porechop
Porechop makes use of C++ functions which are compiled in cpp_functions.so. This module uses ctypes
to wrap them in similarly named Python functions.
This file is part of Porechop. Porechop is free software: you... | gap_extend_score = scoring_scheme_vals[3]
list_run.append([str(sequence.seq).encode('utf-8'), str(adapter.seq).encode('utf-8'), match_score,
mismatch_score, gap_open_score, gap_extend_score, sequence.id, adapter.id])
#print(dict_aln)
with ThreadPool(int(thr... | """
Python wrapper for adapterAlignment C++ function.
"""
alignm_score_value = int(alignm_score_value)
sys.stdout.write("### STARTING ADAPTER ALIGNMENT AND READS ORIENTATION ###\n")
list_adapter = []
list_run = []
for adapter in SeqIO.parse(adapter_sequence, "fasta"):
list_adapter.ap... | identifier_body |
0013_auto_20160223_1757.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| ),
]
| dependencies = [
('main', '0012_auto_20160204_1503'),
]
operations = [
migrations.AlterModelOptions(
name='eventassignment',
options={'permissions': (('can_be_assigned', 'Can be assigned to events'),)},
),
migrations.AlterField(
model_name='su... | identifier_body |
0013_auto_20160223_1757.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
('main', '0012_auto_20160204_1503'),
]
operations = [
migrations.AlterModelOptions(
name='eventassignment',
options={'permissions': (('can_be_assigned', 'Can be assigned to events'),)},
),
migrations.AlterFiel... | Migration | identifier_name |
0013_auto_20160223_1757.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0012_auto_20160204_1503'),
]
operations = [
migrations.AlterModelOptions(
name='eventassignment',
options={'permissions': (('can_be_assigned', 'Can be assig... | random_line_split | |
__init__.py | ##########################################################################
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Copyright (c) 2010-2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary ... | # require IECore
import IECore
# our c++ module components
from _IECoreHoudini import *
# function sets
from FnParameterisedHolder import FnParameterisedHolder
from FnOpHolder import FnOpHolder
from FnProceduralHolder import FnProceduralHolder
# misc utility methods
from TestCase import TestCase
from TestProgram imp... | import hou
| random_line_split |
send_specific_registration_data_to_share.py | """ Sends specified registrations to SHARE """
import argparse
import json
import logging
import django
django.setup()
from osf.models import AbstractNode
from scripts import utils as script_utils
from website import settings
from website.app import setup_django
from website.project.tasks import update_node_share
lo... | (registrations):
assert settings.SHARE_URL, 'SHARE_URL must be set to migrate.'
assert settings.SHARE_API_TOKEN, 'SHARE_API_TOKEN must be set to migrate.'
registrations_count = len(registrations)
count = 0
logger.info('Preparing to migrate {} registrations.'.format(registrations_count))
for re... | migrate | identifier_name |
send_specific_registration_data_to_share.py | """ Sends specified registrations to SHARE """
import argparse
import json
import logging
import django
django.setup()
from osf.models import AbstractNode
from scripts import utils as script_utils
from website import settings
from website.app import setup_django
from website.project.tasks import update_node_share
lo... | main() | conditional_block | |
send_specific_registration_data_to_share.py | """ Sends specified registrations to SHARE """
import argparse
import json
import logging
import django
django.setup()
from osf.models import AbstractNode
from scripts import utils as script_utils
from website import settings
from website.app import setup_django
from website.project.tasks import update_node_share
lo... |
def main():
parser = argparse.ArgumentParser(
description='Changes the provider of specified Preprint objects'
)
parser.add_argument(
'--targets',
action='store',
dest='targets',
help='List of targets, of form ["registration_id", ...]',
)
pargs = parser.pa... | assert settings.SHARE_URL, 'SHARE_URL must be set to migrate.'
assert settings.SHARE_API_TOKEN, 'SHARE_API_TOKEN must be set to migrate.'
registrations_count = len(registrations)
count = 0
logger.info('Preparing to migrate {} registrations.'.format(registrations_count))
for registration_id in regi... | identifier_body |
send_specific_registration_data_to_share.py | """ Sends specified registrations to SHARE """
import argparse
import json
import logging
import django
django.setup()
from osf.models import AbstractNode
from scripts import utils as script_utils
from website import settings
from website.app import setup_django
from website.project.tasks import update_node_share
lo... |
def main():
parser = argparse.ArgumentParser(
description='Changes the provider of specified Preprint objects'
)
parser.add_argument(
'--targets',
action='store',
dest='targets',
help='List of targets, of form ["registration_id", ...]',
)
pargs = parser.pars... | update_node_share(registration)
logger.info('Registration {} was sent to SHARE.'.format(registration_id))
| random_line_split |
device_tracker.py | """Device tracker for Synology SRM routers."""
from __future__ import annotations
import logging
import synology_srm
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import (... |
attr = alias or attribute
filtered_attributes[attr] = value
return filtered_attributes
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
filter_named = [
result["hostname"] for result in self.devices i... | continue | conditional_block |
device_tracker.py | """Device tracker for Synology SRM routers."""
from __future__ import annotations
import logging
import synology_srm
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import (... | (DeviceScanner):
"""This class scans for devices connected to a Synology SRM router."""
def __init__(self, config):
"""Initialize the scanner."""
self.client = synology_srm.Client(
host=config[CONF_HOST],
port=config[CONF_PORT],
username=config[CONF_USERNAME... | SynologySrmDeviceScanner | identifier_name |
device_tracker.py | """Device tracker for Synology SRM routers."""
from __future__ import annotations
import logging
import synology_srm
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import (... | _LOGGER.error("Error with the Synology SRM: %s", ex)
return False
_LOGGER.debug("Found %d device(s) connected to the router", len(self.devices))
return True | random_line_split | |
device_tracker.py | """Device tracker for Synology SRM routers."""
from __future__ import annotations
import logging
import synology_srm
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import (... | """Check the router for connected devices."""
_LOGGER.debug("Scanning for connected devices")
try:
self.devices = self.client.core.get_network_nsm_device({"is_online": True})
except synology_srm.http.SynologyException as ex:
_LOGGER.error("Error with the Synology SRM: %s... | identifier_body | |
fuse.rs | // Copyright 2021 lowRISC contributors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
impl Fuse for FuseController {
fn get_dev_id(&self) -> u64 {
((self.registers.dev_id0.get() as u64) << 32)
| (self.registers.dev_id1.get() as u64)
}
}
| {
FuseController {
registers: base_addr,
}
} | identifier_body |
fuse.rs | // Copyright 2021 lowRISC contributors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
const FUSE_BASE_ADDR: u32 = 0x4045_0000;
const FUSE_REGISTERS: StaticRef<Registers> =
unsafe { StaticRef::new(FUSE_BASE_ADDR as *const Registers) };
pub static mut FUSE: FuseController = FuseController::new(FUSE_REGISTERS);
/// Fuse Controller
pub struct FuseController {
registers: StaticRef<Registers>,
}
i... | (0x004c => _reserved004c),
(0x0448 => @END),
}
} | random_line_split |
fuse.rs | // Copyright 2021 lowRISC contributors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (&self) -> u64 {
((self.registers.dev_id0.get() as u64) << 32)
| (self.registers.dev_id1.get() as u64)
}
}
| get_dev_id | identifier_name |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term.is_ascii_digit()
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u... |
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contains(&term)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
(0x30..=0x37).contains(&term)
}
///... | {
term.is_ascii_alphanumeric()
} | identifier_body |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline] | }
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u8) -> bool {
term.is_ascii_alphanumeric()
}
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contai... | pub fn digit(term: u8) -> bool {
term.is_ascii_digit() | random_line_split |
char_class.rs | /// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
term.is_ascii_alphabetic()
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term.is_ascii_digit()
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u... | (term: u8) -> bool {
(0x30..=0x39).contains(&term) || (0x41..=0x46).contains(&term) || (0x61..=0x66).contains(&term)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
(0x30..=0x37).contains(&term)
}
/// Recognises a space or tab.
#[inline]
pub fn space(term: u8) -> bool {
term ... | hex_digit | identifier_name |
axis_input_box_group.tsx | import React from "react";
import { AxisInputBox } from "./axis_input_box";
import { Row, Col } from "../ui";
import { AxisInputBoxGroupProps, AxisInputBoxGroupState } from "./interfaces";
import { isNumber } from "lodash";
import { Vector3 } from "farmbot";
import { t } from "../i18next_wrapper";
import { lockedClass ... | onChange={this.change}
axis={"x"}
value={x} />
<AxisInputBox
onChange={this.change}
axis={"y"}
value={y} />
<AxisInputBox
onChange={this.change}
axis={"z"}
value={z} />
<Col xs={3}>
<button
onClick={this.clicked}... |
return <Row>
<AxisInputBox | random_line_split |
axis_input_box_group.tsx | import React from "react";
import { AxisInputBox } from "./axis_input_box";
import { Row, Col } from "../ui";
import { AxisInputBoxGroupProps, AxisInputBoxGroupState } from "./interfaces";
import { isNumber } from "lodash";
import { Vector3 } from "farmbot";
import { t } from "../i18next_wrapper";
import { lockedClass ... | extends
React.Component<AxisInputBoxGroupProps, Partial<AxisInputBoxGroupState>> {
constructor(props: AxisInputBoxGroupProps) {
super(props);
this.state = {};
}
change = (axis: keyof Vector3, val: number) => {
this.setState({ [axis]: val });
}
get vector() {
const { x, y, z } = this.state... | AxisInputBoxGroup | identifier_name |
defaults-id_ID.min.js | /*!
|
!function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Tidak ada yang dipilih",noneR... | * Bootstrap-select v1.13.12 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2019 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
| random_line_split |
select_multiple_control_value_accessor.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ElementRef, OnDestroy, Provider, Renderer } from '@angular/core';
import { ControlValueAccessor } from './co... | implements OnDestroy {
private _element;
private _renderer;
private _select;
id: string;
constructor(_element: ElementRef, _renderer: Renderer, _select: SelectMultipleControlValueAccessor);
ngValue: any;
value: any;
ngOnDestroy(): void;
}
| NgSelectMultipleOption | identifier_name |
select_multiple_control_value_accessor.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved. | *
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ElementRef, OnDestroy, Provider, Renderer } from '@angular/core';
import { ControlValueAccessor } from './control_value_accessor';
export declare const SELECT_MULTIPLE_VA... | random_line_split | |
test_broker.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... |
@inlineCallbacks
def test_sasl_plain(self):
channel = yield self.client.channel(200)
yield channel.channel_open()
yield channel.channel_close()
class ASaslAmqPlainAuthenticationTest(TestBase):
"""Test for SASL AMQPLAIN authentication Broker functionality"""
@inlineCallbacks
... | yield client.authenticate(user, password,mechanism='PLAIN') | identifier_body |
test_broker.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... | ch.basic_publish(routing_key = "otherqueue", content = Content(body))
msg = yield ((yield self.client.queue(ctag)).get(timeout = 5))
ch.basic_ack(delivery_tag = msg.delivery_tag)
self.assert_(msg.content.body == body)
@inlineCallbacks
def test_basic_delivery_immediate(se... | random_line_split | |
test_broker.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... | (self,client,user,password):
yield client.authenticate(user, password,mechanism='PLAIN')
@inlineCallbacks
def test_sasl_plain(self):
channel = yield self.client.channel(200)
yield channel.channel_open()
yield channel.channel_close()
class ASaslAmqPlainAuthenticationTest(TestBas... | authenticate | identifier_name |
solarxyz.js | /**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module solarxyz
*/
/**
* Solarxyz: Chapter 26, Rectangular Coordinates of the Sun.
*/
import base from './base.js'
import nutation from './nutation.js'
import solar from './solar.js'
/**
* Position returns rectangular coordinates r... | const z = range * (ss * sε + sβ * cε)
return { x, y, z }
}
/**
* LongitudeJ2000 returns geometric longitude referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {Number} geometric longitude referenced to equinox J2000.
... | const [sε, cε] = base.sincos(nutation.meanObliquity(jde))
const [ss, cs] = base.sincos(lon)
const sβ = Math.sin(lat)
const x = range * cs
const y = range * (ss * cε - sβ * sε) | random_line_split |
solarxyz.js | /**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module solarxyz
*/
/**
* Solarxyz: Chapter 26, Rectangular Coordinates of the Sun.
*/
import base from './base.js'
import nutation from './nutation.js'
import solar from './solar.js'
/**
* Position returns rectangular coordinates r... | PositionJ2000 returns rectangular coordinates referenced to equinox J2000.
* @param {planetposition.Planet} earth - VSOP87Planet Earth
* @param {Number} jde - Julian ephemeris day
* @return {object} rectangular coordinates
* {Number} x
* {Number} y
* {Number} z
*/
export function positionJ2000 (earth, jde)... | lon = earth.position2000(jde).lon
return base.pmod(lon + Math.PI - 0.09033 / 3600 * Math.PI / 180, 2 * Math.PI)
}
/**
* | identifier_body |
solarxyz.js | /**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module solarxyz
*/
/**
* Solarxyz: Chapter 26, Rectangular Coordinates of the Sun.
*/
import base from './base.js'
import nutation from './nutation.js'
import solar from './solar.js'
/**
* Position returns rectangular coordinates r... | // (e *pp.V87Planet, jde float64) (x, y, z float64)
const { x, y, z } = xyz(earth, jde)
return {
x: 0.999925702634 * x + 0.012189716217 * y + 0.000011134016 * z,
y: -0.011179418036 * x + 0.917413998946 * y - 0.397777041885 * z,
z: -0.004859003787 * x + 0.397747363646 * y + 0.917482111428 * z
}
}
con... | arth, jde) { | identifier_name |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... |
pub fn init(&self, self_rc: Rc<Self>, rx: Receiver<State>, tx: Sender<Command>) {
let mut channels = self_rc.channels.borrow_mut();
channels.rx = Some(rx);
channels.tx = Some(tx);
self.build_widgets();
self.attach_handlers(&self_rc);
self.start_rendering_timer(&sel... | {
Rc::new(AppState{
channels: RefCell::new(AppChannels::new()),
widgets: RefCell::new(AppWidgets::new()),
model: RefCell::new(AppModel::new())
})
} | identifier_body |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... | {
state: State,
status: String,
playing: bool,
path: String,
is_dirty: bool
}
pub struct AppState {
channels: RefCell<AppChannels>,
widgets: RefCell<AppWidgets>,
model: RefCell<AppModel>
}
impl AppModel {
fn new() -> AppModel {
AppModel {
state: State::Initial,... | AppModel | identifier_name |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... | model.state = state;
model.status = format!("{}", state);
}
}
//println!("Checking...");
//Update the UI to reflect any changes
if self_clone.model.borrow().is_dirty {
println!("Model dirty. Rendering... | //let's assume we also got some name/value pairs with enough info to locate our widget and render it
//Modifying the model and updating it must be separate scopes
let mut model = self_clone.model.borrow_mut(); | random_line_split |
mod.rs | extern crate gtk;
mod glade;
mod handlers;
mod widgets;
use std::cell::{RefCell};
use gtk::prelude::*;
use gtk::{Window, WindowType};
use gtk::{Button, FileChooserDialog, Entry};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{Arc,Mutex};
use std::rc::Rc;
use std::clone::Clone;
use std::thread;
use castnow:... |
//println!("Checking...");
//Update the UI to reflect any changes
if self_clone.model.borrow().is_dirty {
println!("Model dirty. Rendering...");
self_clone.render_dirty();
}
//So this will get invoked on every tim... | {
while let Ok(state) = rx.try_recv() {
println!("Received state in ui thread {:?}", state);
//let's assume we also got some name/value pairs with enough info to locate our widget and render it
//Modifying the model and upda... | conditional_block |
client_updater.py | import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdo... | (server):
sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
broadcast_msg(server, '', "sizes", tmp)
while True:
logger.info("Participants viewing frontend:" + str(len(server.sockets)))
worksho... | workshops_monitor | identifier_name |
client_updater.py | import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdo... |
class RequestHandlerApp(object):
def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith('/socket.io'):
socketio_manage(environ, {'': QueueStatusHandler})
class QueueStatusHandler(BaseNamespace, BroadcastMixin):
def on_connect(self):
sizes = []
wo... | sizes = []
workshops = getAvailableWorkshops()
for w in workshops:
tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
broadcast_msg(server, '', "sizes", tmp)
while True:
logger.info("Participants viewing frontend:" + str(len(server.sockets)))
workshops_available =... | identifier_body |
client_updater.py | import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdo... | time.sleep(1)
class RequestHandlerApp(object):
def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith('/socket.io'):
socketio_manage(environ, {'': QueueStatusHandler})
class QueueStatusHandler(BaseNamespace, BroadcastMixin):
def on_connect(self):
... | broadcast_msg(server, '', 'sizes', wq)
logger.info("Workshops available:" + str(workshops_available)) | random_line_split |
client_updater.py | import sys
import time
import logging
from socketio import socketio_manage
from socketio.mixins import BroadcastMixin
from socketio.namespace import BaseNamespace
from DataAggregation.webdata_aggregator import getAvailableWorkshops
logger = logging.getLogger(__name__)
std_out_logger = logging.StreamHandler(sys.stdo... | tmp = [w.workshopName, w.q.qsize()]
sizes.append(tmp)
self.emit('sizes', tmp) | conditional_block | |
mdl-table.component.ts | import {
Component,
Input,
Output,
EventEmitter,
ViewEncapsulation
} from '@angular/core';
export interface IMdlTableColumn {
key: string;
name: string;
sortable?: boolean;
numeric?: boolean;
}
export interface IMdlTableModelItem {
selected: boolean;
}
export interface IMdlTableModel {
columns... |
public addAll(data: IMdlTableModelItem[]) {
this.data.push(...data);
}
}
const template = `
<table class="mdl-data-table">
<thead>
<tr>
<th *ngIf="selectable">
<mdl-checkbox mdl-ripple [ngModel]="isAllSelected()" (ngModelChange)="toogleAll()"></m... | {
this.columns = columns;
} | identifier_body |
mdl-table.component.ts | import {
Component,
Input,
Output,
EventEmitter,
ViewEncapsulation
} from '@angular/core';
export interface IMdlTableColumn {
key: string;
name: string;
sortable?: boolean;
numeric?: boolean;
}
export interface IMdlTableModelItem {
selected: boolean;
}
export interface IMdlTableModel {
columns... | <th *ngIf="selectable">
<mdl-checkbox mdl-ripple [ngModel]="isAllSelected()" (ngModelChange)="toogleAll()"></mdl-checkbox>
</th>
<th *ngFor="let column of model.columns"
[ngClass]="{'mdl-data-table__cell--non-numeric': !column.numeric}">
... | <thead>
<tr> | random_line_split |
mdl-table.component.ts | import {
Component,
Input,
Output,
EventEmitter,
ViewEncapsulation
} from '@angular/core';
export interface IMdlTableColumn {
key: string;
name: string;
sortable?: boolean;
numeric?: boolean;
}
export interface IMdlTableModelItem {
selected: boolean;
}
export interface IMdlTableModel {
columns... | {
@Input('table-model') public model: IMdlTableModel;
public selectable = false;
}
@Component({
selector: 'mdl-table-selectable',
template: template,
styles: styles,
encapsulation: ViewEncapsulation.None
})
export class MdlSelectableTableComponent extends MdlTableComponent {
@Input('table-model') pu... | MdlTableComponent | identifier_name |
application.js | ,userphotochange: true
,userprofilechange: true
}
,listeners:{
addcomment: function(){
this.fireEvent('newtimelineevent');
}
,removecomment: function(){
this.fireEvent('newtimelineevent');
}
... | {
if(typeof user.theme == 'string')
changeExtTheme(user.theme);
Ext.QuickTips.init();
/*
* qtip intercepts tooltip
*/
var qtip = Ext.QuickTips.getQuickTip();
qtip.interceptTitles = true;
eventManager = new Ext.ux.fbk.sonet.EventManager({
name: "taolin-even... | identifier_body | |
application.js | <span class="a" onclick="expandSettingsPanel()">Edit your settings</span>.',
'Did you know that you can expand fullscreen widgets clicking on <img width=20px height=1px src="'+Ext.BLANK_IMAGE_URL+'" class="x-tool x-tool-maximize" style="vertical-align:bottom;float:none;cursor:default;"/>? ',
'Did you k... | '<li class="header"><span class="a menu-item" onclick="showUserInfo(null, null, {source: \'logout_div\'})">Personal profile</span></li>' +
'<li class="header"><span class="menu-item a add_widgets" onclick="openAddWidgetsModalWindow()">Add widgets</span></li>' +
'<li clas... | random_line_split | |
application.js | (){
if(typeof user.theme == 'string')
changeExtTheme(user.theme);
Ext.QuickTips.init();
/*
* qtip intercepts tooltip
*/
var qtip = Ext.QuickTips.getQuickTip();
qtip.interceptTitles = true;
eventManager = new Ext.ux.fbk.sonet.EventManager({
name: "taolin-ev... | application_init | identifier_name | |
nodeinfo.py | #
# This file is part of bbhn-utils
#
# bbhn-utils is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# bbhn-utils is distributed in the hope that it w... | #!/usr/bin/env python3
# Copyright 2017-2018 Clayton Smith | random_line_split | |
nodeinfo.py | #!/usr/bin/env python3
# Copyright 2017-2018 Clayton Smith
#
# This file is part of bbhn-utils
#
# bbhn-utils is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later ... | app.run(host='0.0.0.0')
node_db.close() | conditional_block | |
nodeinfo.py | #!/usr/bin/env python3
# Copyright 2017-2018 Clayton Smith
#
# This file is part of bbhn-utils
#
# bbhn-utils is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later ... | ():
last_seen = node_db.last_seen(DISPLAY_HOURS)
return render_template('index.html', last_seen=last_seen)
@app.route('/link/<ip>.html')
def link_info(ip):
name = node_db.name(ip)
neighbours = node_db.neighbours(ip, DISPLAY_HOURS)
for i, neighbour in enumerate(neighbours):
cost = node_db.c... | node_info | identifier_name |
nodeinfo.py | #!/usr/bin/env python3
# Copyright 2017-2018 Clayton Smith
#
# This file is part of bbhn-utils
#
# bbhn-utils is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later ... |
if __name__ == '__main__':
app.run(host='0.0.0.0')
node_db.close()
| name = node_db.name(ip)
neighbours = node_db.neighbours(ip, DISPLAY_HOURS)
for i, neighbour in enumerate(neighbours):
cost = node_db.cost_history(ip, neighbour[1], DISPLAY_HOURS)
cost = [(ts.timestamp() * 1000, lq) for ts, lq in cost]
neighbours[i] = neighbour + (json.dumps(cost),)
r... | identifier_body |
view_mixins.py | from django.apps import apps as django_apps
from django.core.exceptions import ObjectDoesNotExist
from django.views.generic.base import ContextMixin
class SubjectOffstudyViewMixinError(Exception):
pass
class SubjectOffstudyViewMixin(ContextMixin):
"""Adds subject offstudy to the context.
Declare with ... |
raise SubjectOffstudyViewMixinError(e)
return subject_offstudy
| raise SubjectOffstudyViewMixinError(
f'Mixin must be declared together with SubjectIdentifierViewMixin. Got {e}') | conditional_block |
view_mixins.py | from django.apps import apps as django_apps
from django.core.exceptions import ObjectDoesNotExist
from django.views.generic.base import ContextMixin
class SubjectOffstudyViewMixinError(Exception):
pass
class SubjectOffstudyViewMixin(ContextMixin):
| # model_obj=self.subject_offstudy)
# context.update(subject_offstudy=wrapper)
# return context
@property
def subject_offstudy_model_cls(self):
try:
model_cls = django_apps.get_model(self.subject_offstudy_model)
except LookupError as e:
raise S... | """Adds subject offstudy to the context.
Declare with SubjectIdentifierViewMixin.
"""
offstudy_model_wrapper_cls = None
subject_offstudy_model = None
# def __init__(self, **kwargs):
# super().__init__(**kwargs)
# if not self.offstudy_model_wrapper_cls:
# raise SubjectO... | identifier_body |
view_mixins.py | from django.apps import apps as django_apps
from django.core.exceptions import ObjectDoesNotExist
from django.views.generic.base import ContextMixin
class SubjectOffstudyViewMixinError(Exception):
pass
class SubjectOffstudyViewMixin(ContextMixin):
"""Adds subject offstudy to the context.
Declare with ... | def subject_offstudy_model_cls(self):
try:
model_cls = django_apps.get_model(self.subject_offstudy_model)
except LookupError as e:
raise SubjectOffstudyViewMixinError(
f'Unable to lookup subject offstudy model. '
f'model={self.subject_offstudy_... |
@property | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.