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
bootstrap_commands.py
(src).extractall(dst) if movedir: for f in os.listdir(movedir): frm = path.join(movedir, f) to = path.join(dst, f) os.rename(frm, to) os.rmdir(movedir) os.remove(src) @CommandProvider class MachCommands(CommandBase): @Command('env', descri...
gitversion_output = subprocess.check_output(["git", "--version"]) gitversion = LooseVersion(gitversion_output.split(" ")[-1]) if gitversion < LooseVersion("1.8.1"): print("Git version 1.8.1 or above required. Current version is {}" .format(gitversion)) sys.exit(...
identifier_body
bootstrap_commands.py
()) try: resp = urllib2.urlopen(src) fsize = None if resp.info().getheader('Content-Length'): fsize = int(resp.info().getheader('Content-Length').strip()) recved = 0 chunk_size = 8192 while True: chunk = resp.read(chunk_size) if...
(self, force=False): self.ensure_bootstrapped() rust_root = self.config["tools"]["rust-root"] docs_dir = path.join(rust_root, "doc") if not force and path.exists(docs_dir): print("Rust docs already downloaded.", end=" ") print("Use |bootstrap-rust-docs --force| to...
bootstrap_rustc_docs
identifier_name
bootstrap_commands.py
path.exists(path.join(rust_dir, "rustc", "bin", "rustc" + BIN_SUFFIX)): print("Rust compiler already downloaded.", end=" ") print("Use |bootstrap-rust --force| to download again.") return if path.isdir(rust_dir): shutil.rmtree(rust_dir) os.makedirs(rust_...
removing_anything = True name = path.join(base, name) if force: print("Removing " + name) shutil.rmtree(name) else: print("Would remove " + name)
conditional_block
views.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
(request): from geonode.geoserver.helpers import set_attributes_from_geoserver uuid = request.POST['uuid'] resource = get_object_or_404(ResourceBase, uuid=uuid) can_change_data = request.user.has_perm( 'change_resourcebase', resource) layer = Layer.objects.get(id=resource.id) if ...
attributes_sats_refresh
identifier_name
views.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
@require_POST def invalidate_permissions_cache(request): from .utils import sync_resources_with_guardian uuid = request.POST['uuid'] resource = get_object_or_404(ResourceBase, uuid=uuid) can_change_permissions = request.user.has_perm( 'change_resourcebase_permissions', resource) i...
return HttpResponse( 'No methods other than get and post are allowed', status=401, content_type='text/plain')
conditional_block
views.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
from django.conf import settings from django.contrib.auth import get_user_model from geonode.utils import resolve_object from geonode.base.models import ResourceBase from geonode.layers.models import Layer from geonode.people.models import Profile if "notification" in settings.INSTALLED_APPS: from notification im...
from django.utils import simplejson as json from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.views.decorators.http import require_POST from django.shortcuts import get_object_or_404
random_line_split
views.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
@require_POST def attributes_sats_refresh(request): from geonode.geoserver.helpers import set_attributes_from_geoserver uuid = request.POST['uuid'] resource = get_object_or_404(ResourceBase, uuid=uuid) can_change_data = request.user.has_perm( 'change_resourcebase', resource) layer...
from .utils import sync_resources_with_guardian uuid = request.POST['uuid'] resource = get_object_or_404(ResourceBase, uuid=uuid) can_change_permissions = request.user.has_perm( 'change_resourcebase_permissions', resource) if can_change_permissions: # Push Security Rules ...
identifier_body
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
} pub fn last() -> Error { Error::Sys(errno::Errno::last()) } pub fn invalid_argument() -> Error { Error::Sys(errno::EINVAL) } pub fn errno(&self) -> errno::Errno { match *self { Error::Sys(errno) => errno, Error::InvalidPath => errno::Errno::EI...
impl Error { pub fn from_errno(errno: errno::Errno) -> Error { Error::Sys(errno)
random_line_split
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
(errno: errno::Errno) -> Error { Error::Sys(errno) } pub fn last() -> Error { Error::Sys(errno::Errno::last()) } pub fn invalid_argument() -> Error { Error::Sys(errno::EINVAL) } pub fn errno(&self) -> errno::Errno { match *self { Error::Sys(errno) =...
from_errno
identifier_name
lib.rs
//! Rust friendly bindings to the various *nix system functions. //! //! Modules are structured according to the C header file that they would be //! defined in. #![crate_name = "nix"] #![cfg(unix)] #![allow(non_camel_case_types)] // latest bitflags triggers a rustc bug with cross-crate macro expansions causing dead_co...
} impl NixPath for Path { fn len(&self) -> usize { self.as_os_str().as_bytes().len() } fn with_nix_path<T, F>(&self, f: F) -> Result<T> where F: FnOnce(&CStr) -> T { self.as_os_str().as_bytes().with_nix_path(f) } } impl NixPath for PathBuf { fn len(&self) -> usize { self....
{ // TODO: Extract this size as a const let mut buf = [0u8; 4096]; if self.len() >= 4096 { return Err(Error::InvalidPath); } match self.iter().position(|b| *b == 0) { Some(_) => Err(Error::InvalidPath), None => { unsafe { ...
identifier_body
GoogleSettings.tsx
import React, { useState, FC } from 'react' import { useTranslation } from 'react-i18next' import { Alert, Button, Label, Input } from 'reactstrap' import FormRow from '../FormRow' import Tips from './Tips' interface Props { settingForm: object update: (settings: object) => void alert: { status: string s...
} return ( <form className="form-horizontal" role="form" onSubmit={handleSubmit}> <fieldset> <legend>{t('admin.google.legend')}</legend> <Alert color={alert.status} isOpen={!!alert.show}> {alert.message} </Alert> <Tips>{t('admin.google.tips')}</Tips> <...
'google:clientSecret': clientSecret, })
random_line_split
parser.py
#! /usr/bin/env python # -*- encoding: utf-8 -*- # vim:fenc=utf-8: from mole.event import Event from mole.action import Action, ActionSyntaxError from mole.parser import Parser class ActionParser(Parser): """This action parse the pipeline using specific parser :param `name`: a list with string representation...
(self, pipeline): self._init_item() return self.item(pipeline) def get_object(self): return self.context[self.name]
__call__
identifier_name
parser.py
#! /usr/bin/env python # -*- encoding: utf-8 -*- # vim:fenc=utf-8: from mole.event import Event from mole.action import Action, ActionSyntaxError from mole.parser import Parser class ActionParser(Parser): """This action parse the pipeline using specific parser :param `name`: a list with string representation...
def get_object(self): return self.context[self.name]
self._init_item() return self.item(pipeline)
identifier_body
parser.py
#! /usr/bin/env python # -*- encoding: utf-8 -*- # vim:fenc=utf-8: from mole.event import Event from mole.action import Action, ActionSyntaxError from mole.parser import Parser class ActionParser(Parser): """This action parse the pipeline using specific parser :param `name`: a list with string representation...
def __iter__(self): return iter(self.item) def __call__(self, pipeline): self._init_item() return self.item(pipeline) def get_object(self): return self.context[self.name]
if self.context: self.item = self.context[self.name].parser else: self.item = []
conditional_block
parser.py
#! /usr/bin/env python # -*- encoding: utf-8 -*- # vim:fenc=utf-8: from mole.event import Event from mole.action import Action, ActionSyntaxError from mole.parser import Parser class ActionParser(Parser): """This action parse the pipeline using specific parser :param `name`: a list with string representation...
def __init__(self, name,*args, **kwargs): if len(name) > 1: raise ActionSyntaxError("parser command only allow one single parameter") self.item = None self.name = name[0] def _init_item(self): if self.item is None: if self.context: self....
random_line_split
noncebased.rs
usize, nonce_prefix: Vec<u8>, /// Buffer to hold incomplete segments of plaintext, until they are complete and /// ready for encryption. plaintext: Vec<u8>, /// Next free position in `plaintext`. plaintext_pos: usize, /// A final smaller segment can be written by calling `close()`, but afte...
&mut self, buf: &[u8]) -> io::Result<usize> { if self.closed { return Err(io::Error::new( io::ErrorKind::InvalidInput, "write on closed writer", )); } let mut pos = 0; // read position in input plaintext (`buf`) loop { ...
rite(
identifier_name
noncebased.rs
: usize, nonce_prefix: Vec<u8>, /// Buffer to hold incomplete segments of plaintext, until they are complete and /// ready for encryption. plaintext: Vec<u8>, /// Next free position in `plaintext`. plaintext_pos: usize, /// A final smaller segment can be written by calling `close()`, but aft...
/// /// The scheme used for decrypting segments is specified by providing a /// [`SegmentDecrypter`] implementation. The implementation must align /// with the [`SegmentEncrypter`] used in the [`Writer`]. pub struct Reader { r: Box<dyn io::Read>, segment_decrypter: Box<dyn SegmentDecrypter>, decrypted_segme...
/// `Reader` facilitates the decryption of ciphertexts created using a [`Writer`].
random_line_split
noncebased.rs
usize, nonce_prefix: Vec<u8>, /// Buffer to hold incomplete segments of plaintext, until they are complete and /// ready for encryption. plaintext: Vec<u8>, /// Next free position in `plaintext`. plaintext_pos: usize, /// A final smaller segment can be written by calling `close()`, but afte...
} /// `SegmentDecrypter` facilitates implementing various streaming AEAD encryption modes. pub trait SegmentDecrypter { fn decrypt_segment(&self, segment: &[u8], nonce: &[u8]) -> Result<Vec<u8>, TinkError>; } /// `Reader` facilitates the decryption of ciphertexts created using a [`Writer`]. /// /// The scheme use...
let _ = self.close(); }
identifier_body
noncebased.rs
={} != pt_lim={}", self.plaintext_pos, pt_lim ), )); } let nonce = generate_segment_nonce( self.nonce_size, &self.nonce_prefix, self.encrypted_segment_cnt, /* last= */ fals...
last_segment = false; if (self.ciphertext_pos + n) < 1 { return Err(io::Error::new( io::ErrorKind::InvalidInput, "ciphertext segment too short", )); } segment = self.ciphertext_pos + n - 1; }...
conditional_block
lib.rs
//! Lettre is a mailer written in Rust. It provides a simple email builder and several transports. //! //! ## Architecture //! //! This mailer is divided into: //! //! * An `email` part: builds the email message //! * A `transport` part: contains the available transports for your emails. To be sendable, the emails have...
//! //! // Write to the local temp directory //! let mut sender = FileEmailTransport::new(temp_dir()); //! let email = EmailBuilder::new() //! .to("root@localhost") //! .from("user@localhost") //! .body("Hello World!") //! .subject("Hello") //! ...
//! use lettre::transport::file::FileEmailTransport; //! use lettre::transport::EmailTransport; //! use lettre::email::{EmailBuilder, SendableEmail};
random_line_split
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
ut self) -> Result<(), ShioriError> { trace!("Shiori::unload"); Ok(()) } fn request(&mut self, req_text: &str) -> Result<Cow<str>, ShioriError> { trace!("Shiori::request"); let res = self.request_impl(req_text); let rc = match res { Ok(value) => value, ...
Shiori::load"); self.load_dir = Path::new(dir).to_path_buf(); Ok(()) } fn unload(&m
identifier_body
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
"SHIORI/3.0 204 No Content\r\n", "Charset: UTF-8\r\n", "\r\n", ); let res = shiori.request(req).unwrap(); assert_eq!(check, res); } { let req = concat!( "GET SHIORI/3.0\r\n", "Charset: UTF-8\r\n", "Sender: SS...
"\r\n", ); let check = concat!(
random_line_split
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
c>(&mut self, req_text: &'b str) -> Result<Cow<'c, str>, &'c str> { match ShioriRequest::from_str(req_text) { Err(reason) => { let text = format!("{:?}", reason); return Ok(ShioriResponse::bad_request(&text)); } Ok(req) => { if...
t_impl<'b, '
identifier_name
api.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::ffi::OsStr; use std::sync::{Arc, Mutex}; use super::enums::Token; use super::req::ShioriRequest; use super::res::ShioriResponse; use pasta_di::shiori::*; /// SHIORI構造体 #[derive(Debug)] pub struct Shiori { dao: Arc<Mutex<HaveShioriAPI>>, hinst: usi...
} Ok(ShioriResponse::no_content()) } } impl Drop for Shiori { fn drop(&mut self) { trace!("Shiori::drop\n{:?}", self); } } impl ShioriAPI for Shiori { fn load<STR: AsRef<OsStr> + ?Sized>(&mut self, dir: &STR) -> Result<(), ShioriError> { trace!("Shiori::load"); se...
let talk = r"\1\s[10]\0\s[0]やあ、元気?\e"; return Ok(ShioriResponse::talk(talk)); } }
conditional_block
find_holes.py
def haversine2(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula d...
""" Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ lon1, lat1, lon2, lat2= coordinates[0],coordinates[1],\ coordinates[2],coordinates[3] # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, la...
identifier_body
find_holes.py
.close() pool.join() t1 = datetime.datetime.now() print t1-t0 #paths = list(paths) counter = 0 #cd Desktop/Link\ to\ SIMULATIONS/Network_Tracks/smarter_model/ grad_ideal, grad_check1, grad_check2, H_avg1, H_avg2 = 0, 0, 0, 0, 0 SHAPE = (1,1) counter2 = 0 perc_high = 0.01 #counter of how many times the points #have ...
#remove new coordinate and replace with old coordinate
random_line_split
find_holes.py
1* and *coord2*, in an array of shape (*npts*, 2). @rtype: L{ndarray} """ if npts < 2: raise Exception('nb of points must be at least 2') path = wgs84.npts(lon1=lon1, lat1=lat1, lon2=lon2, lat2=lat2, npts=npts-2) return ...
(nbins,paths, grad=False): H, xedges, yedges = np.histogram2d(paths[:,0],paths[:,1],bins=nbins) #name = "path_density_2Dhist.png" if grad: H = np.abs(np.asarray(np.gradient(H)[0]))#name = "path_density_2Dhist_grad.png" # H needs to be rotated and flipped H = np.rot90(H) H = ...
HIST2D
identifier_name
find_holes.py
lat1, lon2, lat2 = path_info[0], \ path_info[1], path_info[2], path_info[3] #lon1, lat1, lon2, lat2, dist = path_info[0], \ #path_info[1], path_info[2], path_info[3], \ #path_info[4] dist = haversine2(lon1, lat1, lon2, lat2) # interpoint distance <= 1 km, and nb of points >= 100 ...
new_coord = ps.points_in_shape(shape_path, 1)[0]
conditional_block
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx); ...
(&self) -> Model<'ctx> { Model::of_solver(self) } } impl<'ctx> Drop for Solver<'ctx> { fn drop(&mut self) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_dec_ref(self.ctx.z3_ctx, self.z3_slv); } } }
get_model
identifier_name
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx);
} } } pub fn assert(&self, ast: &Ast<'ctx>) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_assert(self.ctx.z3_ctx, self.z3_slv, ast.z3_ast); } } pub fn check(&self) -> bool...
Z3_solver_inc_ref(ctx.z3_ctx, s); s
random_line_split
solver.rs
use z3_sys::*; use Context; use Solver; use Model; use Ast; use Z3_MUTEX; impl<'ctx> Solver<'ctx> { pub fn new(ctx: &Context) -> Solver { Solver { ctx: ctx, z3_slv: unsafe { let guard = Z3_MUTEX.lock().unwrap(); let s = Z3_mk_solver(ctx.z3_ctx); ...
pub fn get_model(&self) -> Model<'ctx> { Model::of_solver(self) } } impl<'ctx> Drop for Solver<'ctx> { fn drop(&mut self) { unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_dec_ref(self.ctx.z3_ctx, self.z3_slv); } } }
{ unsafe { let guard = Z3_MUTEX.lock().unwrap(); Z3_solver_check(self.ctx.z3_ctx, self.z3_slv) == Z3_TRUE } }
identifier_body
mod.rs
ExtHandlers, method_ext_handlers: &'a MethodExtHandlers, } #[derive(Clone, Copy, Debug)] enum NullAnnotation { NonNull, Nullable, } #[derive(Debug)] struct JavaForeignTypeInfo { pub base: ForeignTypeInfo, pub java_converter: Option<JavaConverter>, annotation: Option<NullAnnotation>, } impl Fo...
} false }) .map_err(DiagnosticError::map_any_err_to_our_err)?; } Ok(ret) } fn post_proccess_code( &self, _conv_map: &mut TypeMap, _pointer_target_width: usize, mut generated_code: Vec<u8>, ) -> Result<V...
{ return true; }
conditional_block
mod.rs
ClassExtHandlers, method_ext_handlers: &'a MethodExtHandlers, } #[derive(Clone, Copy, Debug)] enum NullAnnotation { NonNull, Nullable, } #[derive(Debug)] struct JavaForeignTypeInfo { pub base: ForeignTypeInfo, pub java_converter: Option<JavaConverter>, annotation: Option<NullAnnotation>, } i...
(method: &ForeignMethod, f_method: &JniForeignMethodSignature) -> String { let need_conv = f_method.input.iter().any(|v: &JavaForeignTypeInfo| { v.java_converter .as_ref() .map(|x| !x.converter.is_empty()) .unwrap_or(false) }) || f_method .output .java...
method_name
identifier_name
mod.rs
ClassExtHandlers, method_ext_handlers: &'a MethodExtHandlers, } #[derive(Clone, Copy, Debug)] enum NullAnnotation { NonNull, Nullable, } #[derive(Debug)] struct JavaForeignTypeInfo { pub base: ForeignTypeInfo, pub java_converter: Option<JavaConverter>, annotation: Option<NullAnnotation>, } i...
traits.push(SMART_PTR_COPY_TRAIT); } let this_type: RustType = ctx.conv_map.find_or_alloc_rust_type_that_implements( &this_type_for_method, &traits, class.src_id, ); if class.smart_ptr_copy_derived() { ...
{ class .validate_class() .map_err(|err| DiagnosticError::new(class.src_id, class.span(), &err))?; if let Some(self_desc) = class.self_desc.as_ref() { let constructor_ret_type = &self_desc.constructor_ret_type; let this_type_for_method = if_ty_result_retur...
identifier_body
mod.rs
ClassExtHandlers, method_ext_handlers: &'a MethodExtHandlers, } #[derive(Clone, Copy, Debug)] enum NullAnnotation { NonNull, Nullable, } #[derive(Debug)] struct JavaForeignTypeInfo { pub base: ForeignTypeInfo, pub java_converter: Option<JavaConverter>, annotation: Option<NullAnnotation>, } i...
let mut ctx = JavaContext { cfg: self, conv_map, pointer_target_width, rust_code: &mut ret, generated_foreign_files: &mut generated_foreign_files, java_type_to_jni_sig_map: rust_code::predefined_java_type_to_jni_sig(), class_ext...
let mut generated_foreign_files = FxHashSet::default();
random_line_split
cache-data.ts
import { FeedData } from './feed-data'; export class CacheData { cacheKey: string; lastSynced: number; feedData: FeedData; public static generateCacheKey(streamID: string) { return encodeURIComponent(streamID); }
if (syncTime == null) { this.lastSynced = new Date().getTime(); } else { this.lastSynced = syncTime; } } toObject() { return { feedData: { feedID: this.feedData.feedID, feedURL: this.feedData.feedURL, ...
constructor(feedData: FeedData, syncTime?: number) { this.feedData = feedData; this.cacheKey = CacheData.generateCacheKey(feedData.feedID);
random_line_split
cache-data.ts
import { FeedData } from './feed-data'; export class CacheData { cacheKey: string; lastSynced: number; feedData: FeedData; public static generateCacheKey(streamID: string) { return encodeURIComponent(streamID); } constructor(feedData: FeedData, syncTime?: number) { this.feedDa...
} toObject() { return { feedData: { feedID: this.feedData.feedID, feedURL: this.feedData.feedURL, feedTitle: this.feedData.feedTitle, entries: this.feedData.entries.map((entry) => entry.toObject()), }, ...
{ this.lastSynced = syncTime; }
conditional_block
cache-data.ts
import { FeedData } from './feed-data'; export class
{ cacheKey: string; lastSynced: number; feedData: FeedData; public static generateCacheKey(streamID: string) { return encodeURIComponent(streamID); } constructor(feedData: FeedData, syncTime?: number) { this.feedData = feedData; this.cacheKey = CacheData.generateCacheK...
CacheData
identifier_name
socket.py
#!/usr/bin/env python3 # 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. import errno import json import logging import threading import time import websocket import parlai.chat_service.utils.lo...
(self, data, force=False): if not self.alive and not force: # Try to wait a second to send a packet timeout = 1 while timeout > 0 and not self.alive: time.sleep(0.1) timeout -= 0.1 if not self.alive: # don't try to s...
_safe_send
identifier_name
socket.py
#!/usr/bin/env python3 # 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. import errno import json import logging import threading import time import websocket import parlai.chat_service.utils.lo...
return False try: self.ws.send(data) except websocket.WebSocketConnectionClosedException: # The channel died mid-send, wait for it to come back up return False return True def _ensure_closed(self): try: self.ws.close() ...
timeout -= 0.1 if not self.alive: # don't try to send a packet if we're still dead
random_line_split
socket.py
#!/usr/bin/env python3 # 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. import errno import json import logging import threading import time import websocket import parlai.chat_service.utils.lo...
try: self.ws.send(data) except websocket.WebSocketConnectionClosedException: # The channel died mid-send, wait for it to come back up return False return True def _ensure_closed(self): try: self.ws.close() except websocket.Web...
timeout = 1 while timeout > 0 and not self.alive: time.sleep(0.1) timeout -= 0.1 if not self.alive: # don't try to send a packet if we're still dead return False
conditional_block
socket.py
#!/usr/bin/env python3 # 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. import errno import json import logging import threading import time import websocket import parlai.chat_service.utils.lo...
def on_message(*args): """ Incoming message handler for messages from the FB user. """ packet_dict = json.loads(args[1]) if packet_dict['type'] == 'conn_success': self.alive = True return # No action for successful co...
""" Disconnect event is a no-op for us, as the server reconnects automatically on a retry. """ log_utils.print_and_log( logging.INFO, 'World server disconnected: {}'.format(args) ) self.alive = False self._ensure_closed(...
identifier_body
file-loader.ts
/** * @license * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be f...
promise = deferred.promise; } else { promise = this.requests[uri].promise; } return promise; } };
{ deferred.reject(new Error('no resolver found for ' + uri)); }
conditional_block
file-loader.ts
/** * @license * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be f...
*/ request(uri:string) { var promise: Promise<string>; if (!(uri in this.requests)) { var handled = false; var deferred = new Deferred<string>(); this.requests[uri] = deferred; // loop backwards through resolvers until one "accepts" the request for (var i = this.resolvers.le...
* identical urls * * @param {string} url The absolute url to request. * @return {Promise.<string>} A promise that resolves to the contents of the URL.
random_line_split
file-loader.ts
/** * @license * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be f...
(uri:string) { var promise: Promise<string>; if (!(uri in this.requests)) { var handled = false; var deferred = new Deferred<string>(); this.requests[uri] = deferred; // loop backwards through resolvers until one "accepts" the request for (var i = this.resolvers.length - 1; i >= ...
request
identifier_name
globalRegistry-api.js
AD = testAD; if (testAD.klass) { testAD.klass.add('EntityType', EntityType); } } // make sure grBase ends in '/' var parts = this.opts.grBase.split('//'); var i = parts.length-1; parts[i] = parts[i] + '/'; parts[i] = parts[i].replace('//', '/'); this.opt...
// if this is in a testing environment: if (testAD) {
random_line_split
globalRegistry-api.js
new EntityType(entityDef); listObjects.push(entity); }); dfd.resolve(listObjects); }); return dfd; }; //**************************************************************************** /** * @function newEntityType * * Return an instance of an EntityType object. * * @param {...
{ returnObj[parts[0]] = parts[1]; }
conditional_block
slack.rs
use std::io::{Read}; use getopts; use hyper::{Client}; use hyper::status::{StatusCode}; use rustc_serialize::{json}; use super::{CreateServiceResult, Service, ServiceFactory, GetUsersResult, GetUsersError, User}; #[derive(RustcDecodable)] struct SlackUserListResponse { ok: bool, members: Vec<SlackUser>, }...
{ token: String, } impl Service for SlackService { fn get_users(&self) -> Result<GetUsersResult, GetUsersError> { let client = Client::new(); let mut response = client.get( &format!("https://slack.com/api/users.list?token={}", self.token) ).send().unwrap(); assert_...
SlackService
identifier_name
slack.rs
use std::io::{Read}; use getopts; use hyper::{Client}; use hyper::status::{StatusCode}; use rustc_serialize::{json}; use super::{CreateServiceResult, Service, ServiceFactory, GetUsersResult, GetUsersError, User}; #[derive(RustcDecodable)] struct SlackUserListResponse { ok: bool, members: Vec<SlackUser>, }...
User{ name: user.name.to_string(), email: Some(user.profile.email.clone().unwrap()), details: match (user.is_owner.unwrap(), user.is_admin.unwrap()) { (true, true) => Some("Owner/Admin".to_string()), (true, false) => Som...
random_line_split
vtkio.py
import vtk import os import os.path from vis.vtkpoly import VtkPolyModel from vis.vtkvol import VtkVolumeModel from IO.obj import OBJReader class
: def __get_reader(self, file_extension): '''Returns a reader that can read the file type having the provided extension. Returns None if no such reader.''' lower_file_ext = file_extension.lower() #if (lower_file_ext == ".tiff" or lower_file_ext == ".tif"): # return vtk.vtkTIFFReader() if (lower_f...
VtkIO
identifier_name
vtkio.py
import vtk import os import os.path from vis.vtkpoly import VtkPolyModel from vis.vtkvol import VtkVolumeModel from IO.obj import OBJReader class VtkIO: def __get_reader(self, file_extension): '''Returns a reader that can read the file type having the provided extension. Returns None if no such reader.''' lo...
if (lower_file_ext == ".ply"): return vtk.vtkPLYReader() if (lower_file_ext == ".obj"): return OBJReader() return None def load(self, file_name): """Loads the data from the file 'file_name' and returns it. Returns None if the file type is not supported.""" # Make sure the file exist...
return vtk.vtkPolyDataReader()
conditional_block
vtkio.py
import vtk import os import os.path from vis.vtkpoly import VtkPolyModel from vis.vtkvol import VtkVolumeModel from IO.obj import OBJReader class VtkIO:
# Get the right data reader depending on the file extension data_reader = self.__get_reader(os.path.splitext(file_name)[1]) if not data_reader: return None data_reader.SetFileName(file_name) data_reader.Update() return data_reader.GetOutput()
def __get_reader(self, file_extension): '''Returns a reader that can read the file type having the provided extension. Returns None if no such reader.''' lower_file_ext = file_extension.lower() #if (lower_file_ext == ".tiff" or lower_file_ext == ".tif"): # return vtk.vtkTIFFReader() if (lower_file_...
identifier_body
vtkio.py
import vtk import os import os.path from vis.vtkpoly import VtkPolyModel from vis.vtkvol import VtkVolumeModel from IO.obj import OBJReader class VtkIO: def __get_reader(self, file_extension): '''Returns a reader that can read the file type having the provided extension. Returns None if no such reader.''' lo...
return None data_reader.SetFileName(file_name) data_reader.Update() return data_reader.GetOutput()
return None # Get the right data reader depending on the file extension data_reader = self.__get_reader(os.path.splitext(file_name)[1]) if not data_reader:
random_line_split
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
n <= 255 } fn to_str(s: &[u8], i1: usize, i2: usize, i3: usize) -> String { let mut ans = String::with_capacity(s.len() + 3); ans.extend((&s[0..i1]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i1..i2]).iter().map(|u| *u as char)); ans.push('.'); ...
|n, c| n * 10 + (*c - '0' as u8) as u32);
conditional_block
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
city(s.len() + 3); ans.extend((&s[0..i1]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i1..i2]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i2..i3]).iter().map(|u| *u as char)); ans.push('.'); ans.extend((&s[i3..]).iter().map(|u| *u as...
s.len() > 3 { return false; } // 只有一个 0 可以,但 00/01 是不行的。 if s[0] == '0' as u8 { return s.len() == 1; } let n = s .iter() .fold(0 as u32, |n, c| n * 10 + (*c - '0' as u8) as u32); n <= 255 } fn to_str(s: &[u8], i1: ...
identifier_body
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
assert_eq!(res, want); } }
random_line_split
no_0093_restore_ip_addresses.rs
struct Solution; impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { let s = s.as_bytes(); let n = s.len(); let mut ans = Vec::new(); if n < 4 || n > 12 { return ans; } // i 表示在哪个索引位置放置 `.` // 每个 for 遍历最多 4 次。注意不要超出 n 的范围。 ...
if s.len() == 0 || s.len() > 3 { return false; } // 只有一个 0 可以,但 00/01 是不行的。 if s[0] == '0' as u8 { return s.len() == 1; } let n = s .iter() .fold(0 as u32, |n, c| n * 10 + (*c - '0' as u8) as u32); n <= 255 } fn to...
identifier_name
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
() -> Type { unsafe { from_glib(gobject_sys::g_binding_flags_get_type()) } } } impl<'a> FromValueOptional<'a> for BindingFlags { unsafe fn from_value_optional(value: &Value) -> Option<Self> { Some(FromValue::from_value(value)) } } impl<'a> FromValue<'a> for BindingFlags { unsafe fn fro...
static_type
identifier_name
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
type GlibType = gobject_sys::GParamFlags; fn to_glib(&self) -> gobject_sys::GParamFlags { self.bits() } } #[doc(hidden)] impl FromGlib<gobject_sys::GParamFlags> for ParamFlags { fn from_glib(value: gobject_sys::GParamFlags) -> ParamFlags { ParamFlags::from_bits_truncate(value) } } ...
} #[doc(hidden)] impl ToGlib for ParamFlags {
random_line_split
flags.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use gobject_sys; use translate::*; use value::FromValue; use value::FromValueOptional; use value::SetValue; use value::Value; use StaticType; use Type; bitflags! { pub struct Bi...
} #[doc(hidden)] impl FromGlib<gobject_sys::GSignalFlags> for SignalFlags { fn from_glib(value: gobject_sys::GSignalFlags) -> SignalFlags { SignalFlags::from_bits_truncate(value) } }
{ self.bits() }
identifier_body
organisation_document.py
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from django.core.exceptions import Va...
def show_link(self): title = self.title if self.title else '%s' % _('Untitled document') if self.url: return '<a href="%s">%s</a>' % (self.url, title,) elif self.document: return '<a href="%s">%s</a>' % (self.document.url, title,) else: return ti...
self.document.name = self.document.name.encode('ascii', 'ignore')
conditional_block
organisation_document.py
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from django.core.exceptions import Va...
def iati_language(self): return codelist_value(Language, self, 'language') def iati_language_unicode(self): return str(self.iati_language()) class Meta: app_label = 'rsr' verbose_name = _('organisation document') verbose_name_plural = _('organisation documents') ...
title = self.title if self.title else '%s' % _('Untitled document') if self.url: return '<a href="%s">%s</a>' % (self.url, title,) elif self.document: return '<a href="%s">%s</a>' % (self.document.url, title,) else: return title
identifier_body
organisation_document.py
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from django.core.exceptions import Va...
document = models.ForeignKey(OrganisationDocument, on_delete=models.CASCADE, related_name='countries', verbose_name=_('document')) country = ValidXMLCharField( _('recipient country'), blank=True, max_length=2, choices=codelist_choices(COUNTRY, show_code=False), h...
class OrganisationDocumentCountry(models.Model):
random_line_split
organisation_document.py
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from django.core.exceptions import Va...
(self): return codelist_value(DocumentCategory, self, 'category') def iati_category_unicode(self): return str(self.iati_category()) class OrganisationDocumentCountry(models.Model): document = models.ForeignKey(OrganisationDocument, on_delete=models.CASCADE, related_name='countries', ...
iati_category
identifier_name
logger.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) li...
msg_type = msg_type.rjust(10, str(" ")) appendix = appendix.replace("\n", "\\n").rjust(40, str(" ")) line += msg_type + " " + appendix + " " line += str(msg.chat_id) + "," + str(msg.message_id) line += "\n" with open(config.msg_log_file_path, "a") as log_file: log_file.write(line.encod...
pendix = ""
conditional_block
logger.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) li...
appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°" elif msg_type == "contact": appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " "...
random_line_split
logger.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def
(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) line += " " busses.status_bus["latest_messages"][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == "text" and msg.text.startsw...
log_message
identifier_name
logger.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message
appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name) elif msg_type in ["audio", "document", "game...
time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) line += " " busses.status_bus["latest_messages"][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == "text" and msg.text.startswith("/"): msg_type = "command" app...
identifier_body
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn
(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: 10, style: String::from("sneaker"), }, Shoe { ...
shoe_in_my_size
identifier_name
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn shoe_in_my_size(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: ...
else { None } } } #[test] fn calling_next_directly() { let mut counter = Counter::new(); assert_eq!(counter.next(), Some(1)); assert_eq!(counter.next(), Some(2)); assert_eq!(counter.next(), Some(3)); assert_eq!(counter.next(), Some(4)); assert_eq!(counter.next(), Some(...
{ Some(self.count) }
conditional_block
lib.rs
#[derive(PartialEq, Debug)] pub struct Shoe { pub size: i32, pub style: String, } pub fn shoe_in_my_size(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } #[test] fn filters_by_size() { let shoes = vec![Shoe { size: ...
#[derive(Debug)] pub struct Counter { pub count: u32, } impl Counter { pub fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.cou...
}]); }
random_line_split
backup.py
import os import shutil import boto from boto.s3.key import Key import subprocess from io import StringIO from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone from django.core.mail import send_mail from c...
else: dir_dest = os.path.join(dest_path, file_name) if os.path.exists(dir_dest): shutil.rmtree(os.path.join(dir_dest)) shutil.copytree(full_file_name, dir_dest) def mycb(so_far, total): print('{0} kb transferred out of {1}'.format(so...
shutil.copy(full_file_name, dest_path)
conditional_block
backup.py
import os import shutil import boto from boto.s3.key import Key import subprocess from io import StringIO from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone from django.core.mail import send_mail from c...
def copy_files(src_path, dest_path): """ :param src_path: The source folder for copying :param dest_path: The destination these files/folders should be copied to :return: None """ if not os.path.exists(src_path): os.makedirs(src_path) files = os.listdir(src_path) for file_name ...
random_line_split
backup.py
import os import shutil import boto from boto.s3.key import Key import subprocess from io import StringIO from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone from django.core.mail import send_mail from c...
shutil.copytree(full_file_name, dir_dest) def mycb(so_far, total): print('{0} kb transferred out of {1}'.format(so_far / 1024, total / 1024)) def handle_s3(tmp_path, start_time): print("Sending to S3.") file_name = '{0}.zip'.format(start_time) file_path = os.path.join(settings.BASE_...
""" :param src_path: The source folder for copying :param dest_path: The destination these files/folders should be copied to :return: None """ if not os.path.exists(src_path): os.makedirs(src_path) files = os.listdir(src_path) for file_name in files: if not file_name == 'te...
identifier_body
backup.py
import os import shutil import boto from boto.s3.key import Key import subprocess from io import StringIO from django.core.management.base import BaseCommand from django.core.management import call_command from django.conf import settings from django.utils import timezone from django.core.mail import send_mail from c...
(start_time, e, success=False): admins = models.Account.objects.filter(is_superuser=True) message = '' if not success: message = 'There was an error during the backup process.\n\n ' send_mail( 'Backup', '{0}{1}.'.format(message, e), 'backup@janeway', [user.email...
send_email
identifier_name
returnServerError.ts
// Imports import {Error} from '../interface/Error'; // Exports export function returnServerError (deferred: any) { return function (serverError: any) { let error: Error = { httpStatus: (serverError.httpStatus || 500), description: (serverError.description || 'Internal error'), error: (serverError.error ||...
for (var key in objectToValidate) { if (objectToValidate[key] === null || objectToValidate[key] === "" || objectToValidate[key] === undefined){ console.log(key, ': ', objectToValidate[key]); flag = false; } } if(!flag){ error = { httpStatus: (400), description: ('Parameters error'), }; } ret...
export function validateObject(objectToValidate: Object): any { let flag: boolean = true; let error = {};
random_line_split
returnServerError.ts
// Imports import {Error} from '../interface/Error'; // Exports export function returnServerError (deferred: any) { return function (serverError: any) { let error: Error = { httpStatus: (serverError.httpStatus || 500), description: (serverError.description || 'Internal error'), error: (serverError.error ||...
} if(!flag){ error = { httpStatus: (400), description: ('Parameters error'), }; } return {flag: flag, error: error}; }
{ console.log(key, ': ', objectToValidate[key]); flag = false; }
conditional_block
returnServerError.ts
// Imports import {Error} from '../interface/Error'; // Exports export function returnServerError (deferred: any) { return function (serverError: any) { let error: Error = { httpStatus: (serverError.httpStatus || 500), description: (serverError.description || 'Internal error'), error: (serverError.error ||...
{ let flag: boolean = true; let error = {}; for (var key in objectToValidate) { if (objectToValidate[key] === null || objectToValidate[key] === "" || objectToValidate[key] === undefined){ console.log(key, ': ', objectToValidate[key]); flag = false; } } if(!flag){ error = { httpStatus: (400), ...
identifier_body
returnServerError.ts
// Imports import {Error} from '../interface/Error'; // Exports export function returnServerError (deferred: any) { return function (serverError: any) { let error: Error = { httpStatus: (serverError.httpStatus || 500), description: (serverError.description || 'Internal error'), error: (serverError.error ||...
(objectToValidate: Object): any { let flag: boolean = true; let error = {}; for (var key in objectToValidate) { if (objectToValidate[key] === null || objectToValidate[key] === "" || objectToValidate[key] === undefined){ console.log(key, ': ', objectToValidate[key]); flag = false; } } if(!flag){ er...
validateObject
identifier_name
lint-exceeding-bitshifts.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 n = 1u16 >> 15; let n = 1u16 >> 16; //~ ERROR: attempt to shift right with overflow let n = 1u32 >> 31; let n = 1u32 >> 32; //~ ERROR: attempt to shift right with overflow let n = 1u64 >> 63; let n = 1u64 >> 64; //~ ERROR: attempt to shift right with overflow let n = 1i8 >>...
{ let n = 1u8 << 7; let n = 1u8 << 8; //~ ERROR: attempt to shift left with overflow let n = 1u16 << 15; let n = 1u16 << 16; //~ ERROR: attempt to shift left with overflow let n = 1u32 << 31; let n = 1u32 << 32; //~ ERROR: attempt to shift left with overflow let n = 1u64 << 6...
identifier_body
lint-exceeding-bitshifts.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 n = 1u8 << -8; //~ ERROR: attempt to shift left with overflow let n = 1i8<<(1isize+-1); }
let n = n << 7; let n = n << 8; //~ ERROR: attempt to shift left with overflow
random_line_split
lint-exceeding-bitshifts.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 n = 1u8 << 7; let n = 1u8 << 8; //~ ERROR: attempt to shift left with overflow let n = 1u16 << 15; let n = 1u16 << 16; //~ ERROR: attempt to shift left with overflow let n = 1u32 << 31; let n = 1u32 << 32; //~ ERROR: attempt to shift left with overflow let n = 1u64 <...
main
identifier_name
0045.py
#!/usr/bin/env python # #45! The second number which is triangular, pentagonal, and hexagonal! # Luckily, all triangular numbers are all hexagonal!
# Option 2: Find some relation between hexagonal and pentagonal numbers... # Pentagon Numbers: # Find pairs of pentagonal numbers (Pn == n*(3*n-1)/2) # which are separated by another pentagonal number... # and sum to another pentagonal number # Minimize their difference import math MAX = 220000 def pentagonal(n): ...
# For some reason, (N^2 + N)/2 == (2M^2 - M) # Option 1: Just check all hexagonal numbers for pentagonalness...
random_line_split
0045.py
#!/usr/bin/env python # #45! The second number which is triangular, pentagonal, and hexagonal! # Luckily, all triangular numbers are all hexagonal! # For some reason, (N^2 + N)/2 == (2M^2 - M) # Option 1: Just check all hexagonal numbers for pentagonalness... # Option 2: Find some relation between hexagonal and p...
# Searched 2200 numbers and found only hexagonal number 143 (correctly) in 0.043s # increase the max! # Searched 22000 numbers and no change in results in 0.083s # At 220000, found 27693 in 0.534s! (0.535 to 0.580 with printing the hexagon (& triangular and pentagonal) number)
hexagon = i*(2*i-1) if is_pentagonal(hexagon): print str(i) + " " + str(hexagon) i +=1
conditional_block
0045.py
#!/usr/bin/env python # #45! The second number which is triangular, pentagonal, and hexagonal! # Luckily, all triangular numbers are all hexagonal! # For some reason, (N^2 + N)/2 == (2M^2 - M) # Option 1: Just check all hexagonal numbers for pentagonalness... # Option 2: Find some relation between hexagonal and p...
# The secret is actually the upper and lower bounds checking on the is_pentagonal() above... # 2/3 is a loose lower bound, based on the fact that 2n^2 > 2/3(3n^2-n), because n^2 > n for all n > 1 i = 1 while i < MAX: hexagon = i*(2*i-1) if is_pentagonal(hexagon): print str(i) + " " + str(hexagon) i +=1 # Sear...
g = int(math.sqrt(n*2/3)) #g = 1 while g < MAX * 2: pentagon = g * (3*g-1)/2 if n == pentagon: return True elif pentagon > n: return False g += 1 return False
identifier_body
0045.py
#!/usr/bin/env python # #45! The second number which is triangular, pentagonal, and hexagonal! # Luckily, all triangular numbers are all hexagonal! # For some reason, (N^2 + N)/2 == (2M^2 - M) # Option 1: Just check all hexagonal numbers for pentagonalness... # Option 2: Find some relation between hexagonal and p...
(n): g = int(math.sqrt(n*2/3)) #g = 1 while g < MAX * 2: pentagon = g * (3*g-1)/2 if n == pentagon: return True elif pentagon > n: return False g += 1 return False # The secret is actually the upper and lower bounds checking on the is_pentagonal() above... # 2/3 is a loose lower bound, based on the f...
is_pentagonal
identifier_name
serverConfigItem.ts
/******************************************************************************* * Copyright 2019 Cognizant Technology Solutions * * 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 * * ...
} } }
random_line_split
serverConfigItem.ts
/******************************************************************************* * Copyright 2019 Cognizant Technology Solutions * * 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 * * ...
(id,key, value, type, isRequired, inputType, children?: any): void { this.id = id ; this.key = key; this.value = value; this.type = type; this.inputType = inputType; this.isRequired = isRequired; if (children != undefined) { this.children = children; ...
setData
identifier_name
serverConfigItem.ts
/******************************************************************************* * Copyright 2019 Cognizant Technology Solutions * * 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 * * ...
} }
{ this.children = children; }
conditional_block
views.py
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_noop, ugettext as _ from corehq.apps.domain.decorators import login_required from corehq.apps.h...
(self): initial_data = {} if self.request.method == 'POST': return SelectControlDemoForm(self.request.POST, initial=initial_data) return SelectControlDemoForm(initial=initial_data) @property def page_context(self): return { 'controls_demo_form': self.cont...
controls_demo_form
identifier_name
views.py
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_noop, ugettext as _ from corehq.apps.domain.decorators import login_required from corehq.apps.h...
return self.get(request, *args, **kwargs)
messages.success(request, _("Form processed successfully.") ) return HttpResponseRedirect(self.page_url)
conditional_block
views.py
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_noop, ugettext as _ from corehq.apps.domain.decorators import login_required from corehq.apps.h...
@property def page_context(self): return { 'controls_demo_form': self.controls_demo_form, } def post(self, request, *args, **kwargs): if self.controls_demo_form.is_valid(): # do something to process the data # It's always best practice to give s...
initial_data = {} if self.request.method == 'POST': return SelectControlDemoForm(self.request.POST, initial=initial_data) return SelectControlDemoForm(initial=initial_data)
identifier_body
views.py
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_noop, ugettext as _ from corehq.apps.domain.decorators import login_required from corehq.apps.h...
def controls_demo_form(self): initial_data = {} if self.request.method == 'POST': return SelectControlDemoForm(self.request.POST, initial=initial_data) return SelectControlDemoForm(initial=initial_data) @property def page_context(self): return { 'cont...
return super(SelectControlDemoView, self).dispatch(request, *args, **kwargs) @property @memoized
random_line_split
index.js
var keystone = require('keystone'); var async = require('async'); var Home = keystone.list('Home'); var HappyClients = keystone.list('HappyClients'); exports = module.exports = function (req, res) { var view = new keystone.View(req, res); var locals = res.locals; locals.section = 'home'; locals.section = 'happyC...
locals.home = result; next(err); }); }); // Load the current post view.on('init', function (next) { var q = HappyClients.model.find(); q.exec(function (err, result) { locals.happyClients = result; console.log(result); next(err); }); }); // Load the happy clients //view.query('happyCli...
random_line_split
stemcf3d.py
"""The WaveBlocks Project Function for stem-plotting functions of the type f:IxI -> C with abs(f) as z-value and phase(f) as color code. This function makes a three dimensional stem plot. @author: R. Bourquin @copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin @license: Modified BSD License """ from numpy import ...
(gridu, gridv, phase, modulus, darken=None, fig=None, markerp="o", **kwargs): r"""Stemplot the modulus of a complex valued function :math:`f:I\times I -> \mathbb{C}` together with its phase in a color coded fashion. Additional keyword arguments are passed to the plot function. :param gridu: The x component...
stemcf3d
identifier_name
stemcf3d.py
"""The WaveBlocks Project Function for stem-plotting functions of the type f:IxI -> C with abs(f) as z-value and phase(f) as color code. This function makes a three dimensional stem plot. @author: R. Bourquin @copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin @license: Modified BSD License """ from numpy import ...
axes = fig.add_subplot(1, 1, 1, projection='3d') for ui, vi, wi, col in zip(gridu, gridv, modulus, rgb_colors): line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1), color=col) axes.add_line(line) axes.set_xlim3d(real(gridu).min(), real(gridu).max()) ...
# Plot to the given axis instance or retrieve the current one if fig is None: fig = gcf()
random_line_split
stemcf3d.py
"""The WaveBlocks Project Function for stem-plotting functions of the type f:IxI -> C with abs(f) as z-value and phase(f) as color code. This function makes a three dimensional stem plot. @author: R. Bourquin @copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin @license: Modified BSD License """ from numpy import ...
axes = fig.add_subplot(1, 1, 1, projection='3d') for ui, vi, wi, col in zip(gridu, gridv, modulus, rgb_colors): line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1), color=col) axes.add_line(line) axes.set_xlim3d(real(gridu).min(), real(gridu).max()...
fig = gcf()
conditional_block
stemcf3d.py
"""The WaveBlocks Project Function for stem-plotting functions of the type f:IxI -> C with abs(f) as z-value and phase(f) as color code. This function makes a three dimensional stem plot. @author: R. Bourquin @copyright: Copyright (C) 2012, 2014, 2016 R. Bourquin @license: Modified BSD License """ from numpy import ...
for ui, vi, wi, col in zip(gridu, gridv, modulus, rgb_colors): line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1), color=col) axes.add_line(line) axes.set_xlim3d(real(gridu).min(), real(gridu).max()) axes.set_ylim3d(real(gridv).min(), real(gridv).max...
r"""Stemplot the modulus of a complex valued function :math:`f:I\times I -> \mathbb{C}` together with its phase in a color coded fashion. Additional keyword arguments are passed to the plot function. :param gridu: The x components of the grid nodes of the real domain grid :math:`\Gamma` :param gridv: The y...
identifier_body
Update_W_each_3it_5s_rademacher.py
cell lengthts in each direction hx = [(csx,npad, -1.5),(csx,ncx),(csx,npad, 1.5)] hz= [(csz,npad,-1.5),(csz,ncz)] # Create mesh mesh = Mesh.TensorMesh([hx, hz],x0="CN") # Map mesh coordinates from local to UTM coordiantes #mesh.x0[2] = mesh.x0[2]-mesh.vectorCCz[-npad-1] mesh.x0[1] = mesh.x0[1]+csz/2. #mesh.x0[0] = mes...
(self, locs, rxType='phi', **kwargs): # We may not need this ... SimPEG.Survey.BaseRx.__init__(self, locs, rxType) @property def nD(self): """Number of data in the receiver.""" return self.locs.shape[0] # Not sure why ... # return int(self.lo...
__init__
identifier_name
Update_W_each_3it_5s_rademacher.py
cell lengthts in each direction hx = [(csx,npad, -1.5),(csx,ncx),(csx,npad, 1.5)] hz= [(csz,npad,-1.5),(csz,ncz)] # Create mesh mesh = Mesh.TensorMesh([hx, hz],x0="CN") # Map mesh coordinates from local to UTM coordiantes #mesh.x0[2] = mesh.x0[2]-mesh.vectorCCz[-npad-1] mesh.x0[1] = mesh.x0[1]+csz/2. #mesh.x0[0] = mes...
mapping = Maps.ExpMap(mesh) survey = DC.Survey(srclist) problem = DC.Problem3D_CC(mesh, sigmaMap=mapping) problem.pair(survey) problem.Solver = PardisoSolver survey.dobs = survey.dpred(mtrue) survey.std = 0.05*np.ones_like(survey.dobs) survey.eps = 1e-5*np.linalg.norm(survey.dobs) print '# of data: ', survey.dobs.sha...
locA = np.r_[-14.+2*(i-11)+1., z] locB = np.r_[14.-1.,z] #M = np.c_[np.arange(locA[0]+1.,12.,2),np.ones(nSrc-i)*z] #N = np.c_[np.arange(locA[0]+3.,14.,2),np.ones(nSrc-i)*z] M = np.c_[np.arange(-12.,10+1,2),np.ones(12)*z] N = np.c_[np.arange(-10.,12+1,2),np.one...
conditional_block