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
celleditable.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
fn remove_widget(&self) { unsafe { ffi::gtk_cell_editable_remove_widget(GTK_CELL_EDITABLE(self.get_widget())) } } }
{ unsafe { ffi::gtk_cell_editable_editing_done(GTK_CELL_EDITABLE(self.get_widget())) } }
identifier_body
celleditable.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
// along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! Interface for widgets which can are used for editing cells use gtk::{mod, ffi}; use gtk::cast::GTK_CELL_EDITABLE; pub trait CellEditableTrait : gtk::WidgetTrait { fn editing_done(&self) { unsafe { ffi::gtk_cell_editable_editing_done(GTK...
random_line_split
celleditable.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
(&self) { unsafe { ffi::gtk_cell_editable_remove_widget(GTK_CELL_EDITABLE(self.get_widget())) } } }
remove_widget
identifier_name
adduser.js
module.exports = adduser var uuid = require("node-uuid") , crypto try { } catch (ex) {} function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function adduser (username, password, email, cb)
, password_sha : sha(password + salt) , email : email , _id : 'org.couchdb.user:'+username , type : "user" , roles : [] , date: new Date().toISOString() } cb = done.call(this, cb) this.log.verbose("adduser", "before first PUT", userobj) this.request('PUT' , '/-/user...
{ if (!crypto) crypto = require("crypto") password = ("" + (password || "")).trim() if (!password) return cb(new Error("No password supplied.")) email = ("" + (email || "")).trim() if (!email) return cb(new Error("No email address supplied.")) if (!email.match(/^[^@]+@[^\.]+\.[^\.]+/)) { return cb(new...
identifier_body
adduser.js
module.exports = adduser var uuid = require("node-uuid") , crypto try { } catch (ex) {} function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function adduser (username, password, email, cb) { if (!crypto) crypto = require("crypto") password = ("" + (password || "")).trim() if (!p...
return cb(er, data, json, response) } Object.keys(data).forEach(function (k) { if (!userobj[k]) { userobj[k] = data[k] } }) this.log.verbose("adduser", "userobj", userobj) this.request...
this.log.verbose("adduser", "update existing user") return this.request('GET' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) , function (er, data, json, response) { if (er || data.error) {
random_line_split
adduser.js
module.exports = adduser var uuid = require("node-uuid") , crypto try { } catch (ex) {} function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function adduser (username, password, email, cb) { if (!crypto) crypto = require("crypto") password = ("" + (password || "")).trim() if (!...
Object.keys(data).forEach(function (k) { if (!userobj[k]) { userobj[k] = data[k] } }) this.log.verbose("adduser", "userobj", userobj) this.request('PUT' , '/-/user/org.couchdb.user:'+encodeURICompo...
{ return cb(er, data, json, response) }
conditional_block
adduser.js
module.exports = adduser var uuid = require("node-uuid") , crypto try { } catch (ex) {} function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function
(username, password, email, cb) { if (!crypto) crypto = require("crypto") password = ("" + (password || "")).trim() if (!password) return cb(new Error("No password supplied.")) email = ("" + (email || "")).trim() if (!email) return cb(new Error("No email address supplied.")) if (!email.match(/^[^@]+@[^\....
adduser
identifier_name
environment_agents.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
} }
{ return new Agents(); }
conditional_block
environment_agents.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
{ uuid: Stream<string>; hostname: Stream<string>; readonly origin: Stream<Origin>; constructor(uuid: string, hostname: string, origin: Origin) { this.uuid = Stream(uuid); this.hostname = Stream(hostname); this.origin = Stream(origin); } static fromJSON(data: EnvironmentAgentJSON) { ...
AgentWithOrigin
identifier_name
environment_agents.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *
* distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Stream from "mithril/stream"; import {Origin, OriginJSON} ...
* Unless required by applicable law or agreed to in writing, software
random_line_split
environment_agents.ts
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
static fromJSON(data: EnvironmentAgentJSON) { return new AgentWithOrigin(data.uuid, data.hostname, Origin.fromJSON(data.origin)); } clone() { return new AgentWithOrigin(this.uuid(), this.hostname(), this.origin().clone()); } } export class Agents extends Array<AgentWithOrigin> { constructor(...age...
{ this.uuid = Stream(uuid); this.hostname = Stream(hostname); this.origin = Stream(origin); }
identifier_body
Mesh.ts
.ts"/> ///<reference path="./Face.ts"/> ///<reference path="./BuffersBox.ts"/> module WebGLEngine.Types { // TODO : refactor (Create material manager) export class
extends LinkedTransformations { public static defaultMaterialName = 'noMaterial'; public static maxVertexIndexValue = 21845; // unsigned short private _webGL : WebGLRenderingContext|any; private _vertexes : number[]; private _vertextTextures : number[]; private _vertexNormals : number[]; private _faces...
Mesh
identifier_name
Mesh.ts
.ts"/> ///<reference path="./Face.ts"/> ///<reference path="./BuffersBox.ts"/> module WebGLEngine.Types { // TODO : refactor (Create material manager) export class Mesh extends LinkedTransformations { public static defaultMaterialName = 'noMaterial'; public static maxVertexIndexValue = 21845; // unsigned short...
if (typeof materials !== 'undefined') { for (material in this._materials) { if (this._materials.hasOwnProperty(material)) { if (materials.hasOwnProperty(material)) { this._materials[material] = materials[material]; this._materials[material].callback(this._materialCallback); } ...
random_line_split
Mesh.ts
.ts"/> ///<reference path="./Face.ts"/> ///<reference path="./BuffersBox.ts"/> module WebGLEngine.Types { // TODO : refactor (Create material manager) export class Mesh extends LinkedTransformations { public static defaultMaterialName = 'noMaterial'; public static maxVertexIndexValue = 21845; // unsigned short...
public clone() { // TODO : finish clone } /** Sets create callback, that will called when mesh will be ready */ public callback(callback : Utils.Callback) : Mesh { this._createCallback.push(callback); if (this._isReady) { while (this._createCallback.length) { this._createCallback.shift().ap...
{ return this._isReady; }
identifier_body
Mesh.ts
.ts"/> ///<reference path="./Face.ts"/> ///<reference path="./BuffersBox.ts"/> module WebGLEngine.Types { // TODO : refactor (Create material manager) export class Mesh extends LinkedTransformations { public static defaultMaterialName = 'noMaterial'; public static maxVertexIndexValue = 21845; // unsigned short...
} public getBufferBoxes() : BuffersBox[] { return this._bufferBoxes; } public getMaterials() : {[key : string] : Material} { return this._materials; } public isReady() : boolean { return this._isReady; } public clone() { // TODO : finish clone } /** Sets create callback, that will ...
{ this._bufferBoxes.push(new BuffersBox(this._webGL, indexes, positions, normals, colors, textures, indexesPerMaterial)); }
conditional_block
outdated_tags.js
known wikipedia and wikidata tags Object.keys(d.brands).forEach(kvnd => { const brand = d.brands[kvnd]; const wd = brand.tags['brand:wikidata']; const wp = brand.tags['brand:wikipedia']; if (wd) { _nsi.wikidata[wd] = kvnd; } if (wp) { _nsi.wikipedia[wp] = kvnd; } });...
election.selectAll('.issue-reference') .data([0]) .enter() .append('div') .attr('class', 'issue-reference') .text(t('issues.old_multipolygon.reference')); } }
identifier_body
outdated_tags.js
olygon'; import { utilDisplayLabel, utilTagDiff } from '../util'; import { validationIssue, validationIssueFix } from '../core/validation'; let _dataDeprecated; let _nsi; export function validationOutdatedTags() { const type = 'outdated_tags'; const nsiKeys = ['amenity', 'shop', 'tourism', 'leisure', 'office']; ...
// for now skip ambiguous matches (like Target~(USA) vs Target~(Australia)) if (match.d) continue; const brand = _nsi.brands[match.kvnd]; if (brand && brand.tags['brand:wikidata'] && brand.tags['brand:wikidata'] !== entity.tags['not:brand:wikidata']) { su...
const center = entity.extent(graph).center(); const countryCode = countryCoder.iso1A2Code(center); const match = _nsi.matcher.matchKVN(k, newTags[k], newTags.name, countryCode && countryCode.toLowerCase()); if (!match) continue;
random_line_split
outdated_tags.js
olygon'; import { utilDisplayLabel, utilTagDiff } from '../util'; import { validationIssue, validationIssueFix } from '../core/validation'; let _dataDeprecated; let _nsi; export function validationOutdatedTags() { const type = 'outdated_tags'; const nsiKeys = ['amenity', 'shop', 'tourism', 'leisure', 'office']; ...
if (newTags.wikipedia) { newTags['brand:wikipedia'] = newTags.wikipedia; delete newTags.wikipedia; } // I considered setting `name` and other tags here, but they aren't unique per wikidata // (Q2759586 -> in USA "Papa John's", in Russia "Папа Джонс") // So us...
{ newTags['brand:wikidata'] = newTags.wikidata; delete newTags.wikidata; }
conditional_block
outdated_tags.js
olygon'; import { utilDisplayLabel, utilTagDiff } from '../util'; import { validationIssue, validationIssueFix } from '../core/validation'; let _dataDeprecated; let _nsi; export function validationOutdatedTags() { const type = 'outdated_tags'; const nsiKeys = ['amenity', 'shop', 'tourism', 'leisure', 'office']; ...
(entity, graph) { const oldTags = Object.assign({}, entity.tags); // shallow copy let preset = presetManager.match(entity, graph); let subtype = 'deprecated_tags'; if (!preset) return []; // upgrade preset.. if (preset.replacement) { const newPreset = presetManager.item(preset.replacemen...
oldTagIssues
identifier_name
stream.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return loop(); }); } loop(); }); } /** * Reads a file until a matching string is found. * * @param file The file to read. * @param matchingString The string to search for. * @param chunkBytes The number of bytes to read each iteration. * @param maximumBytesToRead The maximum number of bytes to rea...
{ fs.read(fd, buffer, bytesRead, totalBytes - bytesRead, null, (err, moreBytesRead) => { if (err) { return end(err, null, 0); } // Retry up to N times in case 0 bytes where read if (moreBytesRead === 0) { if (++zeroAttempts === 10) { return end(null, buffer, bytesRead); } ...
identifier_body
stream.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
loop(); }); } /** * Reads a file until a matching string is found. * * @param file The file to read. * @param matchingString The string to search for. * @param chunkBytes The number of bytes to read each iteration. * @param maximumBytesToRead The maximum number of bytes to read before giving up. * @param cal...
random_line_split
stream.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return callback(null, result); }); } let buffer = new Buffer(maximumBytesToRead); let bytesRead = 0; let zeroAttempts = 0; function loop(): void { fs.read(fd, buffer, bytesRead, chunkBytes, null, (err, moreBytesRead) => { if (err) { return end(err, null); } // Retry up to N time...
{ return callback(err, null); // we want to bubble this error up (file is actually a folder) }
conditional_block
stream.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): void { fs.read(fd, buffer, bytesRead, chunkBytes, null, (err, moreBytesRead) => { if (err) { return end(err, null); } // Retry up to N times in case 0 bytes where read if (moreBytesRead === 0) { if (++zeroAttempts === 10) { return end(null, null); } return loop(); ...
loop
identifier_name
QxSceneViewer_images.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="en_US"> <context> <name>@default</name> <message> <source>ICON_QXSCENE_RESET</source> <translation>qx_view_reset.png</translation> </message> <message> <source>ICON_QXSCENE_ZOOM</source> <tra...
<translation>qx_view_fitall.png</translation> </message> <message> <source>ICON_QXSCENE_FITAREA</source> <translation>qx_view_fitarea.png</translation> </message> </context> </TS>
<source>ICON_QXSCENE_FITALL</source>
random_line_split
iso2022.ts
import { Context, Recogniser } from '.'; import match, { Match } from '../match'; /** * This is a superclass for the individual detectors for * each of the detectable members of the ISO 2022 family * of encodings. */ class ISO_2022 implements Recogniser { escapeSequences: number[][] = []; name() { return...
language() { return 'ja'; } escapeSequences = [ [0x1b, 0x24, 0x28, 0x43], // KS X 1001:1992 [0x1b, 0x24, 0x28, 0x44], // JIS X 212-1990 [0x1b, 0x24, 0x40], // JIS C 6226-1978 [0x1b, 0x24, 0x41], // GB 2312-80 [0x1b, 0x24, 0x42], // JIS X 208-1983 [0x1b, 0x26, 0x40], // JIS X 208 1990...
export class ISO_2022_JP extends ISO_2022 { name() { return 'ISO-2022-JP'; }
random_line_split
iso2022.ts
import { Context, Recogniser } from '.'; import match, { Match } from '../match'; /** * This is a superclass for the individual detectors for * each of the detectable members of the ISO 2022 family * of encodings. */ class ISO_2022 implements Recogniser { escapeSequences: number[][] = []; name() { return...
misses++; } // Shift in/out if (text[i] == 0x0e || text[i] == 0x0f) shifts++; } if (hits == 0) return null; // // Initial quality is based on relative proportion of recognized vs. // unrecognized escape sequences. // All good: quality = 100; // half or l...
{ const seq = this.escapeSequences[escN]; if (textLen - i < seq.length) continue checkEscapes; for (j = 1; j < seq.length; j++) if (seq[j] != text[i + j]) continue checkEscapes; hits++; i += seq.length - 1; continue scanInput; }
conditional_block
iso2022.ts
import { Context, Recogniser } from '.'; import match, { Match } from '../match'; /** * This is a superclass for the individual detectors for * each of the detectable members of the ISO 2022 family * of encodings. */ class ISO_2022 implements Recogniser { escapeSequences: number[][] = []; name() { return...
() { return 'kr'; } escapeSequences = [[0x1b, 0x24, 0x29, 0x43]]; } export class ISO_2022_CN extends ISO_2022 { name() { return 'ISO-2022-CN'; } language() { return 'zh'; } escapeSequences = [ [0x1b, 0x24, 0x29, 0x41], // GB 2312-80 [0x1b, 0x24, 0x29, 0x47], // CNS 11643-1992 Plane 1 ...
language
identifier_name
newweave.rs
//! Writer for new weaves use std::{ collections::BTreeMap, fs::rename, io::{self, Write}, mem::replace, }; use crate::{header::Header, Error, NamingConvention, Result, WriterInfo}; #[allow(unused)] use crate::Compression; /// A builder for a new weave file. The data should be written as a writer. ...
(mut self) -> Result<()> { let temp = replace(&mut self.temp, None); let name = match temp { Some(mut wi) => { writeln!(&mut wi.writer, "\x01E 1")?; wi.name } None => return Err(Error::AlreadyClosed), }; let _ = rename(s...
close
identifier_name
newweave.rs
//! Writer for new weaves use std::{ collections::BTreeMap, fs::rename, io::{self, Write}, mem::replace, }; use crate::{header::Header, Error, NamingConvention, Result, WriterInfo}; #[allow(unused)] use crate::Compression; /// A builder for a new weave file. The data should be written as a writer. ...
let mut header: Header = Default::default(); let delta = header.add(ntags)?; header.write(&mut writeinfo.writer)?; writeln!(&mut writeinfo.writer, "\x01I {}", delta)?; Ok(NewWeave { naming: nc, temp: Some(writeinfo), }) } pub fn close(mut...
random_line_split
newweave.rs
//! Writer for new weaves use std::{ collections::BTreeMap, fs::rename, io::{self, Write}, mem::replace, }; use crate::{header::Header, Error, NamingConvention, Result, WriterInfo}; #[allow(unused)] use crate::Compression; /// A builder for a new weave file. The data should be written as a writer. ...
None => return Err(Error::AlreadyClosed), }; let _ = rename(self.naming.main_file(), self.naming.backup_file()); rename(name, self.naming.main_file())?; Ok(()) } } impl<'n> Write for NewWeave<'n> { // Write the data out, just passing it through to the underlying fil...
{ writeln!(&mut wi.writer, "\x01E 1")?; wi.name }
conditional_block
newweave.rs
//! Writer for new weaves use std::{ collections::BTreeMap, fs::rename, io::{self, Write}, mem::replace, }; use crate::{header::Header, Error, NamingConvention, Result, WriterInfo}; #[allow(unused)] use crate::Compression; /// A builder for a new weave file. The data should be written as a writer. ...
pub fn close(mut self) -> Result<()> { let temp = replace(&mut self.temp, None); let name = match temp { Some(mut wi) => { writeln!(&mut wi.writer, "\x01E 1")?; wi.name } None => return Err(Error::AlreadyClosed), }; ...
{ let mut writeinfo = nc.new_temp()?; let mut ntags = BTreeMap::new(); for (k, v) in tags { ntags.insert(k.to_owned(), v.to_owned()); } let mut header: Header = Default::default(); let delta = header.add(ntags)?; header.write(&mut writeinfo.writer)?; ...
identifier_body
chat.ts
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import { PresenceJSON, SendToJSON } from 'chat/chat-api-responses'; import MainView from 'chat/main-view'; import * as _ from 'lodash'; import C...
// initial population of channel/presence data dataStore.channelStore.updatePresence(presence); } reactTurbolinks.register('chat', MainView, () => { let initialChannel: number | undefined; const sendTo: SendToJSON = osu.parseJson('json-sendto'); if (!_.isEmpty(sendTo)) { const target = dataStore.userSto...
const dataStore = core.dataStore; const presence: PresenceJSON = osu.parseJson('json-presence'); if (!_.isEmpty(presence)) {
random_line_split
chat.ts
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import { PresenceJSON, SendToJSON } from 'chat/chat-api-responses'; import MainView from 'chat/main-view'; import * as _ from 'lodash'; import C...
else if (!target.is(core.currentUser)) { channel = Channel.newPM(target); channel.moderated = !sendTo.can_message; // TODO: move can_message to a user prop? dataStore.channelStore.channels.set(channel.channelId, channel); dataStore.channelStore.loaded = true; initialChannel = channel.chan...
{ initialChannel = channel.channelId; }
conditional_block
loadtrain.py
import numpy as np import fnmatch, os import h5py class Hdf5Loader(): def loadDirectory(self, dirname): """ Loads all hdf5 files in the directory dirname @param dirname: The directory which contains the files to load @returns: list of h5py File objects ""...
""" files = self.loadDirectory(dirname) result = [] for dataset_name in dataset_list: arr = np.concatenate([f[dataset_name] for f in files]) result.append(arr) return result class LoadData(): """ T...
@param dirname: The directory containing the hdf5 files @param dataset_list: List of datasets to load @returns: A list of numpy arrays loaded from the dataset files
random_line_split
loadtrain.py
import numpy as np import fnmatch, os import h5py class Hdf5Loader(): def loadDirectory(self, dirname): """ Loads all hdf5 files in the directory dirname @param dirname: The directory which contains the files to load @returns: list of h5py File objects ""...
def getPowerData(self,csvname): cols = [self.getFeatureCount(csvname)] power = np.loadtxt(csvname,delimiter=self.sep,skiprows=self.skiprows,usecols=cols) return power def load_dir(self, dirname): """ Loads all files of a directory to a single...
cols = range(self.skipcols, self.getFeatureCount(csvname)) print cols log = np.loadtxt(csvname,delimiter=self.sep,skiprows=self.skiprows,usecols=cols) return log
identifier_body
loadtrain.py
import numpy as np import fnmatch, os import h5py class Hdf5Loader(): def loadDirectory(self, dirname): """ Loads all hdf5 files in the directory dirname @param dirname: The directory which contains the files to load @returns: list of h5py File objects ""...
(): """ This class extracts data from features and corresponding powervalues and returns them as array """ def __init__(self, sep=";", groundtruth_elements=2, skiprows=1, skipcols=1): self.sep = sep self.num_groundtruth_elements = groundtruth_elements self.skiprows=1...
LoadData
identifier_name
loadtrain.py
import numpy as np import fnmatch, os import h5py class Hdf5Loader(): def loadDirectory(self, dirname): """ Loads all hdf5 files in the directory dirname @param dirname: The directory which contains the files to load @returns: list of h5py File objects ""...
return result class LoadData(): """ This class extracts data from features and corresponding powervalues and returns them as array """ def __init__(self, sep=";", groundtruth_elements=2, skiprows=1, skipcols=1): self.sep = sep self.num_groundt...
arr = np.concatenate([f[dataset_name] for f in files]) result.append(arr)
conditional_block
utils.js
function Utils() { //constructor } Utils.prototype = { constructor: Utils, goTo: function (hash, correct) { correct = (typeof correct !== 'undefined') ? correct : 0; $('html, body').animate({scrollTop: $(hash).offset().top-correct},500,function(){ window.location.hash = hash; ...
else { return ((elementTop <= pageBottom) && (elementBottom >= pageTop)); } }, prettyDate: function (time){ var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")), diff = (((new Date()).getTime() - date.getTime()) / 1000), day_diff = Math.fl...
{ return ((pageTop < elementTop) && (pageBottom > elementBottom)); }
conditional_block
utils.js
function
() { //constructor } Utils.prototype = { constructor: Utils, goTo: function (hash, correct) { correct = (typeof correct !== 'undefined') ? correct : 0; $('html, body').animate({scrollTop: $(hash).offset().top-correct},500,function(){ window.location.hash = hash; }); ...
Utils
identifier_name
utils.js
function Utils() { //constructor } Utils.prototype = { constructor: Utils, goTo: function (hash, correct) { correct = (typeof correct !== 'undefined') ? correct : 0; $('html, body').animate({scrollTop: $(hash).offset().top-correct},500,function(){ window.location.hash = hash; ...
day_diff < 7 && "Fa " + day_diff + " dies" || day_diff < 31 && "Fa " + Math.ceil( day_diff / 7 ) + " setmanes"; } }; var Utils = new Utils();
diff < 3600 && "Fa " + Math.floor( diff / 60 ) + " minuts" || diff < 7200 && "Fa 1 hora" || diff < 86400 && "Fa " + Math.floor( diff / 3600 ) + " hores") || day_diff == 1 && "Ahir" ||
random_line_split
utils.js
function Utils()
Utils.prototype = { constructor: Utils, goTo: function (hash, correct) { correct = (typeof correct !== 'undefined') ? correct : 0; $('html, body').animate({scrollTop: $(hash).offset().top-correct},500,function(){ window.location.hash = hash; }); }, isElementInView:...
{ //constructor }
identifier_body
theme.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { ActionBarModule, ActionModule, AutoCompleteEditorModule, BackdropModule, BoolEditorModule, CaptionModule, CellEditorModule, CellTooltipModule, ChangeDetectorModule, ...
ThemeComponent ], exports: [ ThemeComponent ], imports: [ CommonModule, FormsModule, TemplateModule, GridModule, DndModule, ResizeModule, ActionBarModule, ActionModule, AutoCompleteEditorModule, BackdropModul...
@NgModule({ declarations: [
random_line_split
theme.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { ActionBarModule, ActionModule, AutoCompleteEditorModule, BackdropModule, BoolEditorModule, CaptionModule, CellEditorModule, CellTooltipModule, ChangeDetectorModule, ...
(theme: ThemeService) { theme.name = 'basic'; theme.component = ThemeComponent; } }
constructor
identifier_name
dashboard.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Observable, Subject } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; import { TransferHttp } from '../../modules/transfer-http/transfer-http'; import { AppState } from '../redu...
ngOnInit() { this.form.get('name').setValue(this.user.name); if (UNIVERSAL) { this.testSub$ = this.http.get('http://localhost:8000/data').pipe(map(data => { return `${data.greeting} ${data.name}`; })); } } clearName() { this.store.dispatch(new UserActions.EditUser( Obje...
}); this.user$ = this.store.select(state => state.user.user); this.user$.pipe(takeUntil(this.destroyed$)) .subscribe(user => { this.user = user; }); }
random_line_split
dashboard.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Observable, Subject } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; import { TransferHttp } from '../../modules/transfer-http/transfer-http'; import { AppState } from '../redu...
() { this.form.get('name').setValue(this.user.name); if (UNIVERSAL) { this.testSub$ = this.http.get('http://localhost:8000/data').pipe(map(data => { return `${data.greeting} ${data.name}`; })); } } clearName() { this.store.dispatch(new UserActions.EditUser( Object.assign({...
ngOnInit
identifier_name
dashboard.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Observable, Subject } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; import { TransferHttp } from '../../modules/transfer-http/transfer-http'; import { AppState } from '../redu...
} clearName() { this.store.dispatch(new UserActions.EditUser( Object.assign({}, this.user, { name: '' } ))); this.form.get('name').setValue(''); } logout() { this.store.dispatch(new UserActions.Logout()); } submitState() { this.store.dispatch(new UserActions.EditUser( ...
{ this.testSub$ = this.http.get('http://localhost:8000/data').pipe(map(data => { return `${data.greeting} ${data.name}`; })); }
conditional_block
dashboard.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Observable, Subject } from 'rxjs'; import { map, takeUntil } from 'rxjs/operators'; import { TransferHttp } from '../../modules/transfer-http/transfer-http'; import { AppState } from '../redu...
ngOnDestroy() { this.destroyed$.next(); } }
{ this.store.dispatch(new UserActions.EditUser( Object.assign({}, this.user, { name: this.form.get('name').value } ))); }
identifier_body
tests.rs
use crate::direct_transport::{DirectTransport, DirectTransportOptions}; use crate::router::{Router, RouterOptions}; use crate::transport::Transport; use crate::worker::WorkerSettings; use crate::worker_manager::WorkerManager; use futures_lite::future; use std::env; async fn init() -> (Router, DirectTransport) { { ...
let _ = builder.is_test(true).try_init(); } let worker_manager = WorkerManager::new(); let worker = worker_manager .create_worker(WorkerSettings::default()) .await .expect("Failed to create worker"); let router = worker .create_router(RouterOptions::default())...
{ builder.filter_level(log::LevelFilter::Off); }
conditional_block
tests.rs
use crate::direct_transport::{DirectTransport, DirectTransportOptions}; use crate::router::{Router, RouterOptions}; use crate::transport::Transport; use crate::worker::WorkerSettings; use crate::worker_manager::WorkerManager; use futures_lite::future; use std::env; async fn init() -> (Router, DirectTransport) { { ...
#[test] fn router_close_event() { future::block_on(async move { let (router, transport) = init().await; let (mut close_tx, close_rx) = async_oneshot::oneshot::<()>(); let _handler = transport.on_close(Box::new(move || { let _ = close_tx.send(()); })); let (mut ...
}
random_line_split
tests.rs
use crate::direct_transport::{DirectTransport, DirectTransportOptions}; use crate::router::{Router, RouterOptions}; use crate::transport::Transport; use crate::worker::WorkerSettings; use crate::worker_manager::WorkerManager; use futures_lite::future; use std::env; async fn
() -> (Router, DirectTransport) { { let mut builder = env_logger::builder(); if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() { builder.filter_level(log::LevelFilter::Off); } let _ = builder.is_test(true).try_init(); } let worker_manager = WorkerManager::new(...
init
identifier_name
tests.rs
use crate::direct_transport::{DirectTransport, DirectTransportOptions}; use crate::router::{Router, RouterOptions}; use crate::transport::Transport; use crate::worker::WorkerSettings; use crate::worker_manager::WorkerManager; use futures_lite::future; use std::env; async fn init() -> (Router, DirectTransport)
let transport = router .create_direct_transport(DirectTransportOptions::default()) .await .expect("Failed to create transport1"); (router, transport) } #[test] fn router_close_event() { future::block_on(async move { let (router, transport) = init().await; let (mu...
{ { let mut builder = env_logger::builder(); if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() { builder.filter_level(log::LevelFilter::Off); } let _ = builder.is_test(true).try_init(); } let worker_manager = WorkerManager::new(); let worker = worker_mana...
identifier_body
YoutubeBatch.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
def getPlaylists(self, ch_id): return map(self.getPlaylist, self._getPlaylists(ch_id)) def _getVideosId(self, id, token=None): req = {"part": "contentDetails", "maxResults": "50", "playlistId": id} if token: req.update({"pageToken": token}) playlist = self.api_res...
req = {"part": "id", "maxResults": "50", "channelId": id} if token: req.update({"pageToken": token}) playlists = self.api_response("playlists", req) for playlist in playlists["items"]: yield playlist["id"] if "nextPageToken" in playlists: for item i...
identifier_body
YoutubeBatch.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
(Crypter): __name__ = "YoutubeBatch" __type__ = "crypter" __pattern__ = r"https?://(?:www\.)?(m\.)?youtube\.com/(?P<TYPE>user|playlist|view_play_list)(/|.*?[?&](?:list|p)=)(?P<ID>[\w-]+)" __version__ = "1.00" __description__ = """Youtube.com channel & playlist decrypter""" __config__ = [("likes"...
YoutubeBatch
identifier_name
YoutubeBatch.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
def _getPlaylists(self, id, token=None): req = {"part": "id", "maxResults": "50", "channelId": id} if token: req.update({"pageToken": token}) playlists = self.api_response("playlists", req) for playlist in playlists["items"]: yield playlist["id"] ...
playlist = playlists["items"][0] return {"id": p_id, "title": playlist["snippet"]["title"], "channelId": playlist["snippet"]["channelId"], "channelTitle": playlist["snippet"]["channelTitle"]}
conditional_block
YoutubeBatch.py
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
if not p_videos: continue elif "checkDups" in p: p_urls = [urlize(v_id) for v_id in p_videos if v_id not in addedvideos] self.logDebug("%s video\s available on playlist \"%s\" after duplicates cleanup" % (len(p_urls), p_name)) else: ...
self.logDebug("%s video\s found on playlist \"%s\"" % (len(p_videos), p_name))
random_line_split
htmlimageelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
(self, width: u32) { let elem: JSRef<Element> = ElementCast::from_ref(self); elem.set_uint_attribute(&atom!("width"), width) } fn Height(self) -> u32 { let node: JSRef<Node> = NodeCast::from_ref(self); let rect = node.get_bounding_content_box(); to_px(rect.size.height) a...
SetWidth
identifier_name
htmlimageelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
fn Width(self) -> u32 { let node: JSRef<Node> = NodeCast::from_ref(self); let rect = node.get_bounding_content_box(); to_px(rect.size.width) as u32 } fn SetWidth(self, width: u32) { let elem: JSRef<Element> = ElementCast::from_ref(self); elem.set_uint_attribute(&at...
{ let element: JSRef<Element> = ElementCast::from_ref(self); element.set_string_attribute(&atom!("ismap"), is_map.to_string()) }
identifier_body
htmlimageelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value.clone()), _ => (), } if atom!("src") == *name { self.update_image(None); } } fn parse_plain_attribute(...
self.update_image(Some((value, &url))); } }
random_line_split
net.rs
use {io}; use sys::unix::{nix, Io}; use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; pub use net::tcp::Shutdown; pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> { let opts = if nonblock { nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC } else { nix::S...
pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> { nix::bind(io.as_raw_fd(), addr) .map_err(super::from_nix_error) } pub fn listen(io: &Io, backlog: usize) -> io::Result<()> { nix::listen(io.as_raw_fd(), backlog) .map_err(super::from_nix_error) } pub fn accept(io: &Io, nonblock: ...
{ match nix::connect(io.as_raw_fd(), addr) { Ok(_) => Ok(true), Err(e) => { match e { nix::Error::Sys(nix::EINPROGRESS) => Ok(false), _ => Err(super::from_nix_error(e)) } } } }
identifier_body
net.rs
use {io}; use sys::unix::{nix, Io}; use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; pub use net::tcp::Shutdown; pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> { let opts = if nonblock { nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC } else { nix::S...
(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> { match nix::connect(io.as_raw_fd(), addr) { Ok(_) => Ok(true), Err(e) => { match e { nix::Error::Sys(nix::EINPROGRESS) => Ok(false), _ => Err(super::from_nix_error(e)) } } } } pu...
connect
identifier_name
net.rs
use {io}; use sys::unix::{nix, Io}; use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; pub use net::tcp::Shutdown; pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> { let opts = if nonblock { nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
nix::SOCK_CLOEXEC }; nix::socket(family, ty, opts, 0) .map_err(super::from_nix_error) } pub fn connect(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> { match nix::connect(io.as_raw_fd(), addr) { Ok(_) => Ok(true), Err(e) => { match e { nix::E...
} else {
random_line_split
0003_set_site_domain_and_name.py
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site d...
dependencies = [ ('sites', '0002_alter_domain_unique'), ] operations = [ migrations.RunPython(update_site_forward, update_site_backward), ]
class Migration(migrations.Migration):
random_line_split
0003_set_site_domain_and_name.py
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site d...
(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model('sites', 'Site') Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'example.com', 'name': 'example.com' } ) class Migration(migrations.Migra...
update_site_backward
identifier_name
0003_set_site_domain_and_name.py
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ from django.conf import settings from django.db import migrations def update_site_forward(apps, schema_editor): """Set site d...
dependencies = [ ('sites', '0002_alter_domain_unique'), ] operations = [ migrations.RunPython(update_site_forward, update_site_backward), ]
identifier_body
binary.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license //! Monte-Carlo simulation of a binary mixture of H20 and CO2. extern crate lumol; extern crate lumol_input as input; use lumol::Logger; use lumol::sys::{Molecule, Particle, Trajectory, UnitCell}; use lum...
{ Logger::stdout(); let mut system = Trajectory::open("data/binary.xyz") .and_then(|mut traj| traj.read()) .unwrap(); // Add bonds in the system for i in 0..system.molecules().len() / 3 { system.add_bond(3 * i, 3 * i + 1); ...
in()
identifier_name
binary.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license //! Monte-Carlo simulation of a binary mixture of H20 and CO2. extern crate lumol; extern crate lumol_input as input; use lumol::Logger; use lumol::sys::{Molecule, Particle, Trajectory, UnitCell}; use lum...
let h2o = { // Or define a new molecule by hand let mut molecule = Molecule::new(0); molecule.merge_with(Molecule::new(1)); molecule.merge_with(Molecule::new(2)); molecule.add_bond(0, 1); molecule.add_bond(1, 2); molecule_type(&molecule, &[Particle::new("H")...
Logger::stdout(); let mut system = Trajectory::open("data/binary.xyz") .and_then(|mut traj| traj.read()) .unwrap(); // Add bonds in the system for i in 0..system.molecules().len() / 3 { system.add_bond(3 * i, 3 * i + 1); ...
identifier_body
binary.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) 2015-2016 Lumol's contributors — BSD license //! Monte-Carlo simulation of a binary mixture of H20 and CO2. extern crate lumol; extern crate lumol_input as input; use lumol::Logger; use lumol::sys::{Molecule, Particle, Trajectory, UnitCell}; use lum...
use input::InteractionsInput; fn main() { Logger::stdout(); let mut system = Trajectory::open("data/binary.xyz") .and_then(|mut traj| traj.read()) .unwrap(); // Add bonds in the system for i in 0..system.molecules().len() / 3 { sy...
random_line_split
parser.rs
u64, pub offset: u64, pub longnames: &'a str, pub sparses: Vec<Sparse>, pub isextended: bool, pub realsize: u64, } #[derive(Debug,PartialEq,Eq)] pub struct Sparse { pub offset: u64, pub numbytes: u64 } #[derive(Debug,PartialEq,Eq)] pub struct Padding; /* * Useful macros...
(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> { chain!(i, prefix: parse_str155 ~ take!(12), ||{ UStarExtraHeader::PosixUStar(PosixUStarHeader { prefix: prefix }) } ) } fn parse_ustar00_extra<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IRe...
parse_ustar00_extra_posix
identifier_name
parser.rs
pub magic: &'a str, pub version: &'a str, pub uname: &'a str, pub gname: &'a str, pub devmajor: u64, pub devminor: u64, pub extra: UStarExtraHeader<'a> } #[derive(Debug,PartialEq,Eq)] pub enum UStarExtraHeader<'a> { PosixUStar(PosixUStarHeader<'a>), Pax(PaxHeader<'a>) }...
#[derive(Debug,PartialEq,Eq)] pub struct UStarHeader<'a> {
random_line_split
parser.rs
u64, pub offset: u64, pub longnames: &'a str, pub sparses: Vec<Sparse>, pub isextended: bool, pub realsize: u64, } #[derive(Debug,PartialEq,Eq)] pub struct Sparse { pub offset: u64, pub numbytes: u64 } #[derive(Debug,PartialEq,Eq)] pub struct Padding; /* * Useful macros...
fn parse_ustar00<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> I
{ match *flag { TypeFlag::PaxInterexchangeFormat => { chain!(i, mut header: parse_ustar00_extra_pax ~ apply!(parse_pax_extra_sparses, &mut header), ||{ UStarExtraHeader::Pax(header) } ) }, ...
identifier_body
ColorPicker.js
define("dojox/widget/nls/he/ColorPicker",{redLabel:"\u05d0",greenLabel:"\u05d9",blueLabel:"\u05db",hueLabel:"\u05d2",saturationLabel:"\u05e8",valueLabel:"\u05e2",degLabel:"\u00b0",hexLabel:"\u05d4\u05e7\u05e1",huePickerTitle:"\u05d1\u05d5\u05e8\u05e8 \u05d2\u05d5\u05d5\u05df",saturationPickerTitle:"\u05d1\u05d5\u05e8\u...
//>>built
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPygobject(PythonPackage): """bindings for the GLib, and GObject, to be used in Py...
depends_on('py-setuptools', type='build') depends_on('pkgconfig', type='build') depends_on("libffi") depends_on('glib') depends_on('python@2:2.99', when='@2:2.99', type=('build', 'run')) depends_on('py-pycairo', type=('build', 'run'), when='@3:') depends_on('py-py2cairo', type=('build', 'ru...
url='http://ftp.gnome.org/pub/GNOME/sources/pygobject/2.28/pygobject-2.28.3.tar.bz2') extends('python')
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPygobject(PythonPackage): """bindings for the GLib, and GObject, to be used in Py...
filter_file( r'Pycairo_IMPORT', r'//Pycairo_IMPORT', 'gi/pygi-foreign-cairo.c')
identifier_body
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPygobject(PythonPackage): """bindings for the GLib, and GObject, to be used in Py...
(self, spec, prefix): make('install', parallel=False) @when('^python@3:') def patch(self): filter_file( r'Pycairo_IMPORT', r'//Pycairo_IMPORT', 'gi/pygi-foreign-cairo.c')
install
identifier_name
InformationDispatcher.py
from vt_manager.controller.actions.ActionController import ActionController from vt_manager.controller.drivers.VTDriver import VTDriver from vt_manager.models.Action import Action from vt_manager.models.VirtualMachine import VirtualMachine import xmlrpclib, threading, logging, copy from vt_manager.communication.utils.X...
if not vtam_vms: raise Exception("VM not found") xmlrpc_server = xmlrpclib.Server(server.getAgentURL()) # Handle safely the connection against the agent try: server_active_vms = xmlrpc_server.force_l...
vmID = vtam_vms[0].getUUID() break
conditional_block
InformationDispatcher.py
from vt_manager.controller.actions.ActionController import ActionController from vt_manager.controller.drivers.VTDriver import VTDriver from vt_manager.models.Action import Action from vt_manager.models.VirtualMachine import VirtualMachine import xmlrpclib, threading, logging, copy from vt_manager.communication.utils.X...
if vmID != 'None': servers = VTDriver.getAllServers() vtam_vms = list() for server in servers: vtam_vms = server.getVMs(id=int(vmID)) if vtam_vms: ...
if serverID != 'None': server = VTDriver.getServerById(serverID) vtam_vms = server.getVMs() else:
random_line_split
InformationDispatcher.py
from vt_manager.controller.actions.ActionController import ActionController from vt_manager.controller.drivers.VTDriver import VTDriver from vt_manager.models.Action import Action from vt_manager.models.VirtualMachine import VirtualMachine import xmlrpclib, threading, logging, copy from vt_manager.communication.utils.X...
else: vms = server.getVMs() if not vms: logging.debug("No VMs available") if infoRspec.response.information.resources.server[sIndex].virtual_machine: infoRspec.response.information.resources.server[sIndex].virtual_machine.pop() elif (sliceUUID is not 'None'): vms = vms.filter(slice...
logging.debug("Enter listResources") infoRspec = XmlHelper.getSimpleInformation() servers = VTDriver.getAllServers() baseVM = copy.deepcopy(infoRspec.response.information.resources.server[0].virtual_machine[0]) if not servers: logging.debug("No VTServers available") infoRspec.response.information.resource...
identifier_body
InformationDispatcher.py
from vt_manager.controller.actions.ActionController import ActionController from vt_manager.controller.drivers.VTDriver import VTDriver from vt_manager.models.Action import Action from vt_manager.models.VirtualMachine import VirtualMachine import xmlrpclib, threading, logging, copy from vt_manager.communication.utils.X...
(sModel, sClass ): sClass.name = sModel.getName() #XXX: CHECK THIS sClass.id = sModel.id sClass.uuid = sModel.getUUID() sClass.operating_system_type = sModel.getOSType() sClass.operating_system_distribution = sModel.getOSDistribution() sClass.operating_system_version = sModel.getOSVersion() sClass.virtu...
__ServerModelToClass
identifier_name
__init__.py
RAAAA" "BGdBTUEAALGeYUxB9wAAACBjSFJNAAB6fAAAfosAAPoBAACHPAAAbUoAAPFDAAA2IAAAHlNX4WK7" "AAACYElEQVR42tTTPW8ScQDH8d/9n44HESgFKQjFWku1rUYdTEAT0sGHSU10cHZz0piYjqYxbia6" "+hB3Y0w3kzq0scaojdZqYiMp1dQWAlLg4A7ugbvzRXTy8wK+21dyXRe7QbBLuw6wG3ceJnJnLuTL" "279DrutySBIhEnUopSbjtMsYVzkXLSFEU5Y9dY/XW5N...
DPSock.sendto(eg.ParseString(eventString)+self.plugin.payDelim+eg.ParseString(payload),addr)
conditional_block
__init__.py
( name = "XBMC Event Receiver", author = "vortexrotor", version = "2.0.5", kind = "program", guid = "{9872BD49-2022-4F1B-B362-85F1ED203B7E}", description = ( "Receives events from XBMC Host UDP Broadcasts." ), url = "http://www.eventghost.net/forum/viewtopic.php?f=10&t=2140", ...
url_xbmc = "http://" + str(host_xbmc) + ":" + str(port_xbmc) + "/xbmcCmds/xbmcHttp?command=SetBroadcast&parameter=2;" + str(udp_xbmc) + "(Notification(" + v_header + "," + v_message + "))" print "str(url_xbmc)" try: urllib.urlopen(url_xbmc) except IOError:
random_line_split
__init__.py
I have used it as a basis for true 2-way control # too and from XBMC. The following improvements have been made to v2.0: # # - Enabled additional fields for configuration of HTTP.API destination in setup # - Enabled the invoking of XBMC Host Broadcast function with in the script # (so it is not necessary to do it ...
def handle_connect(self): print "XBMC Event Broadcast listener ENABLED on Local Host @ " + self.ipadd + ":" + str(self.port) + ". Response to XBMC is " + str(self.selfXbmceventbroadcast) + "." pass def handle_read(self): data, addr = self.recvfrom(1024) if (self.ipadd != addr...
elf.selfXbmceventbroadcast=selfXbmceventbroadcast self.plugin=plugin self.port=port self.payDelim=payDelim asyncore.dispatcher.__init__(self) self.ipadd = socket.gethostbyname(socket.gethostname()) self.create_socket(socket.AF_INET, socket.SOCK_DGRAM) eg.RestartAs...
identifier_body
__init__.py
I have used it as a basis for true 2-way control # too and from XBMC. The following improvements have been made to v2.0: # # - Enabled additional fields for configuration of HTTP.API destination in setup # - Enabled the invoking of XBMC Host Broadcast function with in the script # (so it is not necessary to do it ...
self): return False # we don't have anything to send ! class XbmceventbroadcastListener(eg.PluginClass): canMultiLoad = True text = Text def __init__(self): self.AddAction(self.Xbmceventbroadcast) def __start__(self, prefix=None, xbmcip="None", xbmchttpport=8080, zone="255.255.255.25...
ritable(
identifier_name
main.rs
fn main() { let mut ss = String::from("hello"); ss.push_str(", world!"); println!("{}", ss); // using the clone method the memory on heap for s1 is copied // for s2. This operation can be expensive in some cases. let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, ...
println!("x = {}, y = {}", x, y); // List of types that accept the Copy trait. // All the integer types, like u32. // The boolean type, bool, with values true and false. // All the floating point types, like f64. // Tuples, but only if they contain types that are also Copy. (i32, i32) // i...
// There is no difference between deep and shallow copying here. let x = 5; let y = x;
random_line_split
main.rs
fn main() { let mut ss = String::from("hello"); ss.push_str(", world!"); println!("{}", ss); // using the clone method the memory on heap for s1 is copied // for s2. This operation can be expensive in some cases. let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, ...
: String) -> (String, usize) { let length = s.len(); // len() returns the length of a String. (s, length) } fn takes_ownership(some_string: String) { // some_string comes into scope. println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is ...
lculate_length(s
identifier_name
main.rs
fn main()
// List of types that accept the Copy trait. // All the integer types, like u32. // The boolean type, bool, with values true and false. // All the floating point types, like f64. // Tuples, but only if they contain types that are also Copy. (i32, i32) // is Copy, but (i32, String) is not. ...
{ let mut ss = String::from("hello"); ss.push_str(", world!"); println!("{}", ss); // using the clone method the memory on heap for s1 is copied // for s2. This operation can be expensive in some cases. let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, s2 = {}", ...
identifier_body
extract_elp_prons.py
#!/usr/bin/env python """ Extract pronunciations from the ELP items. Outputs a CSV with the orthographic and phonological form on each line. The phonological form is stripped of syllabification and stress markers. """ # Copyright 2013 Constantine Lignos # # Licensed under the Apache License, Version 2.0 (the "Licens...
else: n_phon = entry.nphon # Perform phoneme replacement on the pron pron = replace_phons(pron) # Remove stress/syllable markers pron = pron.translate(None, DELETION_CHARS) # Check that length matches if len(pron) !=...
continue
conditional_block
extract_elp_prons.py
#!/usr/bin/env python """ Extract pronunciations from the ELP items. Outputs a CSV with the orthographic and phonological form on each line. The phonological form is stripped of syllabification and stress markers. """ # Copyright 2013 Constantine Lignos # # Licensed under the Apache License, Version 2.0 (the "Licens...
words = sorted(elp.keys(), key=lambda s: s.lower()) count = 0 for word in words: entry = elp[word] # Extract orthography and pron pron = entry.pron nsyll = entry.nsyll # Match syllable numbers if specified if target_sylls i...
# Sort by lowercase version of entry
random_line_split
extract_elp_prons.py
#!/usr/bin/env python """ Extract pronunciations from the ELP items. Outputs a CSV with the orthographic and phonological form on each line. The phonological form is stripped of syllabification and stress markers. """ # Copyright 2013 Constantine Lignos # # Licensed under the Apache License, Version 2.0 (the "Licens...
(pron): """Replace phonemes using the PHON_REPLACEMENTS table.""" for replacement in PHON_REPLACEMENTS: pron = pron.replace(*replacement) return pron def extract(input_path, output_path, mono_only, cmudict_format, target_sylls): """Extract words from the input path and write them to the output...
replace_phons
identifier_name
extract_elp_prons.py
#!/usr/bin/env python """ Extract pronunciations from the ELP items. Outputs a CSV with the orthographic and phonological form on each line. The phonological form is stripped of syllabification and stress markers. """ # Copyright 2013 Constantine Lignos # # Licensed under the Apache License, Version 2.0 (the "Licens...
# Skip NULL prons, get the length if there is a pron. if pron == NULL: continue else: n_phon = entry.nphon # Perform phoneme replacement on the pron pron = replace_phons(pron) # Remove stress/syllable markers ...
"""Extract words from the input path and write them to the output.""" with open(output_path, 'wb') as output_file: elp = ELP(input_path) # Sort by lowercase version of entry words = sorted(elp.keys(), key=lambda s: s.lower()) count = 0 for word in words: entry =...
identifier_body
tests.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use quickcheck::quickcheck; use crate::Bytes; use crate::Text; quickcheck! { fn test_shallow_clone(v: Vec<u8>) -> bool { let ...
Text = SAMPLE_TEXT.into(); let b = a.slice(3..12); let s: &str = b.as_ref(); let c = a.slice_to_bytes(s); let d = b.slice_to_bytes(s); assert_eq!(b.as_ptr(), c.as_ptr()); assert_eq!(b.as_ptr(), d.as_ptr()); } #[test] fn test_text_to_string() { let a: Text = SAMPLE_TEXT.into(); assert_eq...
valid() { let a:
identifier_name
tests.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use quickcheck::quickcheck; use crate::Bytes; use crate::Text; quickcheck! { fn test_shallow_clone(v: Vec<u8>) -> bool { let ...
t_text_to_string() { let a: Text = SAMPLE_TEXT.into(); assert_eq!(a.to_string(), SAMPLE_TEXT.to_string()); } #[test] #[should_panic] fn test_text_slice_invalid() { let a: Text = SAMPLE_TEXT.into(); let _b = a.slice(3..11); // invalid utf-8 boundary } #[test] fn test_downcast_mut() { let v = b"abcd...
t = SAMPLE_TEXT.into(); let b = a.slice(3..12); let s: &str = b.as_ref(); let c = a.slice_to_bytes(s); let d = b.slice_to_bytes(s); assert_eq!(b.as_ptr(), c.as_ptr()); assert_eq!(b.as_ptr(), d.as_ptr()); } #[test] fn tes
identifier_body
ReleaseAnnotationUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { AzureAppService } from '../azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights, ApplicationInsightsResources} from '../azure-arm-rest/azure-arm-appinsights'; import { AzureEndpoint } from '../azure-arm-rest/azureModels'; var uuidV4 = r...
(isDeploymentSuccess: boolean): {[key: string]: any} { let annotationName = "Release Annotation"; let releaseUri = tl.getVariable("Release.ReleaseUri"); let buildUri = tl.getVariable("Build.BuildUri"); if (!!releaseUri) { annotationName = `${tl.getVariable("Release.DefinitionName")} - ${tl.getV...
getReleaseAnnotation
identifier_name
ReleaseAnnotationUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { AzureAppService } from '../azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights, ApplicationInsightsResources} from '../azure-arm-rest/azure-arm-appinsights'; import { AzureEndpoint } from '../azure-arm-rest/azureModels'; var uuidV4 = r...
else { tl.debug(`Unable to find Application Insights resource with Instrumentation key ${instrumentationKey}. Skipping adding release annotation.`); } } else { tl.debug(`Application Insights is not configured for the App Service. Skipping adding relea...
{ var appInsights: AzureApplicationInsights = new AzureApplicationInsights(endpoint, appInsightsResources[0].id.split('/')[4], appInsightsResources[0].name); var releaseAnnotationData = getReleaseAnnotation(isDeploymentSuccess); await appInsights.addReleaseAnnotation(rele...
conditional_block
ReleaseAnnotationUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { AzureAppService } from '../azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights, ApplicationInsightsResources} from '../azure-arm-rest/azure-arm-appinsights'; import { AzureEndpoint } from '../azure-arm-rest/azureModels'; var uuidV4 = r...
} catch(error) { console.log(tl.loc("FailedAddingReleaseAnnotation", error)); } } function getReleaseAnnotation(isDeploymentSuccess: boolean): {[key: string]: any} { let annotationName = "Release Annotation"; let releaseUri = tl.getVariable("Release.ReleaseUri"); let buildUri = tl.getV...
{ try { var appSettings = await azureAppService.getApplicationSettings(); var instrumentationKey = appSettings && appSettings.properties && appSettings.properties.APPINSIGHTS_INSTRUMENTATIONKEY; if(instrumentationKey) { let appinsightsResources: ApplicationInsightsResources = new...
identifier_body
ReleaseAnnotationUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { AzureAppService } from '../azure-arm-rest/azure-arm-app-service'; import { AzureApplicationInsights, ApplicationInsightsResources} from '../azure-arm-rest/azure-arm-appinsights'; import { AzureEndpoint } from '../azure-arm-rest/azureModels'; var uuidV4 = r...
let collectionUrl = tl.getVariable('System.TeamFoundationCollectionUri'); let teamProject = tl.getVariable('System.TeamProjectId'); let buildId = tl.getVariable('build.buildId'); if (!!releaseWebUrl) { return releaseWebUrl; } if (!!buildUri) { return `${collectionUrl}${teamProj...
} function getDeploymentUri(): string { let buildUri = tl.getVariable("Build.BuildUri"); let releaseWebUrl = tl.getVariable("Release.ReleaseWebUrl");
random_line_split
__init__.py
coding: UTF-8 -*- # Pluma External Tools plugin # Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net> # # 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 2 ...
<menu name="ExternalToolsMenu" action="ExternalTools"> <placeholder name="ExternalToolPlaceholder"/> </menu> <separator/> </placeholder> <placeholder name="ToolsOps_5"> <menuitem n...
<ui> <menubar name="MenuBar"> <menu name="ToolsMenu" action="Tools"> <placeholder name="ToolsOps_4"> <separator/>
random_line_split
__init__.py
coding: UTF-8 -*- # Pluma External Tools plugin # Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net> # # 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 2 ...
self, accelmap, path, key, mod, tool): tool.shortcut = gtk.accelerator_name(key, mod) tool.save() self._window.get_data("ExternalToolsPluginWindowData").update_manager(tool) def update(self): self.remove() self._merge_id = self._window.get_ui_manager().new_merge_id(...
n_accelmap_changed(
identifier_name
__init__.py
coding: UTF-8 -*- # Pluma External Tools plugin # Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net> # # 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 2 ...
if not language and 'plain' in item.languages: return True if language and (language.get_id() in item.languages): return True else: return False def filter(self, document): if document is None: return titled ...
eturn True
conditional_block
__init__.py
coding: UTF-8 -*- # Pluma External Tools plugin # Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net> # # 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 2 ...
def update_ui(self, window): window.get_data(self.WINDOW_DATA_KEY).update_ui() def create_configure_dialog(self): return self.open_dialog() def open_dialog(self): if not self._manager: self._manager = Manager(self.get_data_dir()) if self._manager_default_s...
indow.get_data(self.WINDOW_DATA_KEY).deactivate() window.set_data(self.WINDOW_DATA_KEY, None)
identifier_body
local.py
"""Development settings and globals.""" from os.path import join, normpath from base import * ########## LOCAL DATABASE CONFIGURATION, OVERIDES BASE # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': joi...
} ########## END CACHE CONFIGURATION ########## TOOLBAR CONFIGURATION # See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation INSTALLED_APPS += ( 'debug_toolbar', 'django_extensions', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } # See: https://github.com/django-deb...
CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }
random_line_split