file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
streaming.py
# -*- coding: utf-8 -*- """ /*************************************************************************** Client for streaming based WPS. It exploits asynchronous capabilities of WPS and QGIS for visualizing intermediate results from a WPS ------------------- copyright : (C) 201...
def createTempGeometry(self, chunkId, geometryType): """ Create rubber bands for rapid visualization of geometries """ if geometryType == "Polygon": self.__tmpGeometry[chunkId] = QgsRubberBand(self.iface.mapCanvas(), True) self.__tmpGeometry[chunkId].setColor( QColor( ...
random_line_split
streaming.py
# -*- coding: utf-8 -*- """ /*************************************************************************** Client for streaming based WPS. It exploits asynchronous capabilities of WPS and QGIS for visualizing intermediate results from a WPS ------------------- copyright : (C) 201...
self, dir, extension): rasters = pystringlist() for name in glob.glob(dir + '/*' + extension): rasters.append(name) return rasters def getGdalBinPath(self): """ Retrieves GDAL binaries location """ settings = QSettings() return settings.val...
etRasterFiles(
identifier_name
FTS3Placement.py
from DIRAC import S_ERROR, S_OK, gLogger from DIRAC.DataManagementSystem.private.FTSAbstractPlacement import FTSAbstractPlacement, FTSRoute from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTS3Servers from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus import random class FTS...
:param route : FTSRoute :returns S_OK or S_ERROR(reason) """ rAccess = self.rssClient.getStorageElementStatus( route.sourceSE, "ReadAccess" ) self.log.debug( "se read %s %s" % ( route.sourceSE, rAccess ) ) if not rAccess["OK"]: self.log.error( rAccess["Message"] ) return ...
random_line_split
FTS3Placement.py
from DIRAC import S_ERROR, S_OK, gLogger from DIRAC.DataManagementSystem.private.FTSAbstractPlacement import FTSAbstractPlacement, FTSRoute from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTS3Servers from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus import random class FTS...
attempt += 1 # FIXME : I need to get the FTS server status from RSS # ftsStatusFromRss = rss.ftsStatusOrSomethingLikeThat if fts3Server: return S_OK( fts3Server ) return S_ERROR ( "Could not find an FTS3 server (max attempt reached)" ) def findRoute( self, sourceSE, targetSE ): ...
self.log.warn( 'FTS server %s is not in good shape. Choose another one' % fts3Server ) fts3Server = None
conditional_block
FTS3Placement.py
from DIRAC import S_ERROR, S_OK, gLogger from DIRAC.DataManagementSystem.private.FTSAbstractPlacement import FTSAbstractPlacement, FTSRoute from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTS3Servers from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus import random class FTS...
def __chooseFTS3Server( self ): """ Choose the appropriate FTS3 server depending on the policy """ fts3Server = None attempt = 0 # FIXME : need to get real valeu from RSS ftsServerStatus = True while not fts3Server and attempt < self.maxAttempts: if self.__serverPolicy == ...
""" return a random server from the list """ return random.choice( self.__serverList )
identifier_body
FTS3Placement.py
from DIRAC import S_ERROR, S_OK, gLogger from DIRAC.DataManagementSystem.private.FTSAbstractPlacement import FTSAbstractPlacement, FTSRoute from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTS3Servers from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus import random class FTS...
( self, sourceSE, targetSE ): """ Find the appropriate route from point A to B :param sourceSE : source SE :param targetSE : destination SE :returns S_OK(FTSRoute) """ fts3server = self.__chooseFTS3Server() if not fts3server['OK']: return fts3server fts3server = fts3serv...
findRoute
identifier_name
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
} fn read_file_and_get_range( path_to_fragment: &PathBuf, index: usize, ) -> LSPRuntimeResult<(String, lsp_types::Range)> { let file = std::fs::read(path_to_fragment) .map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let file_contents = std::str::from_utf8(&file).map_err(|...
)), }
random_line_split
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
( location: Location, root_dir: &PathBuf, ) -> LSPRuntimeResult<(String, lsp_types::Location)> { match location.source_location() { SourceLocationKey::Embedded { path, index } => { let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_...
to_contents_and_lsp_location_of_graphql_literal
identifier_name
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
SourceLocationKey::Standalone { path } => { let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_fragment)?; let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?; Ok((file_contents, lsp_types::Loca...
{ let path_to_fragment = root_dir.join(PathBuf::from(path.lookup())); let uri = get_uri(&path_to_fragment)?; let (file_contents, range) = read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?; Ok((file_contents, lsp_types::Location { uri,...
conditional_block
location.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::{convert::TryInto, path::PathBuf}; use common::{Location, SourceLocationKey}; use lsp_types::Url; use crate::lsp_runtime...
fn get_uri(path: &PathBuf) -> LSPRuntimeResult<Url> { Url::parse(&format!( "file://{}", path.to_str() .ok_or_else(|| LSPRuntimeError::UnexpectedError(format!( "Could not cast path {:?} as string", path )))? )) .map_err(|e| LSPRuntimeE...
{ let file = std::fs::read(path_to_fragment) .map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let file_contents = std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?; let response = extract_graphql::parse_chunks(file_contents); let sou...
identifier_body
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
(&self) -> Result<()> { T::refresh(self) } } impl<T: HgIdMutableHistoryStore + ?Sized, U: Deref<Target = T> + Send + Sync> HgIdMutableHistoryStore for U { fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> { T::add(self, key, info) } fn flush(&self) -> Result<Option<Vec<PathBu...
refresh
identifier_name
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
} impl<T: HgIdMutableHistoryStore + ?Sized, U: Deref<Target = T> + Send + Sync> HgIdMutableHistoryStore for U { fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> { T::add(self, key, info) } fn flush(&self) -> Result<Option<Vec<PathBuf>>> { T::flush(self) } } impl<T: RemoteH...
{ T::refresh(self) }
identifier_body
historystore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::Deref; use std::path::PathBuf; use anyhow::Result; use edenapi_types::HistoryEntry; use types::Key; use types::NodeInfo; us...
} impl<T: RemoteHistoryStore + ?Sized, U: Deref<Target = T> + Send + Sync> RemoteHistoryStore for U { fn prefetch(&self, keys: &[StoreKey]) -> Result<()> { T::prefetch(self, keys) } }
fn flush(&self) -> Result<Option<Vec<PathBuf>>> { T::flush(self) }
random_line_split
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { Some(x) } }).collect(); assert!(v == None); // test that it does not take more elements than it needs let mut functions = [|| Some(()), || None, || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); }
{ None }
conditional_block
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let i = Rc::new(RefCell::new(0i)); { let x = r(i.clone()); let opt = Some(x); let _y = opt.unwrap(); } assert_eq!(*i.borrow(), 1); } #[test] fn test_option_dance() { let x = Some(()); let mut y = Some(5i); let mut y2 = 0; for _x in x.iter() { y2 = y.take...
random_line_split
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1, Some(1))); assert_eq!(it.n...
test_unwrap_or_else
identifier_name
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or_else(|| 2), 2); } #[test] fn test_iter() { let val = 5i; let x = Some(val); let mut it = x.iter(); assert_eq!(it.size_hint(), (1...
{ let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); }
identifier_body
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { BlogComponent } from './blog.component'; import { HeroComponent } from './hero.component';
const appRoutes: Routes = [ { path: '', redirectTo: '/hero', pathMatch: 'full' }, { path: 'blog', component: BlogComponent }, { path: 'hero', component: HeroComponent }, { path: 'about', component: AboutComponent}, { path: 'pricing', component: PricingComponent}, { path: 'contact-us', component: ContactUsC...
import { AboutComponent } from './about.component'; import { PricingComponent} from './pricing.component'; import { ContactUsComponent } from './contact-us.component'; import { BlogPostFullComponent } from './blog-post-full.component';
random_line_split
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { BlogComponent } from './blog.component'; import { HeroComponent } from './hero.component'; import { AboutComponent } from './about.component'; import { PricingComponent} from './pricing.component'; import { Conta...
{ }
AppRoutingModule
identifier_name
websocketGate.js
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { getAllOpenRoomsIds } from './../../actions/roomsActionCreators'; import { getMessagesByRooms } from './../../actions/messagesActionCreators'; import { getGlobalSolvedUnsolvedStatistics ...
onMessage(e) { console.log(e); const data = e.data; if (data.split(":")[0] === WS_COMMANDS.NEW_MESSAGE) { this.onNewMessageAction(data); } if (data.split(":")[0] === WS_COMMANDS.NEW_ROOM) { this.onNewRoomAction(data); } } onNewMessageAction(data) { this.props.getMessagesBy...
{ console.log(e); this.setState({ isOpened: true }); }
identifier_body
websocketGate.js
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { getAllOpenRoomsIds } from './../../actions/roomsActionCreators'; import { getMessagesByRooms } from './../../actions/messagesActionCreators'; import { getGlobalSolvedUnsolvedStatistics ...
(e) { console.log(e); this.setState({ isOpened: true }); } onMessage(e) { console.log(e); const data = e.data; if (data.split(":")[0] === WS_COMMANDS.NEW_MESSAGE) { this.onNewMessageAction(data); } if (data.split(":")[0] === WS_COMMANDS.NEW_ROOM) { this.onNewRoomAction(data);...
onOpen
identifier_name
websocketGate.js
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { getAllOpenRoomsIds } from './../../actions/roomsActionCreators'; import { getMessagesByRooms } from './../../actions/messagesActionCreators'; import { getGlobalSolvedUnsolvedStatistics ...
onNewRoomAction(data) { if (authManager.isEmployee(this.props.role)) { this.props.getAllOpenRoomsIds(); this.props.getGlobalSolvedUnsolvedStatistics(); } } onClose(e) { console.log(e); } render() { const { children } = this.props; return ( <div> {children} ...
this.props.getMessagesByRooms(this.props.rooms); }
random_line_split
websocketGate.js
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { getAllOpenRoomsIds } from './../../actions/roomsActionCreators'; import { getMessagesByRooms } from './../../actions/messagesActionCreators'; import { getGlobalSolvedUnsolvedStatistics ...
} onNewMessageAction(data) { this.props.getMessagesByRooms(this.props.rooms); } onNewRoomAction(data) { if (authManager.isEmployee(this.props.role)) { this.props.getAllOpenRoomsIds(); this.props.getGlobalSolvedUnsolvedStatistics(); } } onClose(e) { console.log(e); } render()...
{ this.onNewRoomAction(data); }
conditional_block
__init__.py
from enum import IntEnum __all__ = ['HTTPStatus'] class HTTPStatus(IntEnum): """HTTP status codes and reason phrases Status codes from the following RFCs are all observed: * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * R...
UNAVAILABLE_FOR_LEGAL_REASONS = (451, 'Unavailable For Legal Reasons', 'The server is denying access to the ' 'resource as a consequence of a legal demand') # server errors INTERNAL_SERVER_ERROR = (500, 'Internal Server Error', 'Server got itself in trouble') NOT_IMPLEME...
REQUEST_HEADER_FIELDS_TOO_LARGE = (431, 'Request Header Fields Too Large', 'The server is unwilling to process the request because its header ' 'fields are too large')
random_line_split
__init__.py
from enum import IntEnum __all__ = ['HTTPStatus'] class HTTPStatus(IntEnum):
"""HTTP status codes and reason phrases Status codes from the following RFCs are all observed: * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * RFC 3229: Delta encoding in HTTP * RFC 4918: HTTP Extensions for WebDAV, obso...
identifier_body
__init__.py
from enum import IntEnum __all__ = ['HTTPStatus'] class
(IntEnum): """HTTP status codes and reason phrases Status codes from the following RFCs are all observed: * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * RFC 3229: Delta encoding in HTTP * RFC 4918: HTTP Extensions f...
HTTPStatus
identifier_name
purefa_volume.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley (simon@purestorage.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1',...
(size): """Given a human-readable byte string (e.g. 2G, 30M), return the number of bytes. Will return 0 if the argument has unexpected form. """ bytes = size[:-1] unit = size[-1] if bytes.isdigit(): bytes = int(bytes) if unit == 'P': bytes *= 11258999068426...
human_to_bytes
identifier_name
purefa_volume.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley (simon@purestorage.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1',...
if __name__ == '__main__': main()
module.exit_json(changed=False)
conditional_block
purefa_volume.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley (simon@purestorage.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1',...
def delete_volume(module, array): """ Delete Volume""" changed = True if not module.check_mode: try: array.destroy_volume(module.params['name']) if module.params['eradicate']: try: array.eradicate_volume(module.params['name']) ...
"""Update Volume""" changed = True vol = array.get_volume(module.params['name']) if human_to_bytes(module.params['size']) > vol['size']: if not module.check_mode: array.extend_volume(module.params['name'], module.params['size']) else: changed = False module.exit_json(chan...
identifier_body
purefa_volume.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Simon Dodsley (simon@purestorage.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1',...
if tgt is None: changed = True if not module.check_mode: array.copy_volume(module.params['name'], module.params['target']) elif tgt is not None and module.params['overwrite']: changed = True if not module.check_mode: array.cop...
changed = False tgt = get_target(module, array)
random_line_split
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside
impl RenderObject for FontIconRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::<St...
/// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject;
random_line_split
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject; impl RenderObject for FontIconRenderObject { fn render_...
}
{ let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::<String>("icon"), widget.get::<Brush>("icon_brush").clone(), widget.get::<String>("ico...
identifier_body
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct FontIconRenderObject; impl RenderObject for FontIconRenderObject { fn render_...
if !icon.is_empty() { ctx.render_context_2_d().begin_path(); ctx.render_context_2_d().set_font_family(icon_font); ctx.render_context_2_d().set_font_size(icon_size); ctx.render_context_2_d().set_fill_style(icon_brush); ctx.render_context_2_d().fill_t...
{ return; }
conditional_block
font_icon.rs
use crate::{ proc_macros::IntoRenderObject, render_object::*, utils::{Brush, Point, Rectangle}, }; /// The `FontIconRenderObject` holds the font icons inside /// a render object. #[derive(Debug, IntoRenderObject)] pub struct
; impl RenderObject for FontIconRenderObject { fn render_self(&self, ctx: &mut Context, global_position: &Point) { let (bounds, icon, icon_brush, icon_font, icon_size) = { let widget = ctx.widget(); ( *widget.get::<Rectangle>("bounds"), widget.clone::...
FontIconRenderObject
identifier_name
tasks.py
import hashlib import logging import os from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction from PIL import Image from olympia import amo from olympia.addons.models import ( Addon, attach_tags, attach_translations, AppSupport, Compat...
for app_range in app_ranges: IncompatibleVersions.objects.create(version=version, app=app_range.app.id, min_app_version=app_range.min, max_app_version=app...
app_ranges.extend(range.apps)
conditional_block
tasks.py
import hashlib import logging import os from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction from PIL import Image from olympia import amo from olympia.addons.models import ( Addon, attach_tags, attach_translations, AppSupport, Compat...
IncompatibleVersions.objects.create(version=version, app=app_range.app.id, min_app_version=app_range.min, max_app_version=app_range.max) log.info('Added...
if min_id and max_id: if min_id <= version.id <= max_id: app_ranges.extend(range.apps) for app_range in app_ranges:
random_line_split
tasks.py
import hashlib import logging import os from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction from PIL import Image from olympia import amo from olympia.addons.models import ( Addon, attach_tags, attach_translations, AppSupport, Compat...
(src, full_dst, **kw): """Creates a PNG of a Persona header/footer image.""" log.info('[1@None] Saving persona image: %s' % full_dst) img = ImageCheck(storage.open(src)) if not img.is_image(): log.error('Not an image: %s' % src, exc_info=True) return with storage.open(src, 'rb') as f...
save_persona_image
identifier_name
tasks.py
import hashlib import logging import os from django.conf import settings from django.core.files.storage import default_storage as storage from django.db import transaction from PIL import Image from olympia import amo from olympia.addons.models import ( Addon, attach_tags, attach_translations, AppSupport, Compat...
def rereviewqueuetheme_checksum(rqt, **kw): """Check for possible duplicate theme images.""" dupe_personas = Persona.objects.filter( checksum=make_checksum(rqt.header_path or rqt.theme.header_path, rqt.footer_path or rqt.theme.footer_path)) if dupe_personas.exists()...
theme.checksum = make_checksum(theme.header_path, theme.footer_path) dupe_personas = Persona.objects.filter(checksum=theme.checksum) if dupe_personas.exists(): theme.dupe_persona = dupe_personas[0] theme.save()
identifier_body
helpers_sync.py
import os from geotrek.flatpages.models import FlatPage from geotrek.flatpages.views import FlatPageViewSet, FlatPageMeta from django.db.models import Q class SyncRando: def __init__(self, sync): self.global_sync = sync def sync(self, lang):
self.global_sync.sync_geojson(lang, FlatPageViewSet, 'flatpages.geojson', zipfile=self.global_sync.zipfile) flatpages = FlatPage.objects.filter(published=True) if self.global_sync.source: flatpages = flatpages.filter(source__name__in=self.global_sync.source) if self.global_sync.porta...
identifier_body
helpers_sync.py
import os from geotrek.flatpages.models import FlatPage from geotrek.flatpages.views import FlatPageViewSet, FlatPageMeta from django.db.models import Q class SyncRando: def __init__(self, sync): self.global_sync = sync def sync(self, lang): self.global_sync.sync_geojson(lang, FlatPageViewS...
name = os.path.join('meta', lang, flatpage.rando_url, 'index.html') self.global_sync.sync_view(lang, FlatPageMeta.as_view(), name, pk=flatpage.pk, params={'rando_url': self.global_sync.rando_url})
conditional_block
helpers_sync.py
import os from geotrek.flatpages.models import FlatPage from geotrek.flatpages.views import FlatPageViewSet, FlatPageMeta from django.db.models import Q class SyncRando:
def __init__(self, sync): self.global_sync = sync def sync(self, lang): self.global_sync.sync_geojson(lang, FlatPageViewSet, 'flatpages.geojson', zipfile=self.global_sync.zipfile) flatpages = FlatPage.objects.filter(published=True) if self.global_sync.source: flatpag...
random_line_split
helpers_sync.py
import os from geotrek.flatpages.models import FlatPage from geotrek.flatpages.views import FlatPageViewSet, FlatPageMeta from django.db.models import Q class SyncRando: def
(self, sync): self.global_sync = sync def sync(self, lang): self.global_sync.sync_geojson(lang, FlatPageViewSet, 'flatpages.geojson', zipfile=self.global_sync.zipfile) flatpages = FlatPage.objects.filter(published=True) if self.global_sync.source: flatpages = flatpages.f...
__init__
identifier_name
plugin.js
// @require core/widget/helpers.js (function ( $, _, Svelto ) { /* PLUGIN */ let Plugin = { call ( Widget, $ele, args ) { let options = args[0], isMethodCall = ( _.isString ( options ) && options.charAt ( 0 ) !== '_' ); // Methods starting with '_' are private for ( let i = 0, l = $...
( Widget ) { if ( !Widget.config.plugin ) return; delete $.fn[Widget.config.name]; } }; /* EXPORT */ Svelto.Plugin = Plugin; }( Svelto.$, Svelto._, Svelto ));
unmake
identifier_name
plugin.js
// @require core/widget/helpers.js (function ( $, _, Svelto ) { /* PLUGIN */ let Plugin = { call ( Widget, $ele, args ) {
let options = args[0], isMethodCall = ( _.isString ( options ) && options.charAt ( 0 ) !== '_' ); // Methods starting with '_' are private for ( let i = 0, l = $ele.length; i < l; i++ ) { let instance = $.widget.get ( $ele[i], Widget, options ); if ( isMethodCall && _.isFunction...
random_line_split
plugin.js
// @require core/widget/helpers.js (function ( $, _, Svelto ) { /* PLUGIN */ let Plugin = { call ( Widget, $ele, args ) { let options = args[0], isMethodCall = ( _.isString ( options ) && options.charAt ( 0 ) !== '_' ); // Methods starting with '_' are private for ( let i = 0, l = $...
}; /* EXPORT */ Svelto.Plugin = Plugin; }( Svelto.$, Svelto._, Svelto ));
{ if ( !Widget.config.plugin ) return; delete $.fn[Widget.config.name]; }
identifier_body
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct A<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&m...
// } type T = i32; Iterator_impl!(T); type L = A<T>; type R = A<T>; #[test] fn ne_test1() { let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 0, end: 10 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, false); } #[test] fn ne_test2() { let a: L = L...
// } // }
random_line_split
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct A<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&m...
#[test] fn ne_test5() { let a: L = L { begin: 10, end: 20 }; let b: R = R { begin: 0, end: 10 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, true); } }
{ let a: L = L { begin: 0, end: 10 }; let b: R = R { begin: 10, end: 20 }; let result: bool = ne::<L, R>(a, b); assert_eq!(result, true); }
identifier_body
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::order::ne; use core::cmp::PartialEq; struct
<T: PartialEq> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) ...
A
identifier_name
multiple.py
from mininet.net import Mininet from mininet.topo import Topo from mininet.log import lg, setLogLevel from mininet.cli import CLI from mininet.node import RemoteController FANOUT = 2 SWITCH_NUM = 2 CORES = {} for i in range(1, SWITCH_NUM + 1): CORES['s%d' % i] = {} if i < 10: CORES['s%d' % i]['dpid'] =...
(Topo): def __init__(self, enable_all = True): "Create Multiple topology." # Add default members to class. super(MultipleTopo, self).__init__() # Add core switches self.cores = {} for switch in CORES: self.cores[switch] = self.addSwitch(switch, dpid=(C...
MultipleTopo
identifier_name
multiple.py
from mininet.net import Mininet from mininet.topo import Topo from mininet.log import lg, setLogLevel from mininet.cli import CLI from mininet.node import RemoteController FANOUT = 2 SWITCH_NUM = 2 CORES = {} for i in range(1, SWITCH_NUM + 1): CORES['s%d' % i] = {} if i < 10: CORES['s%d' % i]['dpid'] =...
if __name__ == '__main__': topo = MultipleTopo() net = Mininet(topo, autoSetMacs=True, xterms=False, controller=RemoteController) net.addController('c', ip='128.112.93.28') # localhost:127.0.0.1 vm-to-mac:10.0.2.2 server-to-mac:128.112.93.28 print "\nHosts configured with IPs, switches pointing to Ope...
def __init__(self, enable_all = True): "Create Multiple topology." # Add default members to class. super(MultipleTopo, self).__init__() # Add core switches self.cores = {} for switch in CORES: self.cores[switch] = self.addSwitch(switch, dpid=(CORES[switch][...
identifier_body
multiple.py
from mininet.log import lg, setLogLevel from mininet.cli import CLI from mininet.node import RemoteController FANOUT = 2 SWITCH_NUM = 2 CORES = {} for i in range(1, SWITCH_NUM + 1): CORES['s%d' % i] = {} if i < 10: CORES['s%d' % i]['dpid'] = '0000000000000%d00' % i else: CORES['s%d' % i]['d...
from mininet.net import Mininet from mininet.topo import Topo
random_line_split
multiple.py
from mininet.net import Mininet from mininet.topo import Topo from mininet.log import lg, setLogLevel from mininet.cli import CLI from mininet.node import RemoteController FANOUT = 2 SWITCH_NUM = 2 CORES = {} for i in range(1, SWITCH_NUM + 1): CORES['s%d' % i] = {} if i < 10:
else: CORES['s%d' % i]['dpid'] = '000000000000%d00' % i class MultipleTopo(Topo): def __init__(self, enable_all = True): "Create Multiple topology." # Add default members to class. super(MultipleTopo, self).__init__() # Add core switches self.cores = {} ...
CORES['s%d' % i]['dpid'] = '0000000000000%d00' % i
conditional_block
state.stories.ts
import { OptGrid } from '../types/options'; import Grid from '../src/grid'; import '../src/css/grid.css'; export default { title: 'State layer', }; function createGrid(options: Omit<OptGrid, 'el'>)
const columns = [{ name: 'name' }, { name: 'artist' }]; export const noData = () => { const { el } = createGrid({ columns, bodyHeight: 'fitToParent' }); return el; }; const noDataNote = ` ## State - If there is no data, the "no data" text is shown. `; noData.story = { parameters: { notes: noDataNote } }; ex...
{ const el = document.createElement('div'); el.style.width = '800px'; const grid = new Grid({ el, ...options }); return { el, grid }; }
identifier_body
state.stories.ts
import { OptGrid } from '../types/options'; import Grid from '../src/grid'; import '../src/css/grid.css'; export default { title: 'State layer', }; function
(options: Omit<OptGrid, 'el'>) { const el = document.createElement('div'); el.style.width = '800px'; const grid = new Grid({ el, ...options }); return { el, grid }; } const columns = [{ name: 'name' }, { name: 'artist' }]; export const noData = () => { const { el } = createGrid({ columns, bodyHeight: 'fit...
createGrid
identifier_name
state.stories.ts
import { OptGrid } from '../types/options'; import Grid from '../src/grid'; import '../src/css/grid.css'; export default { title: 'State layer', }; function createGrid(options: Omit<OptGrid, 'el'>) { const el = document.createElement('div'); el.style.width = '800px'; const grid = new Grid({ el, ...options })...
return el; }; const noDataNote = ` ## State - If there is no data, the "no data" text is shown. `; noData.story = { parameters: { notes: noDataNote } }; export const noDataWithScroll = () => { const { el } = createGrid({ columns, bodyHeight: 'fitToParent', columnOptions: { minWidth: 300 }, widt...
const columns = [{ name: 'name' }, { name: 'artist' }]; export const noData = () => { const { el } = createGrid({ columns, bodyHeight: 'fitToParent' });
random_line_split
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce() { f(); } fn
() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| { // Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter; ...
main
identifier_name
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce() { f(); } fn main() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| {
// Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter; counter += v; } }); assert_eq!(counter, 88); call(move || { // this mu...
random_line_split
unboxed-closures-counter-not-moved.rs
// run-pass // Test that we mutate a counter on the stack only when we expect to. fn call<F>(f: F) where F : FnOnce()
fn main() { let y = vec![format!("Hello"), format!("World")]; let mut counter = 22_u32; call(|| { // Move `y`, but do not move `counter`, even though it is read // by value (note that it is also mutated). for item in y { //~ WARN unused variable: `item` let v = counter...
{ f(); }
identifier_body
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl; /// Any source that can be encoded. This trait should be implemented for all types that you want...
{ (len as u64).encode(encoder) }
identifier_body
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl;
/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait. /// /// # Implementing this trait manually /// /// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `ta...
/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods. ///
random_line_split
mod.rs
//! Encoder-based structs and traits. mod encoder; mod impl_tuples; mod impls; use self::write::Writer; use crate::{config::Config, error::EncodeError, utils::Sealed}; pub mod write; pub use self::encoder::EncoderImpl; /// Any source that can be encoded. This trait should be implemented for all types that you want...
<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> { (len as u64).encode(encoder) }
encode_slice_len
identifier_name
model_deployment.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(self, bucket_name, model_name, model_version, runtime_version=_RUN_TIME_VERSION): """Deploys model on AI Platform. Args: bucket_name: Cloud Storage Bucket name that stores saved model. model_name: Model name to deploy. model_version: Model version. ...
deploy_model
identifier_name
model_deployment.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def model_exists(self, model_name): """ :param model_name: :return: """ models = self._service.projects().models() try: response = models.list( parent='projects/{}'.format(self._project_id)).execute() if response: ...
self._project_id = project_id self._service = _create_service()
identifier_body
model_deployment.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Raises: RuntimeError if deployment completes with errors. """ # For details on request body, refer to: # https://cloud.google.com/ml-engine/reference/rest/v1/projects # .models.versions/create model_version_exists = False model_versions_list = self._list...
bucket_name: Cloud Storage Bucket name that stores saved model. model_name: Model name to deploy. model_version: Model version. runtime_version: Runtime version.
random_line_split
model_deployment.py
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
else: return False except errors.HttpError as err: logging.error('%s', json.loads(err.content)['error']['message']) def _list_model_versions(self, model_name): """Lists existing model versions in the project. Args: model_na...
return True
conditional_block
sre_constants.py
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support modul...
# operators FAILURE = "failure" SUCCESS = "success" ANY = "any" ANY_ALL = "any_all" ASSERT = "assert" ASSERT_NOT = "assert_not" AT = "at" BIGCHARSET = "bigcharset" BRANCH = "branch" CALL = "call" CATEGORY = "category" CHARSET = "charset" GROUPREF = "groupref" GROUPREF_IGNORE = "groupref_ignore" GROUPREF_EXISTS = "g...
pass
identifier_body
sre_constants.py
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support modul...
def dump(f, d, prefix): items = sorted(d.items(), key=lambda a: a[1]) for k, v in items: f.write("#define %s_%s %s\n" % (prefix, k.upper(), v)) f = open("sre_constants.h", "w") f.write("""\ /* * Secret Labs' Regular Expression Engine * * regular expression matching engine * * NO...
conditional_block
sre_constants.py
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support modul...
SRE_FLAG_ASCII = 256 # use ascii "locale" # flags for INFO primitive SRE_INFO_PREFIX = 1 # has prefix SRE_INFO_LITERAL = 2 # entire pattern is literal (given by prefix) SRE_INFO_CHARSET = 4 # pattern starts with character from given set if __name__ == "__main__": def dump(f, d, prefix): items = sorted(d.i...
SRE_FLAG_DEBUG = 128 # debugging
random_line_split
sre_constants.py
# # Secret Labs' Regular Expression Engine # # various symbols used by the regular expression engine. # run this script to update the _sre include files! # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # See the sre.py file for information on usage and redistribution. # """Internal support modul...
(list): d = {} i = 0 for item in list: d[item] = i i = i + 1 return d OPCODES = makedict(OPCODES) ATCODES = makedict(ATCODES) CHCODES = makedict(CHCODES) # replacement operations for "ignore case" mode OP_IGNORE = { GROUPREF: GROUPREF_IGNORE, IN: IN_IGNORE, LITERAL: LITERAL...
makedict
identifier_name
ApplicationRegisterHelpers.js
/** * Copyright (c) 2016 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ...
App.factory('ApplicationRegisterHelpers', function(ApplicationRegisterResource, NotificationService) { return { getOfferingsOfApp: function(appGuid) { return ApplicationRegisterResource .withErrorMessage('Failed to retrieve service offerings from catalog') ...
'use strict';
random_line_split
0029_auto_20170226_0745.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import umibukela.models class
(migrations.Migration): dependencies = [ ('umibukela', '0028_cycle_materials'), ] operations = [ migrations.CreateModel( name='ProgrammeKoboRefreshToken', fields=[ ('programme', models.OneToOneField(related_name='kobo_refresh_token', primary_key=True...
Migration
identifier_name
0029_auto_20170226_0745.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import umibukela.models class Migration(migrations.Migration): dependencies = [ ('umibukela', '0028_cycle_materials'), ] operations = [ migrations.CreateModel( name='Prog...
model_name='cycleresultset', name='survey', field=models.ForeignKey(related_name='cycle_result_sets', blank=True, to='umibukela.Survey', null=True), ), ]
random_line_split
0029_auto_20170226_0745.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import umibukela.models class Migration(migrations.Migration):
dependencies = [ ('umibukela', '0028_cycle_materials'), ] operations = [ migrations.CreateModel( name='ProgrammeKoboRefreshToken', fields=[ ('programme', models.OneToOneField(related_name='kobo_refresh_token', primary_key=True, serialize=False, to='umibuk...
identifier_body
sender.service.ts
* Copyright (C) 2017-2018 Patrice Le Gurun * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This pro...
/** * @license
random_line_split
sender.service.ts
/** * @license * Copyright (C) 2017-2018 Patrice Le Gurun * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version...
}
{ let errMsg: string; const body = error.body.json() || ''; const err = JSON.stringify( body ); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; console.error( errMsg ); return throwError( errMsg ); }
identifier_body
sender.service.ts
/** * @license * Copyright (C) 2017-2018 Patrice Le Gurun * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version...
(): Observable<Sender[]> { return this.httpClient.get<Sender[]>( senderUrl ) .catch( this.handleError ); } private handleError( error: HttpResponse<any>) { let errMsg: string; const body = error.body.json() || ''; const err = JSON.stringify( body ); errMsg = ...
getSenders
identifier_name
mastodon.js
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { BrowserRouter, Route } from 'react-router-dom'; import { ScrollContext } from 'react-router-scroll-4'; import UI from '../features/ui'; import { fetchCust...
} shouldUpdateScroll (prevRouterProps, { location }) { return !(location.state?.mastodonModalKey && location.state?.mastodonModalKey !== prevRouterProps?.location?.state?.mastodonModalKey); } render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messag...
{ this.disconnect(); this.disconnect = null; }
conditional_block
mastodon.js
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { BrowserRouter, Route } from 'react-router-dom'; import { ScrollContext } from 'react-router-scroll-4'; import UI from '../features/ui'; import { fetchCust...
() { return { identity: this.identity, }; } componentDidMount() { if (this.identity.signedIn) { this.disconnect = store.dispatch(connectUserStream()); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } should...
getChildContext
identifier_name
mastodon.js
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { BrowserRouter, Route } from 'react-router-dom'; import { ScrollContext } from 'react-router-scroll-4'; import UI from '../features/ui'; import { fetchCust...
return { identity: this.identity, }; } componentDidMount() { if (this.identity.signedIn) { this.disconnect = store.dispatch(connectUserStream()); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } shouldUpdat...
identity = createIdentityContext(initialState); getChildContext() {
random_line_split
input.js
/** * @license * Visual Blocks Editor * * Copyright 2012 Google Inc. * https://developers.google.com/blockly/ * * 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.apach...
/** * Initialize the fields on this input. */ Blockly.Input.prototype.init = function() { for (var x = 0; x < this.fieldRow.length; x++) { this.fieldRow[x].init(this.sourceBlock_); } }; /** * Sever all links to this input. */ Blockly.Input.prototype.dispose = function() { for (var i = 0, field; field = t...
this.sourceBlock_.render(); } return this; };
random_line_split
input.js
/** * @license * Visual Blocks Editor * * Copyright 2012 Google Inc. * https://developers.google.com/blockly/ * * 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.apach...
return this; }; /** * Add an item to the end of the input's field row. * @param {*} field Something to add as a field. * @param {string} opt_name Language-neutral identifier which may used to find * this field again. Should be unique to the host block. * @return {!Blockly.Input} The input being append to ...
{ this.sourceBlock_.render(); // Adding a field will cause the block to change shape. this.sourceBlock_.bumpNeighbours_(); }
conditional_block
goceditor.py
#coding=UTF-8 """ This file is part of GObjectCreator. GObjectCreator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GObjectCreator is di...
def on_file_open(self, *args): dialog = gtk.FileChooserDialog( action = gtk.FILE_CHOOSER_ACTION_OPEN, buttons = (_("Cancel"), gtk.RESPONSE_CANCEL, _("Open"), gtk.RESPONSE_OK) ) if dialog.run() == gtk.RESPONSE_OK: ...
self._docs_model.new_document()
identifier_body
goceditor.py
#coding=UTF-8 """ This file is part of GObjectCreator. GObjectCreator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GObjectCreator is di...
(self, start_files=[]): locale_dir = os.path.dirname(__file__) locale_dir = os.path.abspath(locale_dir) locale_dir += os.sep + "locale" locale.setlocale(locale.LC_ALL, "") locale.bindtextdomain(self.TRANSL_DOMAIN, locale_dir) gettext.bindtextdomain(self.TRANSL_DOMAIN, ...
__init__
identifier_name
goceditor.py
#coding=UTF-8 """ This file is part of GObjectCreator. GObjectCreator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GObjectCreator is di...
else: new_path = None dialog.destroy() if new_path: content = self._documents.get_content(idx) self._docs_model.save_document(idx, new_path, content) def on_file_quit(self, *args): gtk.main_quit()...
new_path = dialog.get_filename()
conditional_block
goceditor.py
#coding=UTF-8 """ This file is part of GObjectCreator. GObjectCreator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. GObjectCreator is di...
buttons = (_("Cancel"), gtk.RESPONSE_CANCEL, _("Open"), gtk.RESPONSE_OK) ) if dialog.run() == gtk.RESPONSE_OK: file_name = dialog.get_filename() else: file_name = None dialog.destroy() if file_n...
action = gtk.FILE_CHOOSER_ACTION_OPEN,
random_line_split
network.py
# -*- coding: utf-8 -*- import socket from paramiko import SSHClient, AutoAddPolicy, AuthenticationException from bssh.utils import env from bssh.auth import get_pkey from bssh.logger import logger def
( hostname=None, port=22, username=None, password=None, pkey=None, pkey_pwd=None, sock=None, timeout=env.timeout, **kwargs ): """Connect the remote ssh server""" passauth = True if password else False pkey = pkey if passauth else get_pk...
connect
identifier_name
network.py
# -*- coding: utf-8 -*- import socket from paramiko import SSHClient, AutoAddPolicy, AuthenticationException from bssh.utils import env from bssh.auth import get_pkey from bssh.logger import logger def connect( hostname=None, port=22, username=None, password=None, pkey=None,...
"""Connect the remote ssh server""" passauth = True if password else False pkey = pkey if passauth else get_pkey(pkey, pkey_pwd) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(hostname=hostname, port=int(port), ...
identifier_body
network.py
# -*- coding: utf-8 -*- import socket from paramiko import SSHClient, AutoAddPolicy, AuthenticationException from bssh.utils import env from bssh.auth import get_pkey from bssh.logger import logger def connect( hostname=None, port=22,
pkey_pwd=None, sock=None, timeout=env.timeout, **kwargs ): """Connect the remote ssh server""" passauth = True if password else False pkey = pkey if passauth else get_pkey(pkey, pkey_pwd) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) tr...
username=None, password=None, pkey=None,
random_line_split
main.component.ts
import { Component, OnInit } from '@angular/core';
import { StateStorageService } from '../../shared'; @Component({ selector: 'jhi-main', templateUrl: './main.component.html' }) export class JhiMainComponent implements OnInit { constructor( private titleService: Title, private router: Router, private $storageService: StateStorageSe...
import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router'; import { Title } from '@angular/platform-browser';
random_line_split
main.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { StateStorageService } from '../../shared'; @Component({ selector: 'jhi-main', templateUrl: './main.c...
(routeSnapshot: ActivatedRouteSnapshot) { let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'tasksApp'; if (routeSnapshot.firstChild) { title = this.getPageTitle(routeSnapshot.firstChild) || title; } return title; ...
getPageTitle
identifier_name
main.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { StateStorageService } from '../../shared'; @Component({ selector: 'jhi-main', templateUrl: './main.c...
ngOnInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this.titleService.setTitle(this.getPageTitle(this.router.routerState.snapshot.root)); } }); } }
{ let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'tasksApp'; if (routeSnapshot.firstChild) { title = this.getPageTitle(routeSnapshot.firstChild) || title; } return title; }
identifier_body
main.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRouteSnapshot, NavigationEnd, RoutesRecognized } from '@angular/router'; import { Title } from '@angular/platform-browser'; import { StateStorageService } from '../../shared'; @Component({ selector: 'jhi-main', templateUrl: './main.c...
return title; } ngOnInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this.titleService.setTitle(this.getPageTitle(this.router.routerState.snapshot.root)); } }); } }
{ title = this.getPageTitle(routeSnapshot.firstChild) || title; }
conditional_block
imagepicker.tsx
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestion_element"; import { QuestionImagePickerModel } from "../question_imagepicker"; import { ItemValue } from "../itemvalue"; import { ReactQuestionFactory } from "./reactquestion_factory"; export class SurveyQuestionImagePicker exten...
return items; } protected get textStyle(): any { return { marginLeft: "3px", display: "inline", position: "static" }; } protected renderItem( key: string, item: ItemValue, cssClasses: any ): JSX.Element { var isChecked = this.question.isItemSelected(item); var id = this.question.i...
{ var item = this.question.visibleChoices[i]; var key = "item" + i; items.push(this.renderItem(key, item, cssClasses)); }
conditional_block
imagepicker.tsx
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestion_element"; import { QuestionImagePickerModel } from "../question_imagepicker"; import { ItemValue } from "../itemvalue"; import { ReactQuestionFactory } from "./reactquestion_factory"; export class SurveyQuestionImagePicker exten...
? this.question.imageHeight + "px" : undefined } style={style} /> ); } return ( <div key={key} className={itemClass}> <label className={cssClasses.label}> <input style={{ display: "none" }} className={...
height={ this.question.imageHeight
random_line_split
imagepicker.tsx
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestion_element"; import { QuestionImagePickerModel } from "../question_imagepicker"; import { ItemValue } from "../itemvalue"; import { ReactQuestionFactory } from "./reactquestion_factory"; export class SurveyQuestionImagePicker exten...
(): JSX.Element { var cssClasses = this.question.cssClasses; return ( <fieldset className={cssClasses.root}> <legend aria-label={this.question.locTitle.renderedHtml} /> {this.getItems(cssClasses)} </fieldset> ); } protected getItems(cssClasses: any): Array<any> { var item...
renderElement
identifier_name
imagepicker.tsx
import * as React from "react"; import { SurveyQuestionElementBase } from "./reactquestion_element"; import { QuestionImagePickerModel } from "../question_imagepicker"; import { ItemValue } from "../itemvalue"; import { ReactQuestionFactory } from "./reactquestion_factory"; export class SurveyQuestionImagePicker exten...
handleOnChange(event: any) { if (this.question.multiSelect) { if (event.target.checked) { this.question.value = this.question.value.concat(event.target.value); } else { var currValue = this.question.value; currValue.splice(this.question.value.indexOf(event.target.value), 1); ...
{ return this.questionBase as QuestionImagePickerModel; }
identifier_body
settings.py
""" Django settings for djangoApp project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import ...
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.cont...
random_line_split
get_profile_information.rs
//! `GET /_matrix/federation/*/query/profile` //! //! Endpoint to query profile information with a user id and optional field. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile use ruma_common::{api::ruma_api, MxcUri, Us...
Default::default() } } /// Profile fields to specify in query. /// /// This type can hold an arbitrary string. To check for formats that are not available as a /// documented variant here, use its string representation, obtained through `.as_str()`. #[derive(Clone, Debug, Pa...
impl Response { /// Creates an empty `Response`. pub fn new() -> Self {
random_line_split
get_profile_information.rs
//! `GET /_matrix/federation/*/query/profile` //! //! Endpoint to query profile information with a user id and optional field. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile use ruma_common::{api::ruma_api, MxcUri, Us...
{ /// Display name of the user. #[ruma_enum(rename = "displayname")] DisplayName, /// Avatar URL for the user's avatar. #[ruma_enum(rename = "avatar_url")] AvatarUrl, #[doc(hidden)] _Custom(PrivOwnedStr), } impl ProfileField { /// Creat...
ProfileField
identifier_name
lc804-unique-morse-code-words.py
# coding=utf-8 import unittest """804. Unique Morse Code Words https://leetcode.com/problems/unique-morse-code-words/description/ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: `"a"` maps to `".-"`, `"b"` maps to `"-..."`, `"c"` maps to `"-...
**Note:** * The length of `words` will be at most `100`. * Each `words[i]` will have length in range `[1, 12]`. * `words[i]` will only consist of lowercase letters. Similar Questions: """ class Solution(object): def uniqueMorseRepresentations(self, words): """ :type words: List[s...
There are 2 different transformations, "--...-." and "--...--.".
random_line_split