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
KickstartFetch.py
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the im...
return status if __name__ == "__main__": import grinder grinder.setupLogging(False) systemId = open("/etc/sysconfig/rhn/systemid").read() baseURL = "http://satellite.rhn.redhat.com" channelLabel = "rhel-i386-server-5" ksLabel = "ks-rhel-i386-server-5" savePath = "./test123" kf...
LOG.warn("Unauthorized request from fetch(). Will attempt to update authentication credentials and retry") authMap = self.login(refresh=True) return self.fetch(fileName, fetchURL, savePath, itemSize, hashType, md5sum, headers=authMap)
conditional_block
KickstartFetch.py
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the im...
(BaseFetch): def __init__(self, systemId, baseURL): BaseFetch.__init__(self) self.baseURL = baseURL self.systemId = systemId self.rhnComm = RHNComm(baseURL, self.systemId) def login(self, refresh=False): return self.rhnComm.login(refresh) def getFetchURL(self, ...
KickstartFetch
identifier_name
KickstartFetch.py
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the im...
def login(self, refresh=False): return self.rhnComm.login(refresh) def getFetchURL(self, channelLabel, ksLabel, ksFilePath): return self.baseURL + "/SAT/$RHN/" + channelLabel + "/getKickstartFile/" + ksLabel + "/" + ksFilePath; def fetchItem(self, itemInfo): authMap = self.logi...
random_line_split
arv-enum-test.py
#!/usr/bin/env python # Aravis - Digital camera library # # Copyright (c) 2011-2012 Emmanuel Pacaud # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, o...
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, # Boston, MA 02111-1307, USA. # # Author: Emmanuel Pacaud <emmanuel@gnome.org> # If you have installed aravis in a non standard location, you may need # to make GI_TYPELIB_PATH point to the correct location. For example: # # export GI_TYPELIB_PATH=$GI_...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General # Public License along with this library; if not, write to the
random_line_split
getDetail.py
# -*- coding:utf-8 -*- #html_doc = '''<div><a href="http://www.weblio.jp/content/%E5%BD%A2%E5%AE%B9%E5%8B%95%E8%A9%9E" title="形容動詞の意味" class=crosslink>形容動詞</a>「<a href="http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャルの意味" class=crosslink>ア...
except Exception,e: print e tn = tn + 1 #print url, " access error!" #print "try ", tn, "time" time.sleep(5) if tn==tryNum: #print "Cannot fetch page!" return -1 return 0 if __name__ == "__main__": word...
main = soup.find(attrs={'class':'Nhgkt'}) left = soup.find_all(attrs={'class':'nhgktL'}) right = soup.find_all(attrs={'class':'nhgktR'}) if(left): for text in main.stripped_strings: if(re.match(u'終止形$', text)!=None):break ...
identifier_body
getDetail.py
# -*- coding:utf-8 -*- #html_doc = '''<div><a href="http://www.weblio.jp/content/%E5%BD%A2%E5%AE%B9%E5%8B%95%E8%A9%9E" title="形容動詞の意味" class=crosslink>形容動詞</a>「<a href="http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャルの意味" class=crosslink>ア...
in aList: print a['title'].encode('utf8'), print else: for text in main.stripped_strings: if(u'»' in text):break details.append(text) print '#'.join(details).encode('utf8') ...
aList = right[0].find_all('a') for a
conditional_block
getDetail.py
# -*- coding:utf-8 -*- #html_doc = '''<div><a href="http://www.weblio.jp/content/%E5%BD%A2%E5%AE%B9%E5%8B%95%E8%A9%9E" title="形容動詞の意味" class=crosslink>形容動詞</a>「<a href="http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャルの意味" class=crosslink>アー...
from bs4 import BeautifulSoup #from complainDetail import * timeout = 10 socket.setdefaulttimeout(timeout) def fetchDetail(link, word): tryNum = 3 tn = 0 while tn < tryNum: details = [] try: f = urllib2.urlopen(link) content = f.read() soup = BeautifulSo...
import time
random_line_split
getDetail.py
# -*- coding:utf-8 -*- #html_doc = '''<div><a href="http://www.weblio.jp/content/%E5%BD%A2%E5%AE%B9%E5%8B%95%E8%A9%9E" title="形容動詞の意味" class=crosslink>形容動詞</a>「<a href="http://www.weblio.jp/content/%E3%82%A2%E3%83%BC%E3%83%86%E3%82%A3%E3%83%95%E3%82%A3%E3%82%B7%E3%83%A3%E3%83%AB" title="アーティフィシャルの意味" class=crosslink>ア...
'html.parser') main = soup.find(attrs={'class':'Nhgkt'}) left = soup.find_all(attrs={'class':'nhgktL'}) right = soup.find_all(attrs={'class':'nhgktR'}) if(left): for text in main.stripped_strings: if(re.match(u'終止形$', text...
p(content,
identifier_name
admin.py
from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from .models import RegistrationProfile from opps.core.admin import apply_opps_rules @apply_opps_rules('registration') class Regist...
activate_users.short_description = _("Activate users") def resend_activation_email(self, request, queryset): """ Re-sends activation emails for the selected users. Note that this will *only* send activation emails for users who are eligible to activate; emails will not be sent...
""" Activates the selected users, if they are not alrady activated. """ for profile in queryset: RegistrationProfile.objects.activate_user(profile.activation_key)
identifier_body
admin.py
from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from .models import RegistrationProfile from opps.core.admin import apply_opps_rules @apply_opps_rules('registration') class Regist...
site = RequestSite(request) for profile in queryset: if not profile.activation_key_expired(): profile.send_activation_email(site) resend_activation_email.short_description = _("Re-send activation emails") admin.site.register(RegistrationProfile, RegistrationAdmin)
""" if Site._meta.installed: site = Site.objects.get_current() else:
random_line_split
admin.py
from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from .models import RegistrationProfile from opps.core.admin import apply_opps_rules @apply_opps_rules('registration') class Regist...
resend_activation_email.short_description = _("Re-send activation emails") admin.site.register(RegistrationProfile, RegistrationAdmin)
if not profile.activation_key_expired(): profile.send_activation_email(site)
conditional_block
admin.py
from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from .models import RegistrationProfile from opps.core.admin import apply_opps_rules @apply_opps_rules('registration') class Regist...
(self, request, queryset): """ Re-sends activation emails for the selected users. Note that this will *only* send activation emails for users who are eligible to activate; emails will not be sent to users whose activation keys have expired or who have already activated. ...
resend_activation_email
identifier_name
OfferSummary_offer.graphql.ts
/* tslint:disable */ /* eslint-disable */ import { ReaderFragment } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type OfferSummary_offer = { readonly saleDate: string | null; readonly saleLocation: string | null; readonly saleName: string | null; readonly " $refType": "Off...
export type OfferSummary_offer$key = { readonly " $data"?: OfferSummary_offer$data; readonly " $fragmentRefs": FragmentRefs<"OfferSummary_offer">; }; const node: ReaderFragment = { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "OfferSummary_offer", "selections": [ { ...
export type OfferSummary_offer$data = OfferSummary_offer;
random_line_split
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
// It could be usize instead of f64 but this is easier for interop // and its range is still enough not to be a problem. let mut cooccurrences: Array2<f64> = Array2::zeros((words.len() + 1, words.len() + 1)); if words.len() < 25 { info!("Collecting cooccurrences (with one another) of: {:?}", wo...
{ env_logger::init().unwrap(); let args = app_from_crate!() .arg_from_usage("<wordlist> 'file containing words to look for, one per line'") .arg_from_usage("<output> 'file in which to store the resulting cooccurrence matrix'") .get_matches(); // Read the word list from a file. l...
identifier_body
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
(content: &str, ids: &HashMap<&str, usize>) -> Vec<usize> { /// Notice that we return indices (avoiding allocation) content // You can split on nonalphanumerics for a big speedup but the tokens are dubious. //.split(|c: char| ! c.is_alphanumeric()) .split_word_bounds() .map(|ment...
tokenize
identifier_name
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
else { info!("Collecting cooccurrences (with one another) of {} words.", words.len()); } for rec in WarcStreamer::new()? { let mention_ids = tokenize(&rec, &word_ids); for mention_i in 0..mention_ids.len() { for context_i in mention_i..min(mention_ids.len(), WINDOW_WIDT...
{ info!("Collecting cooccurrences (with one another) of: {:?}", words); }
conditional_block
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered.
//! The output is a numpy file with a cooccurrence matrix. The rows are the center word, starting //! with the unknown word as word 0, and proceeding in the order they were specified in the input //! word list. The columns are the context words, and cooccurrence is always counted as 1 or 0. //! // argument parsing #[m...
//!
random_line_split
spsc_queue.rs
mute(box Node { value: None, next: AtomicPtr::new(ptr::null_mut::<Node<T>>()), }) } } } impl<T: Send> Queue<T> { /// Creates a new queue. /// /// This is unsafe as the type system doesn't enforce a single /// consumer-producer relationship. It als...
{ unsafe { stress_bound(0); stress_bound(1); } unsafe fn stress_bound(bound: uint) { let q = Arc::new(Queue::new(bound)); let (tx, rx) = channel(); let q2 = q.clone(); let _t = Thread::spawn(move|| { for _ ...
identifier_body
spsc_queue.rs
// next node in the queue } /// The single-producer single-consumer queue. This structure is not cloneable, /// but it can be safely shared in an Arc if it is guaranteed that there /// is only one popper and one pusher touching the queue at any one point in /// time. pub struct Queue<T> { // consumer fields ...
drop_full
identifier_name
spsc_queue.rs
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or impli...
let ret = *self.first.get(); *self.first.get() = (*ret).next.load(Ordering::Relaxed); return ret; } // If the above fails, then update our copy of the tail and try // again. *self.tail_copy.get() = self.tail_prev.load(Ordering::Acquire); if *s...
{ let b = self.cache_subtractions.load(Ordering::Relaxed); self.cache_subtractions.store(b + 1, Ordering::Relaxed); }
conditional_block
spsc_queue.rs
queue //! A single-producer single-consumer concurrent queue //! //! This module contains the implementation of an SPSC queue which can be used //! concurrently between two tasks. This data structure is safe to use and //! enforces the semantics that there is one pusher and one popper. #![unstable(feature = "std_misc...
fn smoke() { unsafe { let queue = Queue::new(0);
random_line_split
my-modal.component.ts
///<reference path="../../../../../node_modules/@angular/core/src/animation/metadata.d.ts"/> /** * Created by 李 on 2017/3/20. */ import { Component, OnInit, trigger, state, style, transition, animate, Input, Output, EventEmitter } from '@angular/core'; import {Team, TeamService} from "../../../service/team.servic...
animate(200, style({transform: 'scale(0)'})) ]) ]) ], providers:[TeamService,ProjectService] }) export class MyModalComponent implements OnInit{ @Input() show: boolean //是否显示 @Input() title: string @Input() content: string //内容指示 @Input() width: string = '200' ...
random_line_split
my-modal.component.ts
///<reference path="../../../../../node_modules/@angular/core/src/animation/metadata.d.ts"/> /** * Created by 李 on 2017/3/20. */ import { Component, OnInit, trigger, state, style, transition, animate, Input, Output, EventEmitter } from '@angular/core'; import {Team, TeamService} from "../../../service/team.servic...
ser.user_id, username:user.username } arr.push(obj) }) this.memberList = arr }else{ this.showTip(data.msg) } }) } //选择需要邀请的成员 selUser=(item)=>{ item.sel?item.sel=false:item.sel = true } //创建团队 createTeam=()=...
bscribe(data=>{ console.log(data); if(data.success){ let arr:any[] = [] data.datas.forEach((user:any)=>{ let obj = { show:false, sel:false, user_id:u
conditional_block
my-modal.component.ts
///<reference path="../../../../../node_modules/@angular/core/src/animation/metadata.d.ts"/> /** * Created by 李 on 2017/3/20. */ import { Component, OnInit, trigger, state, style, transition, animate, Input, Output, EventEmitter } from '@angular/core'; import {Team, TeamService} from "../../../service/team.servic...
mplements OnInit{ @Input() show: boolean //是否显示 @Input() title: string @Input() content: string //内容指示 @Input() width: string = '200' //默认宽高 @Input() height: string = '200' @Input() position: string = 'center' //默认垂直居中 @Input() type:string //开启方式 @Out...
ModalComponent i
identifier_name
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValConvertible for MozMap<T> where T: FromJSValConvertible<Config = C>, C: Clone, { type Config = C; unsafe fn from_jsval( cx: *mut JSContext, value: HandleValue, config: C, ) -> Result<Conversion...
deref
identifier_name
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
impl<T> MozMap<T> { /// Create an empty `MozMap`. pub fn new() -> Self { MozMap { map: HashMap::new(), } } } impl<T> Deref for MozMap<T> { type Target = HashMap<DOMString, T>; fn deref(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValCo...
/// The `MozMap` (open-ended dictionary) type. #[derive(Clone, JSTraceable)] pub struct MozMap<T> { map: HashMap<DOMString, T>, }
random_line_split
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
} }
{ rooted!(in(cx) let js_object = JS_NewPlainObject(cx)); assert!(!js_object.handle().is_null()); rooted!(in(cx) let mut js_value = UndefinedValue()); for (key, value) in &self.map { let key = key.encode_utf16().collect::<Vec<_>>(); value.to_jsval(cx, js_value.han...
identifier_body
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); if !GetPropertyKeys( cx, object.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, ids.get(), ) { // TODO: can GetPropertyKeys fail? ...
{ return Ok(ConversionResult::Failure( "MozMap value was not an object".into(), )); }
conditional_block
processor.py
# coding: utf-8 import os import shutil from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \ DOWNLOAD_TMP_FILE_SUFFIX from nxdrive.engine.processor import Processor as OldProcessor from nxdrive.logging_config import get_logger log = get_logger(__name__) class Processor(OldProcessor): ...
def _create_remotely(self, local_client, remote_client, doc_pair, parent_pair, name): local_parent_path = parent_pair.local_path # TODO Shared this locking system / Can have concurrent lock self._unlock_readonly(local_client, local_parent_path) tmp_file = None try: ...
doc_pair.local_digest = updated_info.get_digest() self._dao.update_last_transfer(doc_pair.id, "download") self._refresh_local_state(doc_pair, updated_info)
random_line_split
processor.py
# coding: utf-8 import os import shutil from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \ DOWNLOAD_TMP_FILE_SUFFIX from nxdrive.engine.processor import Processor as OldProcessor from nxdrive.logging_config import get_logger log = get_logger(__name__) class Processor(OldProcessor): ...
def _get_partial_folders(self): local_client = self._engine.get_local_client() if not local_client.exists('/.partials'): local_client.make_folder('/', '.partials') return local_client.abspath('/.partials') def _download_content(self, local_client, remote_client, doc_pair, ...
log.warning("acquire...") result = super(Processor, self).acquire_state(row_id) if result is not None and self._engine.get_local_watcher().is_pending_scan(result.local_parent_path): self._dao.release_processor(self._thread_id) # Postpone pair for watcher delay self._e...
identifier_body
processor.py
# coding: utf-8 import os import shutil from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \ DOWNLOAD_TMP_FILE_SUFFIX from nxdrive.engine.processor import Processor as OldProcessor from nxdrive.logging_config import get_logger log = get_logger(__name__) class Processor(OldProcessor): ...
(self, local_client, remote_client, doc_pair, parent_pair, name): local_parent_path = parent_pair.local_path # TODO Shared this locking system / Can have concurrent lock self._unlock_readonly(local_client, local_parent_path) tmp_file = None try: if doc_pair.folderish:...
_create_remotely
identifier_name
processor.py
# coding: utf-8 import os import shutil from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \ DOWNLOAD_TMP_FILE_SUFFIX from nxdrive.engine.processor import Processor as OldProcessor from nxdrive.logging_config import get_logger log = get_logger(__name__) class Processor(OldProcessor): ...
log.debug("Updating content of local file '%s'.", os_path) tmp_file = self._download_content(local_client, remote_client, doc_pair, new_os_path) # Delete original file and rename tmp file local_client.delete_final(doc_pair.local_path) rel_path = local_client.get_path(tmp_file) ...
new_os_path = os_path
conditional_block
index.js
import React from 'react' import PropTypes from 'prop-types' import { Flexbox2 as Flexbox, Header as HeaderStyleguide, IconColorful, Navbar, Spacing } from 'bonde-styleguide' // Components import ActionButton from './ActionButton' import Tabs, { Tab } from './Tabs' import Title from './Title' import UserDropd...
} RightNavbar.propTypes = { dropdown: oneOfType([func, string, object]) } Header.propTypes = { title: oneOfType([func, string, object]), actions: oneOfType([func, string, object]), tabs: oneOfType([func, string, object]), dropdown: oneOfType([func, string, object]) } Header.ActionButton = ActionButton Hea...
RenderElement.propTypes = { component: oneOfType([func, string, object])
random_line_split
op.py
"""Client library for Camlistore.""" __author__ = 'Brett Slatkin (bslatkin@gmail.com)' import base64 import cStringIO import hashlib import httplib import logging import mimetools import urllib import urlparse import simplejson __all__ = ['Error', 'ServerError', 'PayloadError', 'BUFFER_SIZE', 'CamliOp'] BUFFER_SI...
#
random_line_split
op.py
error was returned by the server.""" class PayloadError(ServerError): """Something about a data payload was bad.""" def buffered_sha1(data, buffer_size=BUFFER_SIZE): """Calculates the sha1 hash of some data. Args: data: A string of data to write or an open file-like object. File-like objects will ...
compute.update(line) data.seek(start) return compute.hexdigest() class CamliOp(object): """Camlistore client class that is single threaded, using one socket.""" def __init__(self, server_address, buffer_size=BUFFER_SIZE, create_connection=httplib.HTTPConn...
break
conditional_block
op.py
error was returned by the server.""" class PayloadError(ServerError): """Something about a data payload was bad.""" def buffered_sha1(data, buffer_size=BUFFER_SIZE): """Calculates the sha1 hash of some data. Args: data: A string of data to write or an open file-like object. File-like objects will ...
def put_blobs(self, blobs): """Puts a set of blobs. Args: blobs: List of (data, blobref) tuples; list of open files; or list of blob data strings. Returns: The set of blobs that were actually uploaded. If all blobs are already present this set will be empty. Raises: ...
"""Sets up the HTTP connection.""" self.connection = self._create_connection(self.server_address)
identifier_body
op.py
error was returned by the server.""" class PayloadError(ServerError): """Something about a data payload was bad.""" def
(data, buffer_size=BUFFER_SIZE): """Calculates the sha1 hash of some data. Args: data: A string of data to write or an open file-like object. File-like objects will be seeked back to their original position before this function returns. buffer_size: How much data to munge at a time. Returns:...
buffered_sha1
identifier_name
ndarray.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
M2 = 0.0; mu = 0.0; n = 0; for ( i = 0; i < N; i++ ) { v = x[ ix ]; if ( v === v ) { delta = v - mu; n += 1; mu += delta / n; M2 += delta * ( v - mu ); } ix += stride; } nc = n - correction; if ( nc <= 0.0 ) { return NaN; } return M2 / nc; } / / EXPORTS // module.exports = nanvariancew...
ar delta; var mu; var M2; var ix; var nc; var v; var n; var i; if ( N <= 0 ) { return NaN; } if ( N === 1 || stride === 0 ) { v = x[ offset ]; if ( v === v && N-correction > 0.0 ) { return 0.0; } return NaN; } ix = offset;
identifier_body
ndarray.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
if ( v === v ) { delta = v - mu; n += 1; mu += delta / n; M2 += delta * ( v - mu ); } ix += stride; } nc = n - correction; if ( nc <= 0.0 ) { return NaN; } return M2 / nc; } // EXPORTS // module.exports = nanvariancewd;
n = 0; for ( i = 0; i < N; i++ ) { v = x[ ix ];
random_line_split
ndarray.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
correction, x, stride, offset ) { var delta; var mu; var M2; var ix; var nc; var v; var n; var i; if ( N <= 0 ) { return NaN; } if ( N === 1 || stride === 0 ) { v = x[ offset ]; if ( v === v && N-correction > 0.0 ) { return 0.0; } return NaN; } ix = offset; M2 = 0.0; mu = 0.0; n = 0; for...
ariancewd( N,
identifier_name
ndarray.js
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
turn M2 / nc; } // EXPORTS // module.exports = nanvariancewd;
return NaN; } re
conditional_block
Floater.py
1, sticky = EW) self._valuator.grid(row=0, column=2, padx = 2, pady = 2) self.interior().columnconfigure(0, weight = 1) class FloaterWidget(Pmw.MegaWidget): def __init__(self, parent = None, **kw): #define the megawidget options INITOPT = Pmw.INITOPT optiondefs = ( ...
(self, value): # Nothing visible to update on this type of widget pass def get(self): """ self.get() Get current floater value """ return self.value ## Canvas callback functions # Floater velocity controller def mouseDown(self, event): ""...
updateIndicator
identifier_name
Floater.py
options INITOPT = Pmw.INITOPT optiondefs = ( # Appearance ('width', FLOATER_WIDTH, INITOPT), ('height', FLOATER_HEIGHT, INITOPT), ('relief', RAISED, self.setRelief), ('borderwidth', 2, ...
f['command'] = lambda val, s=self, i=index: s._floaterSetAt(i, val) f.pack(side = self['side'], expand = 1, fill = X) self.floaterList.append(f) # Make sure floaters are initialized
random_line_split
Floater.py
, INITOPT), ('numDigits', 2, self.setNumDigits), # Command to execute on floater updates ('command', None, None), # Extra data to be passed to command function ('commandData', [], None), ...
return self._value
identifier_body
Floater.py
1, sticky = EW) self._valuator.grid(row=0, column=2, padx = 2, pady = 2) self.interior().columnconfigure(0, weight = 1) class FloaterWidget(Pmw.MegaWidget): def __init__(self, parent = None, **kw): #define the megawidget options INITOPT = Pmw.INITOPT optiondefs = ( ...
self.velocitySF = 0.0 self.updateTask = taskMgr.add(self.updateFloaterTask, 'updateFloater') self.updateTask.lastTime = globalClock.getFrameTime() def updateFloaterTask(self, state): """ Update floaterWidget value based on current sca...
apply(self['preCallback'], self['callbackData'])
conditional_block
jquery.amarkalUIComponent.js
$.fn.extend({ // NOTE: this function does not always return a jQuery object! amarkalUIComponent: function( method ) { // Store arguments for use with methods var args = arguments.length > 1 ? Array.apply(null, arguments).slice(1) : null, selection, methodReturnVal; ...
// Override the return value when calling a method methodReturnVal = comp[method].apply(comp, args); // If a method returns a value, only call it for the first // element in the set if(typeof methodReturnV...
random_line_split
jquery.amarkalUIComponent.js
$.fn.extend({ // NOTE: this function does not always return a jQuery object! amarkalUIComponent: function( method ) { // Store arguments for use with methods var args = arguments.length > 1 ? Array.apply(null, arguments).slice(1) : null, selection, methodReturnVal; ...
// If this is a method call, run the method (if it exists) var comp = $(this).data('amarkal-ui-component'); if( typeof method !== 'undefined' && comp.hasOwnProperty(method)) { // Override the return value when calling a method ...
{ $(this).data('amarkal-ui-component', Amarkal.UI.createComponent($(this))); }
conditional_block
blogController.js
subalcatelApp.controller('articleDisplayCtrl', function($scope, $location, articles) { $scope.currentPage = ""; /** * get new data from back end on page changed * @return {[type]} [description] */ $scope.pageChanged = function() { articleFactory.articles($scope.currentPage).success(function(articles) { $...
var id = $stateParams.articleId articleFactory.comment(id, $scope.newComment) .success(function(response) { $scope.displayAddComment = false; }); }; /** * Show confirmation modal and delete article */ $scope.deleteArticle = function() { var modalOptions = { closeButtonText: 'Annuler'...
$scope.saveComment = function() {
random_line_split
logger.js
"use strict"; /** * Logger, 18.12.2013 Spaceify Oy * * @class Logger */ function
(config, class_) { var self = this; var isNodeJs = (typeof window === "undefined" ? true : false); self.RETURN = 1; var LOG = "log"; var DIR = "dir"; var INFO = "info"; self.ERROR = "error"; var ERROR = self.ERROR; var WARN = "warn"; self.FORCE = "force"; var FORCE = self.FORCE; var STDOUT = "stdout"; // ...
Logger
identifier_name
logger.js
"use strict"; /** * Logger, 18.12.2013 Spaceify Oy * * @class Logger */ function Logger(config, class_)
labels[INFO] = "[i] "; labels[ERROR] = "[e] "; labels[WARN] = "[w] "; labels[FORCE] = ""; labels[STDOUT] = ""; var showLabels = true; // -- -- -- -- -- -- -- -- -- -- // var enabled = (config ? config : {}); // Local: enabled = true (default), not enabled = false enabled[LOG] = (typeof enabled[LOG] !== "undefined" ...
{ var self = this; var isNodeJs = (typeof window === "undefined" ? true : false); self.RETURN = 1; var LOG = "log"; var DIR = "dir"; var INFO = "info"; self.ERROR = "error"; var ERROR = self.ERROR; var WARN = "warn"; self.FORCE = "force"; var FORCE = self.FORCE; var STDOUT = "stdout"; // Labels -- -- -- -...
identifier_body
logger.js
"use strict"; /** * Logger, 18.12.2013 Spaceify Oy * * @class Logger */ function Logger(config, class_) { var self = this; var isNodeJs = (typeof window === "undefined" ? true : false); self.RETURN = 1; var LOG = "log"; var DIR = "dir"; var INFO = "info"; self.ERROR = "error"; var ERROR = self.ERROR; var...
return new Logger(loggerConfig, class_); }; Logger.getLogger = function(class_) { if (!class_) class_ = "mainlog"; var globalObj = null; if (typeof(window) === "undefined") //nodejs globalObj = global; else globalObj = window; if (!globalObj.hasOwnProperty("speLoggerInstances_")) { globalObj["sp...
loggerConfig['error'] = all_; loggerConfig['warn'] = all_; }
random_line_split
__init__.py
# -*- encoding: utf-8 -*- ##############################################################################
# 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 the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warrant...
# # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify
random_line_split
worker-helper.js
/* 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 strict"; // Wrapper for CommonJS or browser (function (global, fn) { if (typeof exports === "object") { ...
(e) { self.postMessage({ id: id, error: e ? (e.message || e) : "Error" }); } } } } exports.createTask = createTask; });
handleError
identifier_name
worker-helper.js
/* 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 strict"; // Wrapper for CommonJS or browser (function (global, fn) { if (typeof exports === "object") { ...
// If anything else else { self.postMessage({ id: id, response: response }); } } function handleError (e) { self.postMessage({ id: id, error: e ? (e.message || e) : "Error" }); } } } } exports.createTask = createTask; });
{ handleError(response); }
conditional_block
worker-helper.js
/* 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 strict";
(function (global, fn) { if (typeof exports === "object") { fn(exports); } else { fn(global); } })(this, function (exports) { /** * This file is to only be included by ChromeWorkers. This exposes * a `createTask` function to workers to register tasks for communication * back to `devtools/shared/worker...
// Wrapper for CommonJS or browser
random_line_split
worker-helper.js
/* 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 strict"; // Wrapper for CommonJS or browser (function (global, fn) { if (typeof exports === "object") { ...
} } } exports.createTask = createTask; });
{ self.postMessage({ id: id, error: e ? (e.message || e) : "Error" }); }
identifier_body
Set.ts
import { root } from './root'; export interface ISetCtor { new<T>(): ISet<T>; } export interface ISet<T> { add(value: T): void; has(value: T): boolean; size: number; clear(): void; } export function minimalSetImpl<T>(): ISetCtor { // THIS IS NOT a full impl of Set, this is just the minimum // bits of f...
(value: T): void { if (!this.has(value)) { this._values.push(value); } } has(value: T): boolean { return this._values.indexOf(value) !== -1; } get size(): number { return this._values.length; } clear(): void { this._values.length = 0; } }; } export...
add
identifier_name
Set.ts
import { root } from './root'; export interface ISetCtor { new<T>(): ISet<T>; } export interface ISet<T> { add(value: T): void; has(value: T): boolean; size: number; clear(): void; } export function minimalSetImpl<T>(): ISetCtor { // THIS IS NOT a full impl of Set, this is just the minimum // bits of f...
} has(value: T): boolean { return this._values.indexOf(value) !== -1; } get size(): number { return this._values.length; } clear(): void { this._values.length = 0; } }; } export const Set: ISetCtor = root.Set || minimalSetImpl();
{ this._values.push(value); }
conditional_block
Set.ts
import { root } from './root'; export interface ISetCtor { new<T>(): ISet<T>; } export interface ISet<T> { add(value: T): void; has(value: T): boolean; size: number; clear(): void; } export function minimalSetImpl<T>(): ISetCtor { // THIS IS NOT a full impl of Set, this is just the minimum // bits of f...
clear(): void { this._values.length = 0; } }; } export const Set: ISetCtor = root.Set || minimalSetImpl();
{ return this._values.length; }
identifier_body
Set.ts
import { root } from './root'; export interface ISetCtor { new<T>(): ISet<T>; } export interface ISet<T> { add(value: T): void; has(value: T): boolean; size: number; clear(): void; } export function minimalSetImpl<T>(): ISetCtor { // THIS IS NOT a full impl of Set, this is just the minimum // bits of f...
} get size(): number { return this._values.length; } clear(): void { this._values.length = 0; } }; } export const Set: ISetCtor = root.Set || minimalSetImpl();
has(value: T): boolean { return this._values.indexOf(value) !== -1;
random_line_split
AD1-Exerc2.py
def verificaPalindrome(frase): removeWhiteSpaces = [] ### Array util para remover os espaços em brancos removeHypen = [] ### Array util para remover os hifen palindromo = str(frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula if (len(pa...
verificaPalindrome(frase)): print("E palindromo") else: print("Nao e palindromo")
elif(
conditional_block
AD1-Exerc2.py
def
(frase): removeWhiteSpaces = [] ### Array util para remover os espaços em brancos removeHypen = [] ### Array util para remover os hifen palindromo = str(frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula if (len(palindromo) == 1): ### S...
verificaPalindrome
identifier_name
AD1-Exerc2.py
def verificaPalindrome(frase): removeWhiteSpaces = [] ### Array util para remover os espaços em brancos removeHypen = [] ### Array util para remover os hifen palindromo = str(frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula if (len(pa...
elif(verificaPalindrome(frase)): print("E palindromo") else: print("Nao e palindromo")
frase = input() ### Pega o input do usuario if(frase == "fim"): ### Sai do loop se digitar fim break
random_line_split
AD1-Exerc2.py
def verificaPalindrome(frase):
palindromo = palindromo + word ### END - Remover hypen no meio da frase - END ### if(palindromo[0] == palindromo[-1]): ### Verifica se a primeira e ultima letra sao iguais return verificaPalindrome(palindromo[1:-1]) ### Remove a 1ª[1] e ultima[-1] letra da palavra return False f = open('...
removeWhiteSpaces = [] ### Array util para remover os espaços em brancos removeHypen = [] ### Array util para remover os hifen palindromo = str(frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula if (len(palindromo) == 1): ### Se o tamanho d...
identifier_body
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
} impl fmt::Display for SshKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ID: {:.0}\n\ Fingerprint: {}\n\ Public Key: {}\n\ Name: {}", self.id, self.fingerprint, self....
{ "ssh_key".into() }
identifier_body
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
<'a>() -> Cow<'a, str> { "ssh_key".into() } } impl fmt::Display for SshKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ID: {:.0}\n\ Fingerprint: {}\n\ Public Key: {}\n\ Name: {}", self.id, ...
name
identifier_name
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
use response; #[derive(Deserialize, Debug)] pub struct SshKey { pub id: f64, pub fingerprint: String, pub public_key: String, pub name: String, } impl response::NotArray for SshKey {} impl NamedResponse for SshKey { fn name<'a>() -> Cow<'a, str> { "ssh_key".into() } } impl fmt::Display for SshKe...
random_line_split
scheduler.py
(self): """Initialize analysis storage folder.""" self.storage = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(self.task.id)) # If the analysis storage folder already exists, we ne...
init_storage
identifier_name
scheduler.py
analyzed.""" sample = Database().view_sample(self.task.sample_id) sha256 = File(self.task.target).get_sha256() if sha256 != sample.sha256: log.error("Target file has been modified after submission: \"%s\"", self.task.target) return False return True def st...
# If the user specified a specific machine ID, a platform to be # used or machine tags acquire the machine accordingly. try: machine = machinery.acquire(machine_id=self.task.machine, platform=self.task.platform, ...
machine_lock.release() time.sleep(1) continue
conditional_block
scheduler.py
be analyzed.""" sample = Database().view_sample(self.task.sample_id) sha256 = File(self.task.target).get_sha256() if sha256 != sample.sha256: log.error("Target file has been modified after submission: \"%s\"", self.task.target) return False return True def...
log.error(str(e), extra={"task_id": self.task.id}) finally: # Stop Auxiliary modules. aux.stop() # Take a memory dump of the machine before shutting it off. if self.cfg.cuckoo.memory_dump or self.task.memory: try: d...
except CuckooMachineError as e: log.error(str(e), extra={"task_id": self.task.id}) dead_machine = True except CuckooGuestError as e:
random_line_split
scheduler.py
if not machinery.availables(): machine_lock.release() time.sleep(1) continue # If the user specified a specific machine ID, a platform to be # used or machine tags acquire the machine accordingly. try: machi...
self.running = True self.cfg = Config() self.db = Database() self.maxcount = maxcount self.total_analysis_count = 0
identifier_body
aiohttp.py
"""Utilities to help with aiohttp.""" import json from typing import Any, Dict, Optional from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict class MockRequest:
def query(self) -> "MultiDict[str]": """Return a dictionary with the query variables.""" return MultiDict(parse_qsl(self.query_string, keep_blank_values=True)) @property def _text(self) -> str: """Return the body as text.""" return self._content.decode("utf-8") async de...
"""Mock an aiohttp request.""" def __init__( self, content: bytes, method: str = "GET", status: int = 200, headers: Optional[Dict[str, str]] = None, query_string: Optional[str] = None, url: str = "", ) -> None: """Initialize a request.""" ...
identifier_body
aiohttp.py
"""Utilities to help with aiohttp.""" import json from typing import Any, Dict, Optional from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict class MockRequest: """Mock an aiohttp request.""" def __init__( self, content: bytes, method: str = "GET", ...
async def json(self) -> Any: """Return the body as JSON.""" return json.loads(self._text) async def post(self) -> "MultiDict[str]": """Return POST parameters.""" return MultiDict(parse_qsl(self._text, keep_blank_values=True)) async def text(self) -> str: """Return t...
return self._content.decode("utf-8")
random_line_split
aiohttp.py
"""Utilities to help with aiohttp.""" import json from typing import Any, Dict, Optional from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict class MockRequest: """Mock an aiohttp request.""" def __init__( self, content: bytes, method: str = "GET", ...
(self) -> str: """Return the body as text.""" return self._content.decode("utf-8") async def json(self) -> Any: """Return the body as JSON.""" return json.loads(self._text) async def post(self) -> "MultiDict[str]": """Return POST parameters.""" return MultiDict(...
_text
identifier_name
DropdownSelectCtrl.js
false; this.autoClose = true; this.isActive = false; this.oldText = ''; this.containerElement = null; this.onSelectChange = () => {}; this.onDropdownOpen = () => {}; this.onDropdownClose = () => {}; this._openFn = null; } $onInit() { this._prepareOptions(); this._prepareWatches(); } $postLi...
of this.disabled === 'undefined') { this.disabled = false; } this.onSelectChange = this.onSelectChange || (() => {}); } _prepareWatches() { const scope = this.getScope(); scope.$watch(() => this.datalist, (datalist, oldDatalist) => { this.model = this.modelCopy ? this.modelCopy : this.model; this....
toClose = true; } if (type
conditional_block
DropdownSelectCtrl.js
._searchText = this.model; } // 选中预设值 this.setModelValue(this.model); // 设置预设值的 focusIndex this.focusAt(this.getItemIndexByItemValue(this.model, this.items)); }); scope.$watch(() => this.model, (model, oldModel) => { if (this.model && (!this.items || !this.items.length)) { this.modelCopy = th...
let searchFields = [mapping.valueField, mapping.displayField]; let filteredItems = [];
random_line_split
DropdownSelectCtrl.js
false; this.autoClose = true; this.isActive = false; this.oldText = ''; this.containerElement = null; this.onSelectChange = () => {}; this.onDropdownOpen = () => {}; this.onDropdownClose = () => {}; this._openFn = null; } $onInit() { this._prepareOptions(); this._prepareWatches(); } $postLi...
e); if (newItem) { this.title = newItem[displayField]; this.model = modelValue; this.icon = newItem[iconField]; } else { if (this.supportInputValue) { this.title = this._searchText; this.model = this._searchText; this.icon = false; this.items = this._clampedDatalist; } else { thi...
lue(modelValu
identifier_name
DropdownSelectCtrl.js
false; this.autoClose = true; this.isActive = false; this.oldText = ''; this.containerElement = null; this.onSelectChange = () => {}; this.onDropdownOpen = () => {}; this.onDropdownClose = () => {}; this._openFn = null; } $onInit() { this._prepareOptions(); this._prepareWatches(); } $postLi...
} this.onBeforeSelectChange = this.onBeforeSelectChange || (() => Promise.resolve()); let callbackResult = this.onBeforeSelectChange({ item }); if (!isPromiseLike(callbackResult)) { callbackResult = Promise.resolve(callbackResult); } callbackResult .then(() => { scope.$evalAsync(() => { th...
if (!item) { return;
identifier_body
Variable.ts
import Condition from './Condition'; import Event from './Event'; /** * An object that represents a value in the system that can be changed */ interface Variable { /** * An id that must be unique to this addon or `VariableCollection` and remain constant * across requests and system restarts */ readonly...
} export default Variable;
{ return typeof obj.uniqueId === 'string' && typeof obj.name === 'string' && typeof obj.conditions === 'undefined' || Array.isArray(obj.conditions) && typeof obj.events === 'undefined' || Array.isArray(obj.events) && typeof obj.retrieveValue === 'function' && t...
identifier_body
Variable.ts
import Condition from './Condition'; import Event from './Event'; /** * An object that represents a value in the system that can be changed */ interface Variable { /** * An id that must be unique to this addon or `VariableCollection` and remain constant * across requests and system restarts */ readonly...
(obj: any): obj is Variable { return typeof obj.uniqueId === 'string' && typeof obj.name === 'string' && typeof obj.conditions === 'undefined' || Array.isArray(obj.conditions) && typeof obj.events === 'undefined' || Array.isArray(obj.events) && typeof obj.retrieveValue ==...
objectIsVariable
identifier_name
Variable.ts
import Condition from './Condition'; import Event from './Event'; /** * An object that represents a value in the system that can be changed */ interface Variable { /** * An id that must be unique to this addon or `VariableCollection` and remain constant * across requests and system restarts */ readonly...
* An array of events that this variable offers. These events should be associated * with this variable. */ readonly events?: Event[]; /** * Asks the variable to return its latest value, optionally performing work * asynchronously to retrieve the value * * @returns {Promise<any>} A promise that...
random_line_split
guestshell.py
# Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula from collections import namedtuple import time import logging from functools import partial from aeon.nxos.exceptions import ...
(self): """ Obtains the current resource allocations, assumes that the guestshell is in an 'Activated' state """ if 'None' == self._state: return None cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_de...
_get_sz_info
identifier_name
guestshell.py
# Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula from collections import namedtuple import time import logging from functools import partial from aeon.nxos.exceptions import ...
def _wait_state(self, state, timeout=60, interval=1, retry=0): now_state = None time.sleep(interval) while timeout: now_state = self.state if now_state == state: return time.sleep(interval) timeout -= 1 if state == '...
""" Obtains the current resource allocations, assumes that the guestshell is in an 'Activated' state """ if 'None' == self._state: return None cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_detail']['ROW_deta...
identifier_body
guestshell.py
# Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula from collections import namedtuple import time import logging from functools import partial from aeon.nxos.exceptions import ...
if 'None' == self._state: return None cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_detail']['ROW_detail'] sz_cpu = int(got['cpu_reservation']) sz_disk = int(got['disk_reservation']) sz_memory = int(got['me...
Obtains the current resource allocations, assumes that the guestshell is in an 'Activated' state """
random_line_split
guestshell.py
# Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula from collections import namedtuple import time import logging from functools import partial from aeon.nxos.exceptions import ...
cmd = 'show virtual-service detail name guestshell+' got = self.cli(cmd) got = got['TABLE_detail']['ROW_detail'] sz_cpu = int(got['cpu_reservation']) sz_disk = int(got['disk_reservation']) sz_memory = int(got['memory_reservation']) self.sz_has = _guestshell.Re...
return None
conditional_block
x86stdcall.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd", target_os = "android"))] pub fn main() { }
{ unsafe { let expected = 1234_usize; kernel32::SetLastError(expected); let actual = kernel32::GetLastError(); println!("actual = {}", actual); assert_eq!(expected, actual); } }
identifier_body
x86stdcall.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { unsafe { let expected = 1234_usize; kernel32::SetLastError(expected); let actual = kernel32::GetLastError(); println!("actual = {}", actual); assert_eq!(expected, actual); } } #[cfg(any(target_os = "macos", target_os = "linux", target_os = "freeb...
main
identifier_name
x86stdcall.rs
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd", target_os = "android"))] pub fn main() { }
assert_eq!(expected, actual); } } #[cfg(any(target_os = "macos",
random_line_split
Bookmark.ts
import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; interface Bookmark { startContainer: Node; startOffset: number; endContainer?: Node; endOffset?: number; } /** * Returns a range bookmark. This will convert indexed bookmarks into temporary span elements with * index 0 so that they can be restored proper...
else { container.appendChild(offsetNode); } container = offsetNode; offset = 0; } bookmark[start ? 'startContainer' : 'endContainer'] = container; bookmark[start ? 'startOffset' : 'endOffset'] = offset; }; setupEndPoint(true); if (!rng.collapsed) { setupEndPoint(); ...
{ offset = Math.min(offset, container.childNodes.length - 1); if (start) { container.insertBefore(offsetNode, container.childNodes[offset]); } else { dom.insertAfter(offsetNode, container.childNodes[offset]); } }
conditional_block
Bookmark.ts
import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; interface Bookmark { startContainer: Node; startOffset: number; endContainer?: Node; endOffset?: number; } /** * Returns a range bookmark. This will convert indexed bookmarks into temporary span elements with * index 0 so that they can be restored proper...
bookmark[start ? 'startOffset' : 'endOffset'] = offset; }; restoreEndPoint(true); restoreEndPoint(); const rng = dom.createRng(); rng.setStart(bookmark.startContainer, bookmark.startOffset); if (bookmark.endContainer) { rng.setEnd(bookmark.endContainer, bookmark.endOffset); } return rng; };...
dom.remove(node); } bookmark[start ? 'startContainer' : 'endContainer'] = container;
random_line_split
TestMad.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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 app...
float3 __attribute__((kernel)) testMadFloat3Float3Float3Float3(float3 inMultiplicand1, unsigned int x) { float3 inMultiplicand2 = rsGetElementAt_float3(gAllocInMultiplicand2, x); float3 inOffset = rsGetElementAt_float3(gAllocInOffset, x); return mad(inMultiplicand1, inMultiplicand2, inOffset); } float4 __...
}
random_line_split
testsettings.py
""" Settings for testing the application. """ import os DEBUG = True DJANGO_RDFLIB_DEVELOP = True
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_PATH, 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } SITE_ID = 1 STATIC_URL = '/static/' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', ...
DB_PATH = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'rdflib_django.db'))
random_line_split
RoomCtrl.js
(function() { function
(Room, CurrentUser, $scope) { this.rooms = Room.all; this.currentUser = CurrentUser.getCurrentUser(); this.setActiveRoom = (room) => { this.activeRoom = room; this.listMessages = Room.getMessages(this.activeRoom.$id); }; this.createUser = function(name) { this.curren...
RoomCtrl
identifier_name
RoomCtrl.js
(function() { function RoomCtrl(Room, CurrentUser, $scope)
this.send = () => { var message = { content: this.newMessage, username: this.currentUser, sentAt: new Date().getTime(), roomId: this.activeRoom.$id } console.log(message) Room.send(message); this.newMessage = ""; } } ...
{ this.rooms = Room.all; this.currentUser = CurrentUser.getCurrentUser(); this.setActiveRoom = (room) => { this.activeRoom = room; this.listMessages = Room.getMessages(this.activeRoom.$id); }; this.createUser = function(name) { this.currentUser = name; } ...
identifier_body
RoomCtrl.js
(function() { function RoomCtrl(Room, CurrentUser, $scope) { this.rooms = Room.all; this.currentUser = CurrentUser.getCurrentUser(); this.setActiveRoom = (room) => { this.activeRoom = room; this.listMessages = Room.getMessages(this.activeRoom.$id); }; this.createUser = f...
} angular .module('blocChat') .controller('RoomCtrl', ['Room', 'CurrentUser', '$scope', RoomCtrl]); })();
console.log(message) Room.send(message); this.newMessage = ""; }
random_line_split
svg.py
class Printer: def __init__(self): self._output = '' def print_output(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, ...
self.print_output(_svg_rectangle(x, y, a, a, color=color, width=width, border_color=border_color)) def print_text(self, x, y, text, color=0, font_size=12): self.print_output(_svg_text(x, y, text, color=color, font_size=font_size)) def to_file(self, filename): with open(filename, 'w') a...
def print_square(self, x, y, a, color=0, width=1, border_color=0):
random_line_split
svg.py
class Printer: def __init__(self): self._output = '' def print_output(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, ...
return 'rgb({}, {}, {})'.format(color, color, color)
return color
conditional_block
svg.py
class Printer:
f.write(str(self)) def __str__(self): return """<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> {} </svg> """.format(self._output) def _svg_line(x1, y1, x2, y2, color, width): color = _svg_color(color) return '<line x1="{}" y1...
def __init__(self): self._output = '' def print_output(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, width=1, border_colo...
identifier_body
svg.py
class Printer: def __init__(self): self._output = '' def
(self, output): self._output += output def print_line(self, x1, y1, x2, y2, color=0, width=1): self.print_output(_svg_line(x1, y1, x2, y2, color=color, width=width)) def print_circle(self, x, y, r, color=0, width=1, border_color=0): self.print_output(_svg_circle(x, y, r, color=color, w...
print_output
identifier_name
Matcher.test.js
/** * Sinon-jQuery * * Sinon matcher for matching jQuery collections. * * Copyright (c) Jadu * * Released under the MIT license * https://github.com/jadu/sinon-jquery/blob/master/LICENSE.txt */ 'use strict'; import _ from 'lodash'; import $ from 'jquery'; import Matcher from '../src/Matcher'; const expect = ...
}; this.matcher = new Matcher(this.stubSinon, $); }); describe('match()', function () { _.each(['My description', 'Your description'], function (description) { it('should pass the specified description through to Sinon when "' + description + '"', function () { ...
this.stubSinon = { match: sinon.spy(sinon.match.bind(sinon))
random_line_split