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
GetJobDocumentsResponse.py
#!/usr/bin/env python """ Copyright 2012 GroupDocs. 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...
self.swaggerTypes = { 'result': 'GetJobDocumentsResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'int' } self.result = None # GetJobDocumentsResult self.status = None # str self.error_message = None # str self.comp...
identifier_body
largeTextCellEditor.d.ts
// Type definitions for ag-grid v7.1.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ceolter/> import { ICellEditor } from "./iCellEditor"; import { ICellEditorParams } from "./iCellEditor"; import { Component } from "../../widgets/component"; import { ICellRenderer } from "../...
extends Component implements ICellEditor { private static TEMPLATE; private params; private textarea; private focusAfterAttached; constructor(); init(params: ILargeTextEditorParams): void; private onKeyDown(event); afterGuiAttached(): void; getValue(): any; isPopup(): boolean; }...
LargeTextCellEditor
identifier_name
largeTextCellEditor.d.ts
// Type definitions for ag-grid v7.1.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ceolter/> import { ICellEditor } from "./iCellEditor"; import { ICellEditorParams } from "./iCellEditor"; import { Component } from "../../widgets/component"; import { ICellRenderer } from "../...
getValue(): any; isPopup(): boolean; }
constructor(); init(params: ILargeTextEditorParams): void; private onKeyDown(event); afterGuiAttached(): void;
random_line_split
chai-datetime.d.ts
// Type definitions for chai-datetime // Project: https://github.com/gaslight/chai-datetime.git // Definitions by: Cliff Burger <https://github.com/cliffburger/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../chai/chai.d.ts" /> declare namespace Chai { interface Assert...
beforeTime(val: Date, exp: Date, msg?: string): void; notBeforeTime(val: Date, exp: Date, msg?: string): void; afterTime(val: Date, exp: Date, msg?: string): void; notAfterTime(val: Date, exp: Date, msg?: string): void; equalDate(val: Date, exp: Date, msg?: string): void; ...
} interface Assert { equalTime(val: Date, exp: Date, msg?: string): void; notEqualTime(val: Date, exp: Date, msg?: string): void;
random_line_split
TestEnd2EndDatatypesTestData.ts
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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...
jsRuntimeType: "Boolean", joynrType: "Boolean", values: [true, false, true] }, { attribute: "int8Attribute", jsRuntimeType: "Number", joynrType: "Byte", values: [Math.pow(2, 7) - 1, 0, -Math.pow(2, 7)] }, { attribute: "uint8Attribute", ...
import Country from "../../generated/joynr/datatypes/exampleTypes/Country"; const TestEnd2EndDatatypesTestData = [ { attribute: "booleanAttribute",
random_line_split
reset_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import sys try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse from . import appmanager from . import util setup_module, teardown_module = appmanager.setup(('app', 8380)) class Re...
for h in good: httpcode = h.getinfo(pycurl.RESPONSE_CODE) if httpcode != 200: print("Transfer to %s failed with code %d\n" %\ (h.getinfo(pycurl.EFFECTIVE_URL), httpcode)) raise RuntimeError els...
print("Transfer to %s failed with %d, %s\n" % \ (h.getinfo(pycurl.EFFECTIVE_URL), en, em)) raise RuntimeError
conditional_block
reset_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import sys try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse from . import appmanager from . import util setup_module, teardown_module = appmanager.setup(('app', 8380)) class Re...
break while active_handles: ret = cm.select(1.0) if ret == -1: continue while 1: ret, active_handles = cm.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: ...
random_line_split
reset_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import sys try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse from . import appmanager from . import util setup_module, teardown_module = appmanager.setup(('app', 8380)) class Re...
(self): c = pycurl.Curl() c.setopt(pycurl.URL, 'http://localhost:8380/success') c.reset() try: c.perform() self.fail('Perform worked when it should not have') except pycurl.error: exc = sys.exc_info()[1] code = exc.args[0] ...
test_reset
identifier_name
reset_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import sys try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse from . import appmanager from . import util setup_module, teardown_module = appmanager.setup(('app', 8380)) class Re...
ret, active_handles = cm.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: break count, good, bad = cm.info_read() for h, en, em in bad: print("Transfer to %s failed with %d, %s\n" % \ (h.getinfo...
outf = util.BytesIO() cm = pycurl.CurlMulti() eh = pycurl.Curl() for x in range(1, 20): eh.setopt(pycurl.WRITEFUNCTION, outf.write) eh.setopt(pycurl.URL, 'http://localhost:8380/success') cm.add_handle(eh) while 1: ret, active_han...
identifier_body
pair_slices.rs
use core::cmp::{self}; use core::mem::replace; use crate::alloc::Allocator; use super::VecDeque; /// PairSlices pairs up equal length slice parts of two deques /// /// For example, given deques "A" and "B" with the following division into slices: /// /// A: [0 1 2] [3 4 5] /// B: [a b] [c d e] /// /// It produces th...
(&mut self) -> Option<Self::Item> { // Get next part length let part = cmp::min(self.a0.len(), self.b0.len()); if part == 0 { return None; } let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part); let (q0, q1) = self.b0.split_at(part); // Mo...
next
identifier_name
pair_slices.rs
use core::cmp::{self}; use core::mem::replace; use crate::alloc::Allocator; use super::VecDeque; /// PairSlices pairs up equal length slice parts of two deques /// /// For example, given deques "A" and "B" with the following division into slices: /// /// A: [0 1 2] [3 4 5] /// B: [a b] [c d e] /// /// It produces th...
pub fn has_remainder(&self) -> bool { !self.b0.is_empty() } pub fn remainder(self) -> impl Iterator<Item = &'b [T]> { IntoIterator::into_iter([self.b0, self.b1]) } } impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> { type Item = (&'a mut [T], &'b [T]); fn next(&mut self) ->...
{ let (a0, a1) = to.as_mut_slices(); let (b0, b1) = from.as_slices(); PairSlices { a0, a1, b0, b1 } }
identifier_body
pair_slices.rs
use core::cmp::{self}; use core::mem::replace; use crate::alloc::Allocator; use super::VecDeque; /// PairSlices pairs up equal length slice parts of two deques /// /// For example, given deques "A" and "B" with the following division into slices: /// /// A: [0 1 2] [3 4 5] /// B: [a b] [c d e] /// /// It produces th...
} pub fn remainder(self) -> impl Iterator<Item = &'b [T]> { IntoIterator::into_iter([self.b0, self.b1]) } } impl<'a, 'b, T> Iterator for PairSlices<'a, 'b, T> { type Item = (&'a mut [T], &'b [T]); fn next(&mut self) -> Option<Self::Item> { // Get next part length let part =...
random_line_split
pair_slices.rs
use core::cmp::{self}; use core::mem::replace; use crate::alloc::Allocator; use super::VecDeque; /// PairSlices pairs up equal length slice parts of two deques /// /// For example, given deques "A" and "B" with the following division into slices: /// /// A: [0 1 2] [3 4 5] /// B: [a b] [c d e] /// /// It produces th...
let (p0, p1) = replace(&mut self.a0, &mut []).split_at_mut(part); let (q0, q1) = self.b0.split_at(part); // Move a1 into a0, if it's empty (and b1, b0 the same way). self.a0 = p1; self.b0 = q1; if self.a0.is_empty() { self.a0 = replace(&mut self.a1, &mut [])...
{ return None; }
conditional_block
transaction.py
i + 1 self.lookup = lookup self.reverseLookup = reverseLookup def __getattr__(self, attr): if not self.lookup.has_key(attr): raise AttributeError return self.lookup[attr] def whatis(self, value): return self.reverseLookup[value] # This function comes from b...
(decoded, to_match): if len(decoded) != len(to_match): return False; for i in range(len(decoded)): if to_match[i] == opcodes.OP_PUSHDATA4 and decoded[i][0] <= opcodes.OP_PUSHDATA4 and decoded[i][0]>0: continue # Opcodes below OP_PUSHDATA4 all just push data onto stack, and are equiv...
match_decoded
identifier_name
transaction.py
n = len(public_keys) if num is None: num = n # supports only "2 of 2", and "2 of 3" transactions assert num <= n and n in [2,3] if num==2: s = '52' elif num == 3: s = '53' else: raise for k in public_keys: ...
found = True break
conditional_block
transaction.py
match_decoded(decoded, match): return False, hash_160_to_bc_address(decoded[2][1]) # p2sh match = [ opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUAL ] if match_decoded(decoded, match): return False, hash_160_to_bc_address(decoded[1][1],5) return False, "(None)" class Trans...
vds = BCDataStream() vds.write(self.raw.decode('hex')) d = {} start = vds.read_cursor d['version'] = vds.read_int32() n_vin = vds.read_compact_size() d['inputs'] = [] for i in xrange(n_vin): d['inputs'].append(self.parse_input(vds)) n_vout = vd...
identifier_body
transaction.py
i + 1 self.lookup = lookup self.reverseLookup = reverseLookup def __getattr__(self, attr): if not self.lookup.has_key(attr): raise AttributeError return self.lookup[attr] def whatis(self, value): return self.reverseLookup[value] # This function comes from b...
"OP_MOD", "OP_LSHIFT", "OP_RSHIFT", "OP_BOOLAND", "OP_BOOLOR", "OP_NUMEQUAL", "OP_NUMEQUALVERIFY", "OP_NUMNOTEQUAL", "OP_LESSTHAN", "OP_GREATERTHAN", "OP_LESSTHANOREQUAL", "OP_GREATERTHANOREQUAL", "OP_MIN", "OP_MAX", "OP_WITHIN", "OP_RIPEMD160", "OP_SHA1", "OP_SHA256", "OP_HASH160", "OP_HASH256", "O...
"OP_RETURN", "OP_TOALTSTACK", "OP_FROMALTSTACK", "OP_2DROP", "OP_2DUP", "OP_3DUP", "OP_2OVER", "OP_2ROT", "OP_2SWAP", "OP_IFDUP", "OP_DEPTH", "OP_DROP", "OP_DUP", "OP_NIP", "OP_OVER", "OP_PICK", "OP_ROLL", "OP_ROT", "OP_SWAP", "OP_TUCK", "OP_CAT", "OP_SUBSTR", "OP_LEFT", "OP_RIGHT", "OP_SIZE", "OP_INVERT", ...
random_line_split
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return presentation; }); }); } })); }); let indentationRules = { increaseIndentPattern: /(^.*\{[^}]*$)/, decreaseIndentPattern: /^\s*\}/ }; languages.setLanguageConfiguration('css', { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g, indentation...
let presentation = new ColorPresentation(p.label); presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit); presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
random_line_split
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
{ let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`); } textEditor.edit(mutator => { for (let edit...
identifier_body
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}); } } }
{ window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.'); }
conditional_block
cssMain.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor.document.version !== documentVersion) { window.showInformationMessage(`CSS fix is outdated and can't be applied to the document....
applyCodeAction
identifier_name
assignments_turnitin_msonline_list.py
# https://canvas.instructure.com/doc/api/assignments.html from datetime import datetime from canvas.core.courses import get_courses, get_courses_whitelisted, get_course_people, get_courses_by_account_id from canvas.core.io import write_xlsx_file, tada from canvas.core.assignments import get_assignments def...
write_xlsx_file('turnitin_assignments_spring_dev_{}' .format(datetime.now().strftime('%Y.%m.%d.%H.%M.%S')), header, rows) if __name__ == '__main__': # assignments_turnitin_msonline_list() assignments_turnitin_msonline_list_dev() tada()
row = [ account, course['name'], assignment['name'], assignment['html_url'], assignment['points_possible'] if assignment['points_possible'] else ''] rows.appen...
conditional_block
assignments_turnitin_msonline_list.py
# https://canvas.instructure.com/doc/api/assignments.html from datetime import datetime from canvas.core.courses import get_courses, get_courses_whitelisted, get_course_people, get_courses_by_account_id from canvas.core.io import write_xlsx_file, tada from canvas.core.assignments import get_assignments def...
assignment['name'], assignment['html_url'], assignment['due_at'][0:10] if assignment['due_at'] else '', assignment['points_possible'] if assignment['points_possible'] else '', 'X' if 'group_category_id...
terms = ['2017-1SP'] programs = ['NFNPO', 'NCMO'] synergis = True course_whitelist = get_courses_whitelisted([]) header = ['term', 'program', 'SIS ID', 'course name', 'assignment name', 'assignment URL', 'due date', 'points', 'group assignment', 'faculty of record'] rows = [] ...
identifier_body
assignments_turnitin_msonline_list.py
# https://canvas.instructure.com/doc/api/assignments.html from datetime import datetime from canvas.core.courses import get_courses, get_courses_whitelisted, get_course_people, get_courses_by_account_id from canvas.core.io import write_xlsx_file, tada from canvas.core.assignments import get_assignments def...
(): accounts = {'DEV FNPO': '168920', 'DEV CMO': '168922'} header = ['program', 'course name', 'assignment name', 'assignment URL', 'points'] rows = [] for account in accounts: for course in get_courses_by_account_id(accounts[account], 'DEFAULT'): course_id = course['id'] ...
assignments_turnitin_msonline_list_dev
identifier_name
assignments_turnitin_msonline_list.py
# https://canvas.instructure.com/doc/api/assignments.html from datetime import datetime
from canvas.core.assignments import get_assignments def assignments_turnitin_msonline_list(): terms = ['2017-1SP'] programs = ['NFNPO', 'NCMO'] synergis = True course_whitelist = get_courses_whitelisted([]) header = ['term', 'program', 'SIS ID', 'course name', 'assignment name', 'assignmen...
from canvas.core.courses import get_courses, get_courses_whitelisted, get_course_people, get_courses_by_account_id from canvas.core.io import write_xlsx_file, tada
random_line_split
uuids.rs
extern crate cassandra; use cassandra::CassSession; use cassandra::CassUuid; use cassandra::CassStatement; use cassandra::CassResult; use cassandra::CassError; use cassandra::CassUuidGen; use cassandra::CassCluster; static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?, ?, ?);"; st...
(session: &mut CassSession, key: &str) -> Result<CassResult, CassError> { let mut statement = CassStatement::new(SELECT_QUERY, 1); statement.bind_string(0, &key).unwrap(); let mut future = session.execute_statement(&statement); let results = try!(future.wait()); Ok(results) } fn main() { let uu...
select_from_log
identifier_name
uuids.rs
extern crate cassandra; use cassandra::CassSession; use cassandra::CassUuid; use cassandra::CassStatement; use cassandra::CassResult; use cassandra::CassError; use cassandra::CassUuidGen; use cassandra::CassCluster; static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?, ?, ?);"; st...
fn select_from_log(session: &mut CassSession, key: &str) -> Result<CassResult, CassError> { let mut statement = CassStatement::new(SELECT_QUERY, 1); statement.bind_string(0, &key).unwrap(); let mut future = session.execute_statement(&statement); let results = try!(future.wait()); Ok(results) } fn...
{ let mut statement = CassStatement::new(INSERT_QUERY, 3); statement.bind_string(0, key).unwrap(); statement.bind_uuid(1, time).unwrap(); statement.bind_string(2, &entry).unwrap(); let mut future = session.execute_statement(&statement); future.wait() }
identifier_body
uuids.rs
extern crate cassandra; use cassandra::CassSession; use cassandra::CassUuid; use cassandra::CassStatement; use cassandra::CassResult; use cassandra::CassError; use cassandra::CassUuidGen; use cassandra::CassCluster; static INSERT_QUERY:&'static str = "INSERT INTO examples.log (key, time, entry) VALUES (?, ?, ?);"; st...
insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #3").unwrap(); insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #4").unwrap(); let results = select_from_log(session, "test").unwrap(); // for row in results.iter() { // let time = row.get_column(1).unwrap(); // let entry = ...
insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #1").unwrap(); insert_into_log(session, "test", uuid_gen.get_time(), "Log entry #2").unwrap();
random_line_split
setup.py
# -*- coding: utf-8 -*- # # Copyright (C) 2009 Damien Churchill <damoxc@gmail.com> # # Basic plugin template created by: # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # # This file is part of Deluge and is licensed under GNU General Public Licen...
license=__license__, long_description=__long_description__ if __long_description__ else __description__, packages=find_packages(), namespace_packages=["deluge", "deluge.plugins"], package_data=__pkg_data__, entry_points=""" [deluge.plugin.core] %s = deluge.plugins.%s:CorePlugin [de...
description=__description__, author=__author__, author_email=__author_email__, url=__url__,
random_line_split
flows_overview.ts
import {compareAlphabeticallyBy} from '../../lib/type_utils'; interface FlowOverviewCategory { readonly title: string; readonly items: ReadonlyArray<FlowListItem>; } /** * Component that displays available Flows. */ @Component({ selector: 'flows-overview', templateUrl: './flows_overview.ng.html', styleUrl...
import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; import {BehaviorSubject, Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {FlowListItem, FlowsByCategory} from '../../components/flow_picker/flow_list_item';
random_line_split
flows_overview.ts
import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; import {BehaviorSubject, Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {FlowListItem, FlowsByCategory} from '../../components/flow_picker/flow_list_item'; import {compareAlphabeticallyBy} from '../../li...
private readonly flowsByCategory$ = new BehaviorSubject<FlowsByCategory|null>(null); readonly categories$: Observable<ReadonlyArray<FlowOverviewCategory>> = this.flowsByCategory$.pipe( map(fbc => { const result = Array.from(fbc?.entries() ?? []) .m...
{ return this.flowsByCategory$.value; }
identifier_body
flows_overview.ts
import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; import {BehaviorSubject, Observable} from 'rxjs'; import {map} from 'rxjs/operators'; import {FlowListItem, FlowsByCategory} from '../../components/flow_picker/flow_list_item'; import {compareAlphabeticallyBy} from '../../li...
(value: FlowsByCategory|null) { this.flowsByCategory$.next(value); } get flowsByCategory(): FlowsByCategory|null { return this.flowsByCategory$.value; } private readonly flowsByCategory$ = new BehaviorSubject<FlowsByCategory|null>(null); readonly categories$: Observable<ReadonlyArray<FlowOver...
flowsByCategory
identifier_name
youtubewrapper.py
,contentDetails&channelId='+channel_id+'&maxResults=50&key='+youtube_api_key raw = urllib.urlopen(url) resp = json.load(raw) raw.close() totalplaylists = len(resp["items"]) for playlist in resp["items"]: playlist_id = playlist["id"] try: for level in ["high","medium","low"]: if level in playlist["snippe...
else: video_info['width'] = 854 video_info['height'] = 480 audio_info['channels'] = 1 try: if xbmcaddon.Addon(id='plugin.video.youtube').getSetting('kodion.video.quality.ask') == 'false' and xbmcaddon.Addon(id='plugin.video.youtube').getSetting('kodion.video.quality') != '3' and xbmcaddon.A...
video_info['width'] = 1280 video_info['height'] = 720 audio_info['channels'] = 2
conditional_block
youtubewrapper.py
ideoid = item["id"] episode = re.findall('(\d+)',title) try: aired = re.compile('(.+?)-(.+?)-(.+?)T').findall(aired)[0] date = aired[2] + '.' + aired[1] + '.' + aired[0] aired = aired[0]+'-'+aired[1]+'-'+aired[2] except: aired = '' date = '' infolabels = {'plot':plot.encode(...
video_url = 'plugin://plugin.video.youtube?path=/root/video&action=play_video&videoid='+url item = xbmcgui.ListItem(path=video_url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item) player = KKPlayer(mainurl=url) player.play(video_url,item) while player._playbackLock: player._trackPosition() xbmc.sleep(1...
identifier_body
youtubewrapper.py
(): url = 'https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId='+channel_id+'&maxResults=50&key='+youtube_api_key raw = urllib.urlopen(url) resp = json.load(raw) raw.close() totalplaylists = len(resp["items"]) for playlist in resp["items"]: playlist_id = playlist["id"] try: ...
get_playlists
identifier_name
youtubewrapper.py
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 urllib import json import re import os import sys import math import xbmcaddon import xbmcplugin from common_variables import * from directory import * #get list of pla...
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
random_line_split
get_articles.py
import json import csv import pandas as pd cred = pd.read_csv('credible.csv') noncred = pd.read_csv('noncredible.csv') noncred.reset_index(level=0, inplace=True) cred.columns = ['site','type'] noncred.columns = ['site', 'lang', 'type','notes', 'tmp'] cred['clean_site'] = cred['site'].apply(lambda x: x.split('.')[0].lo...
data.append(l) elif s in false and s not in true: l['label']=1 data.append(l) else: pass print(len(data)) df = pd.DataFrame(data) df.to_csv('articles1.csv') with open('sources.csv','w',newline='') as f: cw = csv.writer(f) sources = list(so...
random_line_split
get_articles.py
import json import csv import pandas as pd cred = pd.read_csv('credible.csv') noncred = pd.read_csv('noncredible.csv') noncred.reset_index(level=0, inplace=True) cred.columns = ['site','type'] noncred.columns = ['site', 'lang', 'type','notes', 'tmp'] cred['clean_site'] = cred['site'].apply(lambda x: x.split('.')[0].lo...
print(len(data)) df = pd.DataFrame(data) df.to_csv('articles1.csv') with open('sources.csv','w',newline='') as f: cw = csv.writer(f) sources = list(sources) for s in sources: print(s) cw.writerow([s])
l = json.loads(line) if l['media-type']=='News': s = l['source'] if s not in sources: print(s) sources.add(l['source']) s = l['source'].replace(' ','').replace("'","").replace('-','').lower() if s in true and s not ...
conditional_block
Scheduler.py
# -*- coding: utf-8 -*- """ The scheduler is responsible for the module handling. """ import modules from importlib import import_module from additional.Logging import Logging ################################################################################ class Scheduler(): """ This class instantiates the...
################################################################################ class SubClassError(Exception): """ Exception for module subclass errors. """ class VersionError(Exception): """ Exception for module version errors. """
""" Returns the module's search queries. """ queries = {} for module_name, module in self._instantiated_modules.items(): queries[module_name] = module.get_queries('select') return queries
identifier_body
Scheduler.py
# -*- coding: utf-8 -*- """ The scheduler is responsible for the module handling. """ import modules from importlib import import_module from additional.Logging import Logging ################################################################################ class Scheduler(): """ This class instantiates the...
elif result[0][0] > module_version: raise VersionError('Old module version detected!' + 'Module: {} - Expected: {} - Found: {}' .format(module_name, result[0][0], module_version)) ################################################################...
self.server.db.update_data(''' UPDATE versions SET version = %s WHERE module = %s''', (module_version, module_name,))
conditional_block
Scheduler.py
# -*- coding: utf-8 -*- """ The scheduler is responsible for the module handling. """ import modules from importlib import import_module from additional.Logging import Logging ################################################################################ class Scheduler(): """ This class instantiates the...
# makes sure the module implements DatasourceBase if not isinstance(module, modules.DatasourceBase): raise SubClassError( 'Modul is not an instance of DatasourceBase: {}' .format(module.__class__.__name__)) # adds the module t...
random_line_split
Scheduler.py
# -*- coding: utf-8 -*- """ The scheduler is responsible for the module handling. """ import modules from importlib import import_module from additional.Logging import Logging ################################################################################ class
(): """ This class instantiates the modules, takes care of the module's versions and gets the module's select queries. """ # dictonary of instantiated modules _instantiated_modules = {} def __init__(self, db): self._db = db self._log = Logging(self.__class__.__name__).get_...
Scheduler
identifier_name
statement.js
mi) else this.semicolon() return this.finishNode(node, "DoWhileStatement") } // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpres...
node.left = init node.right = this.parseExpression() this.expect(tt.parenR) node.body = this.parseStatement(false)
random_line_split
statement.js
expr) } } pp.parseBreakContinueStatement = function(node, keyword) { let isBreak = keyword == "break" this.next() if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null else if (this.type !== tt.name) this.unexpected() else { node.label = this.parseIdent() this.semicolon() } // Ve...
return this.finishNode(node, "ReturnStatement") } pp.parseSwitchStatement = function(node) { this.next() node.discriminant = this.parseParenExpression() node.cases = [] this.expect(tt.braceL) this.labels.push(switchLabel) // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is...
{ node.argument = this.parseExpression(); this.semicolon() }
conditional_block
ndvi.py
#!/usr/bin/env python # Version 0.1 # NDVI automated acquisition and calculation by Vladyslav Popov # Using landsat-util, source: https://github.com/developmentseed/landsat-util # Uses Amazon Web Services Public Dataset (Lansat 8) # Script should be run every day from os.path import join, abspath, dirname, exis...
nir_file = scene_id + '_B5.TIF' ndvi_file = scene_id + '_NDVI.TIF' print 'Filenames builded succsessfuly' # Create directories for future pssing base_dir = os.getcwd() temp_folder = join(base_dir, "temp_folder") scene_folder = join(temp_folder, scene_id) if not os.path.exists(temp_folder): os.makedirs(tem...
# Build filenames for band rasters and output NDVI file red_file = scene_id + '_B4.TIF'
random_line_split
ndvi.py
#!/usr/bin/env python # Version 0.1 # NDVI automated acquisition and calculation by Vladyslav Popov # Using landsat-util, source: https://github.com/developmentseed/landsat-util # Uses Amazon Web Services Public Dataset (Lansat 8) # Script should be run every day from os.path import join, abspath, dirname, exis...
if not os.path.exists(scene_folder): os.makedirs(scene_folder) # Download section for Band 4 using urllib2 file_name = url_red.split('/')[-1] u = urllib2.urlopen(url_red) f = open("temp_folder/"+scene_id+"/"+file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Do...
os.makedirs(temp_folder)
conditional_block
setup.py
# -*- coding: utf-8 -*- import os.path import re import warnings try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version = '0.2.1' news = os.path.join(os.path.dirname(__file__...
if not found_news: warnings.warn('No news for this version found.') long_description = """ keepassdb is a Python library that provides functionality for reading and writing KeePass 1.x (and KeePassX) password databases. This library brings together work by multiple authors, including: - Karsten-Kai König <kkoen...
found_news = parts[i+i] break
conditional_block
setup.py
# -*- coding: utf-8 -*- import os.path import re import warnings try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages version = '0.2.1' news = os.path.join(os.path.dirname(__file__...
)
use_2to3=True, zip_safe=False # Technically it should be fine, but there are issues w/ 2to3
random_line_split
bibclassify_microtests.py
# -*- coding: utf-8 -*- """Module for running microtests on how well the extraction works - this module is STANDALONE safe""" import ConfigParser import glob import traceback import codecs import bibclassify_config as bconfig import bibclassify_engine as engine log = bconfig.get_logger("bibclassify.microtest") de...
config = {} cfg = ConfigParser.ConfigParser() fo = codecs.open(cfgfile, 'r', 'utf-8') cfg.readfp(fo, filename=cfgfile) for s in cfg.sections(): if s in config: log.error('two sections with the same name') config[s] = {} for k, v in cfg.items(s): if "\n...
unwanted: [some-string] section-2: ..... } """
random_line_split
bibclassify_microtests.py
# -*- coding: utf-8 -*- """Module for running microtests on how well the extraction works - this module is STANDALONE safe""" import ConfigParser import glob import traceback import codecs import bibclassify_config as bconfig import bibclassify_engine as engine log = bconfig.get_logger("bibclassify.microtest") de...
if filter(len, out) and filter(len, out2): return "%s\n%s" % ("\n".join(filter(len, out)), "\n".join(out2)) else: return "%s%s" % ("\n".join(filter(len, out)), "\n".join(out2)) def analyze_results(test_case, results): skw = results[0] ckw = results[1] details = {"correct" : []...
out2.append("%s=%s" % (key.rjust(padding-1), phrase[padding:]))
conditional_block
bibclassify_microtests.py
# -*- coding: utf-8 -*- """Module for running microtests on how well the extraction works - this module is STANDALONE safe""" import ConfigParser import glob import traceback import codecs import bibclassify_config as bconfig import bibclassify_engine as engine log = bconfig.get_logger("bibclassify.microtest") de...
(details): plevel = details["plevel"] details["plevel"] = [plevel] out = format_test_case(details) details["plevel"] = plevel return out def format_test_case(test_case): padding = 13 keys = ["phrase", "expected", "unwanted"] out = ["" for x in range(len(keys))] out2 = [] for ...
format_details
identifier_name
bibclassify_microtests.py
# -*- coding: utf-8 -*- """Module for running microtests on how well the extraction works - this module is STANDALONE safe""" import ConfigParser import glob import traceback import codecs import bibclassify_config as bconfig import bibclassify_engine as engine log = bconfig.get_logger("bibclassify.microtest") de...
def run_microtest_suite(test_cases, results={}, plevel=1): """Runs all tests from the test_case @var test_cases: microtest definitions @keyword results: dict, where results are cummulated @keyword plevel: int [0..1], performance level, results below the plevel are considered unsuccessful ...
"""Execute microtests""" if verbose is not None: log.setLevel(int(verbose)) results = {} for pattern in glob_patterns: log.info("Looking for microtests: %s" % pattern) for cfgfile in glob.glob(pattern): log.debug("processing: %s" % (cfgfile)) try: ...
identifier_body
test-ipcbrowser-chrome.js
function
() { enableAsyncScrolling(); messageManager.loadFrameScript( "chrome://global/content/test-ipcbrowser-content.js", true ); } function browser() { return document.getElementById("content"); } function frameLoader() { return browser().QueryInterface(Components.interfaces.nsIFrameLoaderOwner)...
init
identifier_name
test-ipcbrowser-chrome.js
function init() { enableAsyncScrolling(); messageManager.loadFrameScript( "chrome://global/content/test-ipcbrowser-content.js", true ); } function browser() { return document.getElementById("content"); } function frameLoader() { return browser().QueryInterface(Components.interfaces.nsIFram...
} // Functions affecting <browser>. function scrollViewportBy(dx, dy) { rootView().scrollBy(dx, dy); } function scrollViewportTo(x, y) { rootView().scrollTo(x, y); } function setViewportScale(xs, ys) { rootView().setScale(xs, ys); } var kDelayMs = 100; var kDurationMs = 250; var scrolling = false; func...
function setContentResolution(xres, yres) { messageManager.sendAsyncMessage("setResolution", { xres: xres, yres: yres });
random_line_split
test-ipcbrowser-chrome.js
function init() { enableAsyncScrolling(); messageManager.loadFrameScript( "chrome://global/content/test-ipcbrowser-content.js", true ); } function browser() { return document.getElementById("content"); } function frameLoader() { return browser().QueryInterface(Components.interfaces.nsIFram...
var kDelayMs = 100; var kDurationMs = 250; var scrolling = false; function startAnimatedScrollBy(dx, dy) { if (scrolling) throw "don't interrupt me!"; scrolling = true; var start = mozAnimationStartTime; var end = start + kDurationMs; // |- k| so that we do something in first invocation ...
{ rootView().setScale(xs, ys); }
identifier_body
test-ipcbrowser-chrome.js
function init() { enableAsyncScrolling(); messageManager.loadFrameScript( "chrome://global/content/test-ipcbrowser-content.js", true ); } function browser() { return document.getElementById("content"); } function frameLoader() { return browser().QueryInterface(Components.interfaces.nsIFram...
else { mozRequestAnimationFrame(nudgeScroll); } prevNow = now; } nudgeScroll(start); mozRequestAnimationFrame(nudgeScroll); }
{ var fixupDx = Math.max(dx - accumDx, 0); var fixupDy = Math.max(dy - accumDy, 0); rootView().scrollBy(fixupDx, fixupDy); scrolling = false; }
conditional_block
FunctionalUseCase.ts
// LICENSE : MIT "use strict"; import { FunctionalUseCaseContext } from "./FunctionalUseCaseContext"; import { UseCaseLike } from "./UseCaseLike"; import { Dispatcher } from "./Dispatcher"; import { generateNewId } from "./UseCaseIdGenerator"; import { DispatcherPayloadMetaImpl } from "./DispatcherPayloadMeta"; import ...
(functionUseCase: (context: FunctionalUseCaseContext) => Function) { super(); const dispatcher = { dispatch: (payload: Payload) => { // system dispatch has meta // But, when meta is empty, the `payload` object generated by user const useCaseMet...
constructor
identifier_name
FunctionalUseCase.ts
// LICENSE : MIT "use strict"; import { FunctionalUseCaseContext } from "./FunctionalUseCaseContext"; import { UseCaseLike } from "./UseCaseLike"; import { Dispatcher } from "./Dispatcher"; import { generateNewId } from "./UseCaseIdGenerator"; import { DispatcherPayloadMetaImpl } from "./DispatcherPayloadMeta"; import ...
} }
const payload = new ErrorPayload({ error }); this.dispatch(payload, meta);
random_line_split
FunctionalUseCase.ts
// LICENSE : MIT "use strict"; import { FunctionalUseCaseContext } from "./FunctionalUseCaseContext"; import { UseCaseLike } from "./UseCaseLike"; import { Dispatcher } from "./Dispatcher"; import { generateNewId } from "./UseCaseIdGenerator"; import { DispatcherPayloadMetaImpl } from "./DispatcherPayloadMeta"; import ...
throw error; } }; /** * Functional version of UseCase class. * The user pass a function as UseCase * @example * * const functionalUseCase = ({ dispatcher }) => { * return (...args) => { * dispatcher.dispatch({ type: "fire" }); * } * } * */ export class FunctionalUseCase extends Dispatc...
{ console.error(`Warning(UseCase): This is wrong Functional UseCase. Example: const useCase = ({ dispatcher }) => { return (args) => { // execute } }; context.useCase(useCase).execute("args"); `); }
conditional_block
app.js
'use strict'; /** * @ngdoc object * @name activityApp * @requires $routeProvider * @requires activityControllers * @requires ui.bootstrap * * @description * Root app, which routes and specifies the partial html and controller depending on the url requested. * */ var app = angular.module('activityApp', ['...
* Holds the constants that represent HTTP error codes. * */ app.constant('HTTP_ERRORS', { 'UNAUTHORIZED': 401 }); /** * @ngdoc service * @name oauth2Provider * * @description * Service that holds the OAuth2 information shared across all the pages. * */ app.factory('oauth2Provider', function ($modal) { ...
* * @description
random_line_split
endpoint_handler.py
""" HTTP handeler to serve specific endpoint request like http://myserver:9004/endpoints/mymodel For how generic endpoints requests is served look at endpoints_handler.py """ import json import logging import shutil from tabpy.tabpy_server.common.util import format_exception from tabpy.tabpy_server.handlers import Ma...
else: self.error_out( 404, "Unknown endpoint", info=f"Endpoint {endpoint_name} is not found", ) @gen.coroutine def put(self, name): if self.should_fail_with_auth_error() != AuthErrorStates.NONE: ...
self.write(json.dumps(self.tabpy_state.get_endpoints()[endpoint_name]))
conditional_block
endpoint_handler.py
""" HTTP handeler to serve specific endpoint request like http://myserver:9004/endpoints/mymodel For how generic endpoints requests is served look at endpoints_handler.py """ import json import logging import shutil from tabpy.tabpy_server.common.util import format_exception from tabpy.tabpy_server.handlers import Ma...
(self, endpoint_name): if self.should_fail_with_auth_error() != AuthErrorStates.NONE: self.fail_with_auth_error() return self.logger.log(logging.DEBUG, f"Processing GET for /endpoints/{endpoint_name}") self._add_CORS_header() if not endpoint_name: se...
get
identifier_name
endpoint_handler.py
""" HTTP handeler to serve specific endpoint request like http://myserver:9004/endpoints/mymodel For how generic endpoints requests is served look at endpoints_handler.py """ import json import logging import shutil from tabpy.tabpy_server.common.util import format_exception from tabpy.tabpy_server.handlers import Ma...
info=f"Endpoint {endpoint_name} is not found", ) @gen.coroutine def put(self, name): if self.should_fail_with_auth_error() != AuthErrorStates.NONE: self.fail_with_auth_error() return self.logger.log(logging.DEBUG, f"Processing PUT for...
def initialize(self, app): super(EndpointHandler, self).initialize(app) def get(self, endpoint_name): if self.should_fail_with_auth_error() != AuthErrorStates.NONE: self.fail_with_auth_error() return self.logger.log(logging.DEBUG, f"Processing GET for /endpoints/{en...
identifier_body
endpoint_handler.py
""" HTTP handeler to serve specific endpoint request like http://myserver:9004/endpoints/mymodel For how generic endpoints requests is served look at endpoints_handler.py """ import json import logging import shutil from tabpy.tabpy_server.common.util import format_exception from tabpy.tabpy_server.handlers import Ma...
self.settings, self.tabpy_state, self.python_service, self.logger ) @gen.coroutine def _delete_po_future(self, delete_path): future = STAGING_THREAD.submit(shutil.rmtree, delete_path) ret = yield future raise gen.Return(ret)
on_state_change(
random_line_split
nmap_scanner.py
# region Description """ nmap_scanner.py: Scan local network with NMAP Author: Vladimir Ivanov License: MIT Copyright 2020, Raw-packet Project """ # endregion # region Import from raw_packet.Utils.base import Base import xml.etree.ElementTree as ET import subprocess as sub from tempfile import gettempdir from os.path ...
# region Address for address in element.findall('address'): if address.attrib['addrtype'] == 'ipv4': ipv4_address = address.attrib['addr'] if address.attrib['addrtype'] == 'mac': ...
assert state == 'up'
random_line_split
nmap_scanner.py
# region Description """ nmap_scanner.py: Scan local network with NMAP Author: Vladimir Ivanov License: MIT Copyright 2020, Raw-packet Project """ # endregion # region Import from raw_packet.Utils.base import Base import xml.etree.ElementTree as ET import subprocess as sub from tempfile import gettempdir from os.path ...
# endregion # region OS for os_info in element.find('os'): if os_info.tag == 'osmatch': try: os = os_info.attrib['name'] except TypeError: ...
ports.append(ports_info.attrib['portid'])
conditional_block
nmap_scanner.py
# region Description """ nmap_scanner.py: Scan local network with NMAP Author: Vladimir Ivanov License: MIT Copyright 2020, Raw-packet Project """ # endregion # region Import from raw_packet.Utils.base import Base import xml.etree.ElementTree as ET import subprocess as sub from tempfile import gettempdir from os.path ...
: # region Variables _base: Base = Base(admin_only=True, available_platforms=['Linux', 'Darwin', 'Windows']) try: Info = namedtuple(typename='Info', field_names='vendor, os, mac_address, ipv4_address, ports', defaults=('', '', '', '', [])) except TypeError: Inf...
NmapScanner
identifier_name
nmap_scanner.py
# region Description """ nmap_scanner.py: Scan local network with NMAP Author: Vladimir Ivanov License: MIT Copyright 2020, Raw-packet Project """ # endregion # region Import from raw_packet.Utils.base import Base import xml.etree.ElementTree as ET import subprocess as sub from tempfile import gettempdir from os.path ...
# endregion # region Find devices in local network with nmap def scan(self, exit_on_failure: bool = True, quiet: bool = False) -> Union[None, List[NamedTuple]]: try: # region Variables network_devices: List[NamedTuple] = list() ipv4_ad...
self._your: Dict[str, Union[None, str]] = \ self._base.get_interface_settings(interface_name=network_interface, required_parameters=['mac-address', 'ipv4-address', 'first-ipv4-address', 'last-ipv...
identifier_body
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule, Http, RequestOptions } from '@angular/http'; import { AuthHttp, AuthConfig } from ...
declarations: [ AppComponent, CalendarComponent, CreationReservationComponent, ValidationReservationComponent, AdminComponent, HeaderComponent, ReservationOkComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, RouterModule.forR...
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule, Http, RequestOptions } from '@angular/http'; import { AuthHttp, AuthConfig } from ...
{ }
AppModule
identifier_name
account.py
appe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint from frappe import throw, _ from frappe.model.document import Document class RootNotEditable(frappe.ValidationError): pass c...
(self): if not self.account_currency: self.account_currency = frappe.db.get_value("Company", self.company, "default_currency") elif self.account_currency != frappe.db.get_value("Account", self.name, "account_currency"): if frappe.db.get_value("GL Entry", {"account": self.name}): frappe.throw(_("Currency ...
validate_account_currency
identifier_name
account.py
appe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint from frappe import throw, _ from frappe.model.document import Document class RootNotEditable(frappe.ValidationError): pass c...
self.validate_parent() self.validate_root_details() self.set_root_and_report_type() self.validate_mandatory() self.validate_warehouse_account() self.validate_frozen_accounts_modifier() self.validate_balance_must_be_debit_or_credit() self.validate_account_currency() def validate_parent(self): """Fetc...
def validate(self):
random_line_split
account.py
appe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint from frappe import throw, _ from frappe.model.document import Document class RootNotEditable(frappe.ValidationError): pass c...
def validate_warehouse_account(self): if not cint(frappe.defaults.get_global_default("auto_accounting_for_stock")): return if self.account_type == "Warehouse": if not self.warehouse: throw(_("Warehouse is mandatory if account type is Warehouse")) old_warehouse = cstr(frappe.db.get_value("Account",...
if not self.report_type: throw(_("Report Type is mandatory")) if not self.root_type: throw(_("Root Type is mandatory"))
identifier_body
account.py
appe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint from frappe import throw, _ from frappe.model.document import Document class RootNotEditable(frappe.ValidationError): pass c...
if not self.root_type: throw(_("Root Type is mandatory")) def validate_warehouse_account(self): if not cint(frappe.defaults.get_global_default("auto_accounting_for_stock")): return if self.account_type == "Warehouse": if not self.warehouse: throw(_("Warehouse is mandatory if account type is Ware...
throw(_("Report Type is mandatory"))
conditional_block
mod.rs
/// This is a streaming segmented sieve, meaning it sieves numbers in /// intervals, extracting whatever it needs and discarding it. See /// `Sieve` for a wrapper that caches the information to allow for /// repeated queries, at the cost of *O(limit)* memory use. /// /// This uses *O(sqrt(limit))* memory, and is design...
mod presieve; /// A heavily optimised prime sieve. ///
random_line_split
mod.rs
_pi(11), 5); /// /// assert_eq!(primal::StreamingSieve::prime_pi(100), 25); /// assert_eq!(primal::StreamingSieve::prime_pi(1000), 168); /// ``` pub fn prime_pi(n: usize) -> usize { match n { 0...1 => 0, 2 => 1, 3...4 => 2, 5...6 => 3, ...
&m
identifier_name
mod.rs
sieve.next().unwrap(); let bytes = bitv.as_bytes(); count += hamming::weight(bytes) as usize; } let (_, last) = sieve.next().unwrap(); count += last.count_ones_before(tweak + includes as usize); count }...
run(b, 10_000_000) } }
identifier_body
prepare_dpf4.py
#!/usr/bin/env python # # # # $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_dpf4.py,v 1.14.4.1 2011/12/01 17:16:33 rhuey Exp $ # import string import os.path from MolKit import Read from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algori...
if __name__ == '__main__': import getopt import sys try: opt_list, args = getopt.getopt(sys.argv[1:], 'sLShvl:r:i:o:x:p:k:e') except getopt.GetoptError, msg: print 'prepare_dpf4.py: %s' % msg usage() sys.exit(2) receptor_filename = ligand_filename = None ...
print "Usage: prepare_dpf4.py -l pdbqt_file -r pdbqt_file" print " -l ligand_filename" print " -r receptor_filename" print print "Optional parameters:" print " [-o output dpf_filename]" print " [-i template dpf_filename]" print " [-x flexres_filename]" print " [-p param...
identifier_body
prepare_dpf4.py
#!/usr/bin/env python # # # # $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_dpf4.py,v 1.14.4.1 2011/12/01 17:16:33 rhuey Exp $ # import string import os.path from MolKit import Read from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algori...
print " The DPF will by default be <ligand>_<receptor>.dpf. This" print "may be overridden using the -o flag." if __name__ == '__main__': import getopt import sys try: opt_list, args = getopt.getopt(sys.argv[1:], 'sLShvl:r:i:o:x:p:k:e') except getopt.GetoptError, msg: pr...
print print "Prepare a docking parameter file (DPF) for AutoDock4." print
random_line_split
prepare_dpf4.py
#!/usr/bin/env python # # # # $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_dpf4.py,v 1.14.4.1 2011/12/01 17:16:33 rhuey Exp $ # import string import os.path from MolKit import Read from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algori...
#dm.set_docking_parameters( ga_num_evals=1750000,ga_pop_size=150, ga_run=20, rmstol=2.0) kw = {} for p in parameters: key,newvalue = string.split(p, '=') #detect string reps of lists: eg "[1.,1.,1.]" if newvalue[0]=='[': nv = [] for item in newvalue[1:-1]...
flexmol = Read(flexres_filename)[0] flexres_types = flexmol.allAtoms.autodock_element lig_types = dm.dpo['ligand_types']['value'].split() all_types = lig_types for t in flexres_types: if t not in all_types: all_types.append(t) all_types_string = all_t...
conditional_block
prepare_dpf4.py
#!/usr/bin/env python # # # # $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_dpf4.py,v 1.14.4.1 2011/12/01 17:16:33 rhuey Exp $ # import string import os.path from MolKit import Read from AutoDockTools.DockingParameters import DockingParameters, DockingParameter4FileMaker, genetic_algori...
(): print "Usage: prepare_dpf4.py -l pdbqt_file -r pdbqt_file" print " -l ligand_filename" print " -r receptor_filename" print print "Optional parameters:" print " [-o output dpf_filename]" print " [-i template dpf_filename]" print " [-x flexres_filename]" print " [...
usage
identifier_name
yaqluator.js
"/evaluate/"; var apiExampleName = "/examples/"; var autoComplete = apiServerString + "/autoComplete/"; var evalReqObj = { "yaml": "", "yaql_expression": "", "legacy": false }; //methods /** * @param args [hitType, eventCategory, eventAction, eventLabel, eventValue] */ function ga_send(args) { if (t...
function selectTextareaLine(tarea, lineNum) { lineNum--; // array starts at 0 var lines = tarea.value.split("\n"); // calculate start/end var startPos = 0; for (var x = 0; x < lines.length; x++) { if (x == lineNum) { break; } startPos += (lines[x].length + 1); ...
{ $yamlInput.val(JSON.stringify(yaml, undefined, 4)); }
identifier_body
yaqluator.js
= "/evaluate/"; var apiExampleName = "/examples/"; var autoComplete = apiServerString + "/autoComplete/"; var evalReqObj = { "yaml": "", "yaql_expression": "", "legacy": false }; //methods /** * @param args [hitType, eventCategory, eventAction, eventLabel, eventValue] */ function ga_send(args) { if ...
} function handleFiles() { var file = $("#fileInput")[0].files[0]; var reader = new FileReader(); reader.readAsText(file, "UTF-8"); reader.onload = function (evt) { $yamlInput.val(evt.target.result); //setYaml(evt.target.result); }; reader.onerror = function (evt) { $yam...
$yaqlAlert.html(error); toggleError($yaqlAlert, true); } }); });
random_line_split
yaqluator.js
"/evaluate/"; var apiExampleName = "/examples/"; var autoComplete = apiServerString + "/autoComplete/"; var evalReqObj = { "yaml": "", "yaql_expression": "", "legacy": false }; //methods /** * @param args [hitType, eventCategory, eventAction, eventLabel, eventValue] */ function ga_send(args) { if (t...
console.log("Suggestions for YAQL expression " + $yaqlInput.val() + " are: " + suggestions); $yaqlInput.typeahead('destroy'); $yaqlInput.typeahead({source: suggestions, items: 'all', showHintOnFocus: true}); $yaqlInput.focus(); // this fixes dropdown clo...
{ var currentValue = $yaqlInput.val(); var prefix = currentValue.substring(0, currentValue.lastIndexOf(".")); suggestions = result.value.suggestions.map(function (item) { return prefix + "." + item }); ...
conditional_block
yaqluator.js
= "/evaluate/"; var apiExampleName = "/examples/"; var autoComplete = apiServerString + "/autoComplete/"; var evalReqObj = { "yaml": "", "yaql_expression": "", "legacy": false }; //methods /** * @param args [hitType, eventCategory, eventAction, eventLabel, eventValue] */ function ga_send(args) { if ...
(yaml) { $yamlInput.val(JSON.stringify(yaml, undefined, 4)); } function selectTextareaLine(tarea, lineNum) { lineNum--; // array starts at 0 var lines = tarea.value.split("\n"); // calculate start/end var startPos = 0; for (var x = 0; x < lines.length; x++) { if (x == lineNum) { ...
setYaml
identifier_name
socket.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::*; use ffi; use glib::object::Downcast; use Widget; glib_wrapper! { ...
/*pub fn add_id(&self, window: Window) { unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) }; } pub fn get_id(&self) -> Window { unsafe { ffi::gtk_socket_get_id(self.to_glib_none().0) }; } pub fn get_plug_window(&self) -> GdkWindow { let tmp_pointer = unsafe ...
{ assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() } }
identifier_body
socket.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::*; use ffi; use glib::object::Downcast; use Widget; glib_wrapper! { ...
pub fn new() -> Socket { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() } } /*pub fn add_id(&self, window: Window) { unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) }; } pub fn get_id(&self) -> W...
impl Socket {
random_line_split
socket.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::*; use ffi; use glib::object::Downcast; use Widget; glib_wrapper! { ...
() -> Socket { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_socket_new()).downcast_unchecked() } } /*pub fn add_id(&self, window: Window) { unsafe { ffi::gtk_socket_add_id(self.to_glib_none().0, window) }; } pub fn get_id(&self) -> Window { ...
new
identifier_name
MetaChangeFromDefaultRule.py
# Copyright (c) 2018, Ansible Project from ansiblelint.rules import AnsibleLintRule class MetaChangeFromDefaultRule(AnsibleLintRule): id = '703' shortdesc = 'meta/main.yml default values should be changed' field_defaults = [ ('author', 'your name'), ('description', 'your description'), ...
results = [] for field, default in self.field_defaults: value = galaxy_info.get(field, None) if value and value == default: results.append(({'meta/main.yml': data}, 'Should change default metadata: %s' % field)) return re...
return False
conditional_block
MetaChangeFromDefaultRule.py
# Copyright (c) 2018, Ansible Project from ansiblelint.rules import AnsibleLintRule class MetaChangeFromDefaultRule(AnsibleLintRule): id = '703' shortdesc = 'meta/main.yml default values should be changed' field_defaults = [ ('author', 'your name'), ('description', 'your description'), ...
galaxy_info = data.get('galaxy_info', None) if not galaxy_info: return False results = [] for field, default in self.field_defaults: value = galaxy_info.get(field, None) if value and value == default: results.append(({'meta/main.yml':...
return False
random_line_split
MetaChangeFromDefaultRule.py
# Copyright (c) 2018, Ansible Project from ansiblelint.rules import AnsibleLintRule class MetaChangeFromDefaultRule(AnsibleLintRule): id = '703' shortdesc = 'meta/main.yml default values should be changed' field_defaults = [ ('author', 'your name'), ('description', 'your description'), ...
(self, file, data): if file['type'] != 'meta': return False galaxy_info = data.get('galaxy_info', None) if not galaxy_info: return False results = [] for field, default in self.field_defaults: value = galaxy_info.get(field, None) ...
matchplay
identifier_name
MetaChangeFromDefaultRule.py
# Copyright (c) 2018, Ansible Project from ansiblelint.rules import AnsibleLintRule class MetaChangeFromDefaultRule(AnsibleLintRule):
return False galaxy_info = data.get('galaxy_info', None) if not galaxy_info: return False results = [] for field, default in self.field_defaults: value = galaxy_info.get(field, None) if value and value == default: results....
id = '703' shortdesc = 'meta/main.yml default values should be changed' field_defaults = [ ('author', 'your name'), ('description', 'your description'), ('company', 'your company (optional)'), ('license', 'license (GPLv2, CC-BY, etc)'), ('license', 'license (GPL-2.0-or-la...
identifier_body
service.rs
without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Creates and registers clien...
&client_path.to_str().expect("DB path could not be converted to string.") ).map_err(::client::Error::Database)?); let pruning = config.pruning; let client = Client::new(config, &spec, db.clone(), miner, io_service.channel())?; let snapshot_params = SnapServiceParams { engine: spec.engine.clone(), ge...
{ let panic_handler = PanicHandler::new_in_arc(); let io_service = IoService::<ClientIoMessage>::start()?; panic_handler.forward_from(&io_service); info!("Configured for {} using {} engine", Colour::White.bold().paint(spec.name.clone()), Colour::Yellow.bold().paint(spec.engine.name())); let mut db_config = ...
identifier_body
service.rs
without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Creates and registers clien...
(&self) -> Arc<Client> { self.client.clone() } /// Get snapshot interface. pub fn snapshot_service(&self) -> Arc<SnapshotService> { self.snapshot.clone() } /// Get network service component pub fn io(&self) -> Arc<IoService<ClientIoMessage>> { self.io_service.clone() } /// Set the actor to be notified ...
client
identifier_name
service.rs
even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Creates and registers client and ne...
ClientIoMessage::FeedStateChunk(ref hash, ref chunk) => self.snapshot.feed_state_chunk(*hash, chunk), ClientIoMessage::FeedBlockChunk(ref hash, ref chunk) => self.snapshot.feed_block_chunk(*hash, chunk), ClientIoMessage::TakeSnapshot(num) => { let client = self.client.clone(); let snapshot = self.snap...
{ if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) { warn!("Failed to initialize snapshot restoration: {}", e); } }
conditional_block
service.rs
without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Creates and registers clien...
run_ipc(ipc_path, client.clone(), snapshot.clone(), stop_guard.share()); Ok(ClientService { io_service: Arc::new(io_service), client: client, snapshot: snapshot, panic_handler: panic_handler, database: db, _stop_guard: stop_guard, }) } /// Get general IO interface pub fn register_io_handler...
let stop_guard = ::devtools::StopGuard::new();
random_line_split
child-comments.js
var React = require('react'); import {Icon} from "react-photonkit"; var styles = { avatar: { marginRight: 10, borderRadius: '50%', verticalAlign: 'middle' } } module.exports = React.createClass({ renderComment: function () { var c = []; var _this = this; th...
});
}
random_line_split
protractor_webdriver.js
`Protractor`, the E2E test framework for Angular applications. * * Copyright (c) 2014 Steffen Eckardt * Licensed under the MIT license. * * @see https://github.com/seckardt/grunt-protractor-webdriver * @see https://github.com/angular/protractor * @see https://code.google.com/p/selenium/wiki/WebDriverJs * @see ...
} function extract(regexp, value, idx) { var result; if (regexp.test(value) && (result = regexp.exec(value)) && typeof result[idx] === 'string') { return result[idx].trim(); } return ''; } function Webdriver(context, options, restarted) { var done = context.async(), restartedPrefix = (restarted =...
{ var opts = { cwd: process.cwd(), stdio: [process.stdin] }; if (process.platform === 'win32') { opts.windowsVerbatimArguments = true; var child = spawn('cmd.exe', ['/s', '/c', command.replace(/\//g, '\\')], opts); rl.createInterface({ input: process.stdin, output: process.stdout }).on...
identifier_body
protractor_webdriver.js
`Protractor`, the E2E test framework for Angular applications. * * Copyright (c) 2014 Steffen Eckardt * Licensed under the MIT license. * * @see https://github.com/seckardt/grunt-protractor-webdriver * @see https://github.com/angular/protractor * @see https://code.google.com/p/selenium/wiki/WebDriverJs * @see ...
(out) { grunt.verbose.writeln('>> '.red + out); var lines; if (REGEXP_REMOTE.test(out)) { server = extract(REGEXP_REMOTE, out, 1).replace(/\/wd\/hub/, '') || server; } else if (REGEXP_START_READY.test(out)) { // Success started(done); } else if (REGEXP_START_RUNNING.test(out)) { if (fail...
data
identifier_name
protractor_webdriver.js
`Protractor`, the E2E test framework for Angular applications. * * Copyright (c) 2014 Steffen Eckardt * Licensed under the MIT license. * * @see https://github.com/seckardt/grunt-protractor-webdriver * @see https://github.com/angular/protractor * @see https://code.google.com/p/selenium/wiki/WebDriverJs * @see ...
if (status[2]) { cb(); return; } stop(cb); }; } function data(out) { grunt.verbose.writeln('>> '.red + out); var lines; if (REGEXP_REMOTE.test(out)) { server = extract(REGEXP_REMOTE, out, 1).replace(/\/wd\/hub/, '') || server; } else if (REGEXP_START_READY.test(out)) { ...
};
random_line_split