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
ACPF_ExportMuRaster.py
# SSURGO_ExportMuRaster.py # # Convert MUPOLYGON featureclass to raster for the specified SSURGO geodatabase. # By default any small NoData areas (< 5000 sq meters) will be filled using # the Majority value. # # Input mupolygon featureclass must have a projected coordinate system or it will skip. # Input databas...
# Update credits eIdInfo = root.find('idinfo') if not eIdInfo is None: #PrintMsg("\t\tcredits", 0) for child in eIdInfo.iter('datacred'): sCreds = child.text if sCreds.find("xxSTATExx") >= 0: #PrintMsg("\t...
if child.text == "xxSTATExx": child.text = mdState elif child.text == "xxSURVEYSxx": child.text = surveyInfo
conditional_block
ACPF_ExportMuRaster.py
# SSURGO_ExportMuRaster.py # # Convert MUPOLYGON featureclass to raster for the specified SSURGO geodatabase. # By default any small NoData areas (< 5000 sq meters) will be filled using # the Majority value. # # Input mupolygon featureclass must have a projected coordinate system or it will skip. # Input databas...
arcpy.SetProgressor("default", "Calculating raster statistics...") PrintMsg("\tCalculating raster statistics...", 0) env.pyramid = "PYRAMIDS -1 NEAREST" arcpy.env.rasterStatistics = 'STATISTICS 100 100' arcpy.CalculateStatistics_management (outputRaster, 1...
if arcpy.Exists(outputRaster): time.sleep(1)
random_line_split
get_sheet.py
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
.use_lst).reset_index() d2_3.index = range(1, d2_3.shape[0]+1) return d2_3 #df_bin, use_lst, #type_lst#, type_train, woe_dic def get_bin_ins_oot(self, type_lst=['ins', 'oot', 'oot2']): res = [] for loc, i in enumerate(type_lst): lst = [] df_tmp = self...
df_data_des = df_data_des.reset_index() df_data_des['cover'] = df_data_des['index'].apply(lambda x: round(cover_dic[x]/df.shape[0], 4)) df_data_des.index = df_data_des['index'] df_data_des.drop(columns=['index', 'count'], inplace=True) d2_2 = df_data_des.reset_index() d2_2....
identifier_body
get_sheet.py
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
]].fillna(0) #添加几行用来画画 # #n = len(Counter(df_tmp[cate])) #length = df.shape[0]//n #for i in range(n): # #df[:length] #print(df) # df.index = range(1, df.shape[0]+1) return df def ks_calc_cross(self,data,pred,y_label): ...
, 'count', 'bad_rate', 'ks'
conditional_block
get_sheet.py
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
e_lst = use_lst self.woe_dic = woe_dic self.type_train = type_train self.model = lr self.y = y def main(self): print('d2_1 = self.get_2_1_imp()',#依次放好, 'd2_2 = self.get_2_2_des()', 'd2_3 = self.get_2_3_corr()', '''d3 = self.get_bin_ins_oo...
self.us
identifier_name
get_sheet.py
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
split_name = str(type_lst[loc-1])+'<-->'+str(i) d[split_name] = [split_name for i in range(d.shape[0])] d = d[[split_name, 'slice', 'bad', 'count', 'bad_rio', 'woe' ]] lst.append(d) res.append(lst) return pd.conca...
split_name = '<-->'+str(i) else:
random_line_split
instance_list.py
# 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 agreed to in writing, software # d...
def _get_marker_instance(ctx, marker): """Get the marker instance from its cell. This returns the marker instance from the cell in which it lives """ try: im = objects.InstanceMapping.get_by_instance_uuid(ctx, marker) except exception.InstanceMappingNotFound: raise exception.Mar...
"""Wrap an instance object from the database so it is sortable. We use heapq.merge() below to do the merge sort of things from the cell databases. That routine assumes it can use regular python operators (> and <) on the contents. Since that won't work with instances from the database (and depends on t...
identifier_body
instance_list.py
# 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 agreed to in writing, software # d...
return db_inst def get_instances_sorted(ctx, filters, limit, marker, columns_to_join, sort_keys, sort_dirs): """Get a cross-cell list of instances matching filters. This iterates cells in parallel generating a unified and sorted list of instances as efficiently as possible. ...
raise exception.MarkerNotFound(marker=marker)
conditional_block
instance_list.py
# 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 agreed to in writing, software # d...
(ctx): """Generate InstanceWrapper(Instance) objects from a cell. We do this inside the thread (created by scatter_gather_all_cells()) so that we return wrappers and avoid having to iterate the combined result list in the caller again. This is run against each cell by the scatte...
do_query
identifier_name
instance_list.py
# 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 agreed to in writing, software # d...
def compare_instances(self, inst1, inst2): """Implements cmp(inst1, inst2) for the first key that is different Adjusts for the requested sort direction by inverting the result as needed. """ for skey, sdir in zip(self._sort_keys, self._sort_dirs): resultflag = 1 ...
random_line_split
youtube.rs
use anyhow::{Context, Result}; use chrono::offset::TimeZone; use log::{debug, trace}; use crate::common::{Service, YoutubeID}; fn api_prefix() -> String
/* [ { title: String, videoId: String, author: String, authorId: String, authorUrl: String, videoThumbnails: [ { quality: String, url: String, width: Int32, height: Int32 } ], description: String, descriptionHtml: String, viewCoun...
{ #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() }
identifier_body
youtube.rs
use anyhow::{Context, Result}; use chrono::offset::TimeZone; use log::{debug, trace}; use crate::common::{Service, YoutubeID}; fn api_prefix() -> String { #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() } /* [ {...
/// Important info about channel #[derive(Debug)] pub struct ChannelMetadata { pub title: String, pub thumbnail: String, pub description: String, } /// Important info about a video pub struct VideoInfo { pub id: String, pub url: String, pub title: String, pub description: String, pub th...
random_line_split
youtube.rs
use anyhow::{Context, Result}; use chrono::offset::TimeZone; use log::{debug, trace}; use crate::common::{Service, YoutubeID}; fn api_prefix() -> String { #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() } /* [ {...
Ok(new_items) => { if new_items.len() == 0 { // No more items, stop iterator None } else { current_items.extend(new_items); Some(Ok(current...
{ // Error state, prevent future iteration completed = true; // Return error Some(Err(e)) }
conditional_block
youtube.rs
use anyhow::{Context, Result}; use chrono::offset::TimeZone; use log::{debug, trace}; use crate::common::{Service, YoutubeID}; fn api_prefix() -> String { #[cfg(test)] let prefix: &str = &mockito::server_url(); #[cfg(not(test))] let prefix: &str = "https://invidio.us"; prefix.into() } /* [ {...
(&self) -> Result<ChannelMetadata> { let url = format!( "{prefix}/api/v1/channels/{chanid}", prefix = api_prefix(), chanid = self.chan_id.id ); let d: YTChannelInfo = request_data(&url)?; Ok(ChannelMetadata { title: d.author.clone(), ...
get_metadata
identifier_name
x25519.rs
// -*- mode: rust; -*- // // This file is part of x25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // Copyright (c) 2019 DebugSteven // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> // - DebugSteven <debugsteven@gmail.com> //! x25519 Diffie-Hellman ...
} /// A short-lived Diffie-Hellman secret key that can only be used to compute a single /// [`SharedSecret`]. /// /// This type is identical to the [`StaticSecret`] type, except that the /// [`EphemeralSecret::diffie_hellman`] method consumes and then wipes the secret key, and there /// are no serialization methods d...
{ self.0.as_bytes() }
identifier_body
x25519.rs
// -*- mode: rust; -*- // // This file is part of x25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // Copyright (c) 2019 DebugSteven // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> // - DebugSteven <debugsteven@gmail.com> //! x25519 Diffie-Hellman ...
(bytes: [u8; 32]) -> PublicKey { PublicKey(MontgomeryPoint(bytes)) } } impl PublicKey { /// Convert this public key to a byte array. #[inline] pub fn to_bytes(&self) -> [u8; 32] { self.0.to_bytes() } /// View this public key as a byte array. #[inline] pub fn as_bytes(&s...
from
identifier_name
x25519.rs
// -*- mode: rust; -*- // // This file is part of x25519-dalek. // Copyright (c) 2017-2019 isis lovecruft // Copyright (c) 2019 DebugSteven // See LICENSE for licensing information. // // Authors: // - isis agora lovecruft <isis@patternsinthevoid.net> // - DebugSteven <debugsteven@gmail.com> //! x25519 Diffie-Hellman ...
} #[test] #[cfg(feature = "serde")] fn serde_bincode_public_key_roundtrip() { use bincode; let public_key = PublicKey::from(X25519_BASEPOINT_BYTES); let encoded = bincode::serialize(&public_key).unwrap(); let decoded: PublicKey = bincode::deserialize(&encoded).unwrap()...
.to_bytes(); assert_eq!(result, expected); }
random_line_split
engine.rs
use std::cmp; use std::mem; use std::collections::HashMap; use std::thread::{self, Builder, Thread}; use std::time::Duration; use std::sync::mpsc::{self, Sender, Receiver}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::Mutex; use cpal; use cpal::UnknownTypeBuff...
(&self) -> (usize, Option<usize>) { // TODO: slow? benchmark this let next_hints = self.next.lock().unwrap().iter() .map(|i| i.size_hint().0).fold(0, |a, b| a + b); (self.current.size_hint().0 + next_hints, None) } }
size_hint
identifier_name
engine.rs
use std::cmp; use std::mem; use std::collections::HashMap; use std::thread::{self, Builder, Thread}; use std::time::Duration; use std::sync::mpsc::{self, Sender, Receiver}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::Mutex; use cpal; use cpal::UnknownTypeBuff...
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { // TODO: slow? benchmark this let next_hints = self.next.lock().unwrap().iter() .map(|i| i.size_hint().0).fold(0, |a, b| a + b); (self.current.size_hint().0 + next_hints, None) } }
} }
random_line_split
geomodel.go
/* Copyright 2012 Alexander Yngling 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 agreed to ...
isEven = !isEven if bit < 4 { bit = bit + 1 } else { cell[i] = GEOCELL_ALPHABET[ch] i = i + 1 bit = 0 ch = 0 } } cell = cell[:len(cell)-1] return string(cell) } func GeoCells(lat, lon float64, resolution int) []string { g := GeoCell(lat, lon, resolution) cells := make([]string, len(g), le...
} }
random_line_split
geomodel.go
/* Copyright 2012 Alexander Yngling 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 agreed to ...
bbox = NewBoundingBox(90.0, 180.0, -90.0, -180.0) for len(cell) > 0 { var subcellLonSpan float64 = (bbox.lonNE - bbox.lonSW) / GEOCELL_GRID_SIZE var subcellLatSpan float64 = (bbox.latNE - bbox.latSW) / GEOCELL_GRID_SIZE var l []int = SubdivXY(rune(cell[0])) var x int = l[0] var y int = l[1] bbox = New...
{ return bbox }
conditional_block
geomodel.go
/* Copyright 2012 Alexander Yngling 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 agreed to ...
(lat1, lon1, lat2, lon2 float64) float64 { var p1lat = DegToRad(lat1) var p1lon = DegToRad(lon1) var p2lat = DegToRad(lat2) var p2lon = DegToRad(lon2) return 6378135 * math.Acos(math.Sin(p1lat)*math.Sin(p2lat)+math.Cos(p1lat)*math.Cos(p2lat)*math.Cos(p2lon-p1lon)) } func DistanceSortedEdges(cells []string, lat, l...
Distance
identifier_name
geomodel.go
/* Copyright 2012 Alexander Yngling 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 agreed to ...
func GeoCells(lat, lon float64, resolution int) []string { g := GeoCell(lat, lon, resolution) cells := make([]string, len(g), len(g)) for i := 0; i < resolution; i++ { cells[i] = g[0 : i+1] } return cells } func Distance(lat1, lon1, lat2, lon2 float64) float64 { var p1lat = DegToRad(lat1) var p1lon = DegToR...
{ resolution = resolution + 1 north := 90.0 south := -90.0 east := 180.0 west := -180.0 isEven := true mid := 0.0 ch := 0 bit := 0 bits := []int{16, 8, 4, 2, 1} cell := make([]byte, resolution, resolution) i := 0 for i = 0; i < resolution; { if isEven { mid = (west + east) / 2 if lon > mid { ...
identifier_body
gles2.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
{ tex: GLuint, vertices: Vec<TextVertex>, } impl Batch { fn new() -> Self { Self { tex: 0, vertices: Vec::with_capacity(BATCH_MAX) } } #[inline] fn len(&self) -> usize { self.vertices.len() } #[inline] fn capacity(&self) -> usize { BATCH_MAX } #[i...
Batch
identifier_name
gles2.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
gl::VertexAttribPointer( index, $count, $gl_type, gl::FALSE, size_of::<TextVertex>() as i32, size as *const _, ); gl...
macro_rules! add_attr { ($count:expr, $gl_type:expr, $type:ty) => {
random_line_split
gles2.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
; let is_wide = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 }; let mut vertex = TextVertex { x, y: y + size_info.cell_height() as i16, glyph_x, glyph_y: glyph_y + glyph.height, u: glyph.uv_left, v: glyph.uv_bot + gly...
{ RenderingGlyphFlags::empty() }
conditional_block
gles2.rs
use std::mem::size_of; use std::ptr; use crossfont::RasterizedGlyph; use log::info; use alacritty_terminal::term::cell::Flags; use crate::display::content::RenderableCell; use crate::display::SizeInfo; use crate::gl; use crate::gl::types::*; use crate::renderer::shader::{ShaderProgram, ShaderVersion}; use crate::ren...
} impl<'a> LoadGlyph for RenderApi<'a> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { Atlas::load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { Atlas::clear_atlas(self.atlas, self.current_atlas) } } impl<'a> TextRender...
{ if !self.batch.is_empty() { self.render_batch(); } }
identifier_body
state.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
else {gl::TRUE}, if (color.mask & s::BLUE ).is_empty() {gl::FALSE} else {gl::TRUE}, if (color.mask & s::ALPHA).is_empty() {gl::FALSE} else {gl::TRUE} )}; } pub fn bind_blend_slot(gl: &gl::Gl, slot: ColorSlot, color: s::Color) { let buf = slot as gl::types::GLuint; match color.blend { ...
{gl::FALSE}
conditional_block
state.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( map...
bind_blend
identifier_name
state.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
}, } } pub fn bind_rasterizer(gl: &gl::Gl, r: &s::Rasterizer, is_embedded: bool) { unsafe { gl.FrontFace(match r.front_face { FrontFace::Clockwise => gl::CW, FrontFace::CounterClockwise => gl::CCW, }) }; match r.cull_face { CullFace::Nothing ...
random_line_split
state.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
pub fn bind_blend(gl: &gl::Gl, color: s::Color) { match color.blend { Some(b) => unsafe { gl.Enable(gl::BLEND); gl.BlendEquationSeparate( map_equation(b.color.equation), map_equation(b.alpha.equation) ); gl.BlendFuncSeparate( ...
{ match factor { s::Factor::Zero => gl::ZERO, s::Factor::One => gl::ONE, s::Factor::ZeroPlus(BlendValue::SourceColor) => gl::SRC_COLOR, s::Factor::OneMinus(BlendValue::SourceColor) => gl::ONE_MINUS_SRC_COLOR, s::Facto...
identifier_body
TestGAN.py
from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampl...
plt.savefig(filename) plt.close() def show_images(gan_imgs, orig_imgs, filename=None): n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(gan_imgs[i].reshape(28, 28)) ...
plt.show() else:
random_line_split
TestGAN.py
from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampl...
def plot_results(sizes, ddiff, dstd, control, graph_params, filename=None): plt.figure() carr = np.zeros(len(sizes)) carr.fill(control) plt.plot(sizes, carr, label=graph_params.control_legend) plt.errorbar(sizes, ddiff, yerr=dstd, label=graph_params.ddiff_legend) plt.grid(b=True) plt.xlabe...
def __init__(self, xlabel, ylabel, control_legend, ddiff_legend): self.xlabel = xlabel self.ylabel = ylabel self.control_legend = control_legend self.ddiff_legend = ddiff_legend
identifier_body
TestGAN.py
from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampl...
else: plt.savefig(filename) plt.close() def show_images(gan_imgs, orig_imgs, filename=None): n = 10 # how many digits we will display plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(gan_imgs[i].reshape(...
plt.show()
conditional_block
TestGAN.py
from __future__ import print_function, division from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import BatchNormalization, Activation, ZeroPadding2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampl...
(imgs): cols = 8 rows = (len(imgs) // cols ) + (len(imgs) % cols) # Rescale images 0 - 1 imgs = 0.5 * imgs + 0.5 fig, axs = plt.subplots(rows, cols) cnt = 0 for i in range(rows): for j in range(cols): if cnt < len(imgs): axs[i,j].imshow(imgs[cnt, :,:...
show_images
identifier_name
service.go
package campaigns import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "reflect" "regexp" "strconv" "strings" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/campaigns/graphql" ) type Service...
Data struct { CurrentUser struct { ID string `json:"id"` } `json:"currentUser"` } `json:"data"` } if ok, err := svc.client.NewRequest(usernameQuery, nil).DoRaw(ctx, &resp); err != nil || !ok { return "", errors.WithMessage(err, "failed to resolve namespace: no user logged in") } if resp.D...
func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (string, error) { if namespace == "" { // if no namespace is provided, default to logged in user as namespace var resp struct {
random_line_split
service.go
package campaigns import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "reflect" "regexp" "strconv" "strings" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/campaigns/graphql" ) type Service...
else { for file := range r.FileMatches { existing.FileMatches[file] = true } } } return repos, nil } var defaultQueryCountRegex = regexp.MustCompile(`\bcount:\d+\b`) const hardCodedCount = " count:999999" func setDefaultQueryCount(query string) string { if defaultQueryCountRegex.MatchString(query) { ...
{ repo := r.Repository repos = append(repos, &repo) ids[r.ID] = &repo }
conditional_block
service.go
package campaigns import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "reflect" "regexp" "strconv" "strings" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/campaigns/graphql" ) type Service...
(ctx context.Context, namespace, spec string, ids []ChangesetSpecID) (CampaignSpecID, string, error) { var result struct { CreateCampaignSpec struct { ID string ApplyURL string } } if ok, err := svc.client.NewRequest(createCampaignSpecMutation, map[string]interface{}{ "namespace": namespace, ...
CreateCampaignSpec
identifier_name
service.go
package campaigns import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "reflect" "regexp" "strconv" "strings" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" "github.com/sourcegraph/src-cli/internal/api" "github.com/sourcegraph/src-cli/internal/campaigns/graphql" ) type Service...
{ var tn struct { Typename string `json:"__typename"` } if err := json.Unmarshal(data, &tn); err != nil { return err } switch tn.Typename { case "FileMatch": var result struct { Repository graphql.Repository File struct { Path string } } if err := json.Unmarshal(data, &result); err !...
identifier_body
debian.py
# # Copyright (c) nexB Inc. and others. # Exatrcted from http://nexb.com and https://github.com/nexB/debian_inspector/ # Copyright (c) Peter Odding # Author: Peter Odding <peter@peterodding.com> # URL: https://github.com/xolox/python-deb-pkg-tools # SPDX-License-Identifier: MIT import logging import operator as operat...
else: upstream = version revision = "0" return cls(epoch=epoch, upstream=upstream, revision=revision) def compare(self, other_version): return compare_versions(self, other_version) def to_dict(self): return asdict(self) def tuple(self): ret...
upstream, _, revision = version.rpartition("-")
conditional_block
debian.py
# # Copyright (c) nexB Inc. and others. # Exatrcted from http://nexb.com and https://github.com/nexB/debian_inspector/ # Copyright (c) Peter Odding # Author: Peter Odding <peter@peterodding.com> # URL: https://github.com/xolox/python-deb-pkg-tools # SPDX-License-Identifier: MIT import logging import operator as operat...
def compare_versions(version1, version2): """ Compare two Version objects or strings and return one of the following integer numbers: - -1 means version1 sorts before version2 - 0 means version1 and version2 are equal - 1 means version1 sorts after version2 """ version1 = coerc...
""" Compare two version strings (upstream or revision) using Debain semantics and return one of the following integer numbers: - -1 means version1 sorts before version2 - 0 means version1 and version2 are equal - 1 means version1 sorts after version2 """ logger.debug("Comparing D...
identifier_body
debian.py
# # Copyright (c) nexB Inc. and others. # Exatrcted from http://nexb.com and https://github.com/nexB/debian_inspector/ # Copyright (c) Peter Odding # Author: Peter Odding <peter@peterodding.com> # URL: https://github.com/xolox/python-deb-pkg-tools # SPDX-License-Identifier: MIT import logging import operator as operat...
(self, other): return not self.__eq__(other) def __lt__(self, other): if type(self) is type(other): return eval_constraint(self, "<<", other) return NotImplemented def __le__(self, other): if type(self) is type(other): return eval_constraint(self, "<=", ...
__ne__
identifier_name
debian.py
# # Copyright (c) nexB Inc. and others. # Exatrcted from http://nexb.com and https://github.com/nexB/debian_inspector/ # Copyright (c) Peter Odding # Author: Peter Odding <peter@peterodding.com> # URL: https://github.com/xolox/python-deb-pkg-tools # SPDX-License-Identifier: MIT import logging import operator as operat...
upstream = version revision = "0" return cls(epoch=epoch, upstream=upstream, revision=revision) def compare(self, other_version): return compare_versions(self, other_version) def to_dict(self): return asdict(self) def tuple(self): return self.epoch,...
upstream, _, revision = version.rpartition("-") else:
random_line_split
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
Ok(r) => Some(r), } } } impl BusDevice for ProxyDevice { fn debug_label(&self) -> String { self.debug_label.clone() } fn config_register_write(&mut self, reg_idx: usize, offset: u64, data: &[u8]) { let len = data.len() as u32; let mut buffer = [0u8; 4]; ...
{ error!( "failed to read result of {:?} from child device process {}: {}", cmd, self.debug_label, e, ); None }
conditional_block
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
(&mut self, info: BusAccessInfo, data: &[u8]) { let mut buffer = [0u8; 8]; let len = data.len() as u32; buffer[0..data.len()].clone_from_slice(data); self.send_no_result(&Command::Write { len, info, data: buffer, }); } } impl Drop for Prox...
write
identifier_name
proxy.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Runs hardware devices in child processes. use std::fmt::{self, Display}; use std::time::Duration; use std::{self, io}; use base::{error, net::Uni...
self.data = data[0]; } fn read(&mut self, _info: BusAccessInfo, data: &mut [u8]) { assert!(data.len() == 1); data[0] = self.data; } fn config_register_write(&mut self, _reg_idx: usize, _offset: u64, data: &[u8]) { assert!(data.len() == 1)...
"EchoDevice".to_owned() } fn write(&mut self, _info: BusAccessInfo, data: &[u8]) { assert!(data.len() == 1);
random_line_split
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
.map_err(|_| ClientError::VersionParseError(s.to_string()))?; } } let version = Version { version: s.to_string(), major, minor, patch, }; Ok(version) } pub fn as_u64(&self) -> u64 { (self.maj...
patch = part .parse::<u64>()
random_line_split
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
(&mut self, yes: bool) -> &Self { self.disable_certificate_validation = yes; self } pub fn with_username(&mut self, username: &str) -> &Self { self.username = Some(username.to_string()); self } pub fn with_password(&mut self, password: &str) -> &Self { self.pass...
disable_certificate_validation
identifier_name
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
} #[cfg(test)] mod test { use super::*; #[test] pub fn test_version_compare() { assert_eq!( Version::parse("1.1.1").unwrap(), Version::parse("1.1.1").unwrap() ); assert!(Version::parse("7.7.0").unwrap() < Version::parse("7.7.1").unwrap()); assert!(V...
{ if !self.has_error() { return None; } if let Some(error) = &self.error { return Some(error.to_string()); } if let Some(items) = &self.items { for item in items { if let serde_json::Value::String(err) = &item["index"]["error"][...
identifier_body
client.rs
// Copyright (C) 2020 Jason Ish // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // ...
; Ok(request) } pub fn post(&self, path: &str) -> Result<reqwest::RequestBuilder, reqwest::Error> { let url = format!("{}/{}", self.url, path); let request = self .get_http_client()? .post(&url) .header("Content-Type", "application/json"); let...
{ request }
conditional_block
interactive.rs
//! Interactive picking of replacements, contained in a suggestion. //! //! The result of that pick is a bandaid. use super::*; use crossterm; use crossterm::{ cursor, event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}...
pub fn to_bandaid(&self) -> BandAid { if self.is_custom_entry() { BandAid::from(( self.custom_replacement.clone(), self.suggestion.span.clone(), )) } else { BandAid::try_from((self.suggestion, self.pick_idx)) .expe...
{ self.pick_idx + 1 == self.n_items }
identifier_body
interactive.rs
//! Interactive picking of replacements, contained in a suggestion. //! //! The result of that pick is a bandaid. use super::*; use crossterm; use crossterm::{ cursor, event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}...
{ Replacement(BandAid), /// Skip this suggestion and move on to the next suggestion. Skip, /// Jump to the previous suggestion. Previous, /// Print the help message and exit. Help, /// Skip the remaining fixes for the current file. SkipFile, /// Stop execution. Quit, ///...
Pick
identifier_name
interactive.rs
//! Interactive picking of replacements, contained in a suggestion.
use crossterm; use crossterm::{ cursor, event::{Event, KeyCode, KeyEvent, KeyModifiers}, style::{style, Attribute, Color, ContentStyle, Print, PrintStyledContent, StyledContent}, terminal, QueueableCommand, }; use std::convert::TryFrom; use std::io::{stdin, stdout}; use std::path::Path; const HELP: &...
//! //! The result of that pick is a bandaid. use super::*;
random_line_split
WebGlCanvas.ts
import { ProgramInfo, BufferInfo, setAttributes, createProgramInfoFromProgram, createBufferInfoFromArrays, setUniforms, } from 'twgl.js'; import { FlipnoteParserBase, FlipnoteStereoscopicEye } from '../parsers'; import { assert, assertBrowserEnv, isBrowser } from '../utils'; import { CanvasInterface, Canva...
(type?: string, quality?: any) { return new Promise<Blob>((resolve, reject) => this.canvas.toBlob(resolve, type, quality)); } /** * Frees any resources used by this canvas instance */ destroy() { const refs = this.refs; const gl = this.gl; const canvas = this.canvas; refs.shaders.forEac...
getBlob
identifier_name
WebGlCanvas.ts
import { ProgramInfo, BufferInfo, setAttributes, createProgramInfoFromProgram, createBufferInfoFromArrays, setUniforms, } from 'twgl.js'; import { FlipnoteParserBase, FlipnoteStereoscopicEye } from '../parsers'; import { assert, assertBrowserEnv, isBrowser } from '../utils'; import { CanvasInterface, Canva...
const bufferInfo = createBufferInfoFromArrays(this.gl, { position: { numComponents: 2, data: positions }, texcoord: { numComponents: 2, data: texCoords }, indices: indices }); // collect references to buffer objects for (let name in bufferIn...
{ for (let x = 0; x < xSubdivs; x++) { // triangle 1 indices[indicesPtr++] = (y + 0) * numVertsAcross + x; indices[indicesPtr++] = (y + 1) * numVertsAcross + x; indices[indicesPtr++] = (y + 0) * numVertsAcross + x + 1; // triangle 2 indices[indicesPtr++] = (y + 0) *...
conditional_block
WebGlCanvas.ts
import { ProgramInfo, BufferInfo, setAttributes, createProgramInfoFromProgram, createBufferInfoFromArrays, setUniforms, } from 'twgl.js'; import { FlipnoteParserBase, FlipnoteStereoscopicEye } from '../parsers'; import { assert, assertBrowserEnv, isBrowser } from '../utils'; import { CanvasInterface, Canva...
private createProgram(vertexShaderSource: string, fragmentShaderSource: string) { if (this.checkContextLoss()) return; const gl = this.gl; const vert = this.createShader(gl.VERTEX_SHADER, vertexShaderSource); const frag = this.createShader(gl.FRAGMENT_SHADER, fragmentShaderSource); const program...
{ this.setCanvasSize(this.width, this.height); const gl = this.gl; if (this.checkContextLoss()) return; this.layerProgram = this.createProgram(vertShaderLayer, fragShaderLayer); this.upscaleProgram = this.createProgram(vertShaderUpscale, fragShaderUpscale); this.quadBuffer = this.createScreenQua...
identifier_body
WebGlCanvas.ts
import { ProgramInfo, BufferInfo, setAttributes, createProgramInfoFromProgram, createBufferInfoFromArrays, setUniforms, } from 'twgl.js'; import { FlipnoteParserBase, FlipnoteStereoscopicEye } from '../parsers'; import { assert, assertBrowserEnv, isBrowser } from '../utils'; import { CanvasInterface, Canva...
CanvasStereoscopicMode.Dual, // CanvasStereoscopicMode.Anaglyph, // couldn't get this working, despite spending lots of time on it :/ ]; /** */ stereoscopeMode = CanvasStereoscopicMode.None; /** */ stereoscopeStrength = 0; private options: WebglCanvasOptions; private layerProgram: ProgramInfo; //...
/** */ frameIndex: number; /** */ supportedStereoscopeModes = [ CanvasStereoscopicMode.None,
random_line_split
tables.py
__all__ = [ 'CombineTables', 'ReshapeTable', 'ExtractArray', 'SplitTableOnArray', ] __displayname__ = 'Table Operations' import numpy as np import pandas as pd import vtk from vtk.util import numpy_support as nps from vtk.numpy_interface import dataset_adapter as dsa # Import Helpers: from ..base impo...
def Apply(self, inputDataObject, arrayName): self.SetInputDataObject(inputDataObject) arr, field = _helpers.searchForArray(inputDataObject, arrayName) self.SetInputArrayToProcess(0, 0, 0, field, arrayName) self.Update() return self.GetOutput() ############################...
return 1
random_line_split
tables.py
__all__ = [ 'CombineTables', 'ReshapeTable', 'ExtractArray', 'SplitTableOnArray', ] __displayname__ = 'Table Operations' import numpy as np import pandas as pd import vtk from vtk.util import numpy_support as nps from vtk.numpy_interface import dataset_adapter as dsa # Import Helpers: from ..base impo...
def SetNumberOfRows(self, nrows): """Set the number of rows for the output ``vtkTable`` """ if isinstance(nrows, float): nrows = int(nrows) if self.__nrows != nrows: self.__nrows = nrows self.Modified() def SetOrder(self, order): """...
"""Set the number of columns for the output ``vtkTable`` """ if isinstance(ncols, float): ncols = int(ncols) if self.__ncols != ncols: self.__ncols = ncols self.Modified()
identifier_body
tables.py
__all__ = [ 'CombineTables', 'ReshapeTable', 'ExtractArray', 'SplitTableOnArray', ] __displayname__ = 'Table Operations' import numpy as np import pandas as pd import vtk from vtk.util import numpy_support as nps from vtk.numpy_interface import dataset_adapter as dsa # Import Helpers: from ..base impo...
(self, **kwargs): FilterBase.__init__(self, nInputPorts=1, inputType='vtkTable', nOutputPorts=1, outputType='vtkTable') # Parameters self.__nrows = kwargs.get('nrows', 1) self.__ncols = kwargs.get('ncols', 1) self.__names = kwargs.get('names', []) ...
__init__
identifier_name
tables.py
__all__ = [ 'CombineTables', 'ReshapeTable', 'ExtractArray', 'SplitTableOnArray', ] __displayname__ = 'Table Operations' import numpy as np import pandas as pd import vtk from vtk.util import numpy_support as nps from vtk.numpy_interface import dataset_adapter as dsa # Import Helpers: from ..base impo...
else: self.__names = ['Field %d' % i for i in range(self.__ncols)] # Make a 2D numpy array and fill with data from input table data = np.empty((rows,cols)) for i in range(cols): c = pdi.GetColumn(i) data[:,i] = interface.convertArray(c) if (...
raise _helpers.PVGeoError('Too many array names. `ncols` specified as %d and %d names given.' % (self.__ncols, num))
conditional_block
testdriver.py
import os import os.path import datetime import time import sys import yaml import requests import re CLUSTER_FOLDER = ".cluster/" PRIVATE_KEY_FILE = f"{CLUSTER_FOLDER}key" PUBLIC_KEY_FILE = f"{CLUSTER_FOLDER}key.pub" TIMEOUT_SECONDS = 3600 def prerequisites(): """ Checks the prerequisites of this script and fail...
(): """Launch a cluster. This function creates a folder .cluster/ where everything related to the cluster is stored. In the cluster definition, the 'publicKeys' section is extended with a generated public key. The according private key is used to access the cluster later. If the cluster laun...
launch
identifier_name
testdriver.py
import os import os.path import datetime import time import sys import yaml import requests import re CLUSTER_FOLDER = ".cluster/" PRIVATE_KEY_FILE = f"{CLUSTER_FOLDER}key" PUBLIC_KEY_FILE = f"{CLUSTER_FOLDER}key.pub" TIMEOUT_SECONDS = 3600 def prerequisites(): """ Checks the prerequisites of this script and fail...
if not dry_run: log(f"Terminating the test cluster...") terminate() log("T2 test driver finished.")
log("Interactive mode. The testdriver will be open for business until you stop it by creating a file /cluster_lock") while not os.path.exists('/cluster_lock'): time.sleep(5)
conditional_block
testdriver.py
import os import os.path import datetime import time import sys import yaml import requests import re CLUSTER_FOLDER = ".cluster/" PRIVATE_KEY_FILE = f"{CLUSTER_FOLDER}key" PUBLIC_KEY_FILE = f"{CLUSTER_FOLDER}key.pub" TIMEOUT_SECONDS = 3600 def prerequisites(): """ Checks the prerequisites of this script and fail...
def get_cluster(t2_url, t2_token, id): """Get the cluster information using T2 REST API Returns: - JSON representing cluster (REST response) """ response = requests.get(f"{t2_url}/api/clusters/{id}", headers={ "t2-token": t2_token }) if(response.status_code != 200): log(f"API call to...
"""Create a cluster using T2 REST API Returns: - JSON representing cluster (REST response) """ response = requests.post(f"{t2_url}/api/clusters", data=cluster_definition, headers={ "t2-token": t2_token, "Content-Type": "application/yaml" }) if(response.status_code != 200): log(f"API call to...
identifier_body
testdriver.py
import os import os.path import datetime import time import sys import yaml import requests import re CLUSTER_FOLDER = ".cluster/" PRIVATE_KEY_FILE = f"{CLUSTER_FOLDER}key" PUBLIC_KEY_FILE = f"{CLUSTER_FOLDER}key.pub" TIMEOUT_SECONDS = 3600 def prerequisites(): """ Checks the prerequisites of this script and fail...
def run_test_script(): if os.path.isfile("/test.sh"): os.system('rm -rf /target/stackable-versions.txt || true') os.system('rm -rf /target/test_output.log || true') os.system('touch /target/test_output.log') os.system(f"chown {uid_gid_output} /target/test_output.log") os.syst...
return 'INTERACTIVE_MODE' in os.environ and os.environ['INTERACTIVE_MODE']=='true'
random_line_split
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
#[cfg(test)] mod tests { use super::*; /// Just make sure json parsing produces a proper list. /// If the alias map length changes, keep this test in sync. #[test] fn test_auto_namespace_map() { let dp_opts = Opts::default().decl_opts(); assert_eq!(dp_opts.auto_namespace_map.len()...
{ use std::io::Write; for line in std::io::stdin().lock().lines() { let mut buf = Vec::new(); f(Path::new(&line?).to_path_buf(), &mut buf)?; // Account for utf-8 encoding and text streams with the python test runner: // https://stackoverflow.com/questions/3586923/counting-unicode...
identifier_body
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
{ /// Input file(s) filenames: Vec<PathBuf>, /// Read a list of files (one-per-line) from this file #[clap(long)] input_file_list: Option<PathBuf>, } #[derive(Parser, Debug)] enum Command { /// Assemble HHAS file(s) into HackCUnit. Prints those HCUs' HHAS representation. Assemble(assemble...
FileOpts
identifier_name
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
// Test Decls-in-Compilation None if opts.daemon && opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile_daemon(&mut opts) } None if opts.flag_commands.test_compile_with_decls => { compile::test_decl_compile(&mut opts, &mut std::io::stdout(...
{ facts::run_flag(&mut opts, &mut std::io::stdout()) }
conditional_block
hackc.rs
// Copyright (c) Meta Platforms, Inc. and affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod assemble; mod cmp_unit; mod compile; mod crc; mod expr_trees; mod facts; mod parse; mod util; mod verify; use ::compile::EnvFlags; us...
for_debugger_eval: bool, #[clap(long, default_value("0"))] emit_class_pointers: i32, #[clap(long, default_value("0"))] check_int_overflow: i32, /// Number of parallel worker threads for subcommands that support parallelism, /// otherwise ignored. If 0, use available parallelism, typically...
#[clap(long)] disable_toplevel_elaboration: bool, /// Mutate the program as if we're in the debugger repl #[clap(long)]
random_line_split
conductor.go
package cmd import ( "context" "sync" "time" "github.com/cockroachdb/errors" "github.com/cockroachdb/logtags" "github.com/knz/shakespeare/pkg/crdb/log" ) // conduct runs the play. func (ap *app) conduct(ctx context.Context) (err error) { // Start the audition. This initializes the epoch, and thus needs to //...
log.Errorf(ctx, "complaint during %s: %+v", prefix, stErr) finalErr = combineErrors(finalErr, stErr) } return errors.WithContextTags(errors.Wrap(finalErr, prefix), ctx) } type terminate struct{} func ignCancel(err error) error { if errors.Is(err, context.Canceled) { return nil } return err }
{ continue }
conditional_block
conductor.go
package cmd import ( "context" "sync" "time" "github.com/cockroachdb/errors" "github.com/cockroachdb/logtags" "github.com/knz/shakespeare/pkg/crdb/log" ) // conduct runs the play. func (ap *app) conduct(ctx context.Context) (err error) { // Start the audition. This initializes the epoch, and thus needs to //...
interrupt = false } wgau.Wait() auDone() // in case not called before. // Fourth stage: wait for the collector to finish. finalErr = combineErrors(ignCancel(<-th.colErrCh), finalErr) wgcol.Wait() colDone() // in case not called before. return finalErr } type theater struct { auErrCh <-chan error au ...
log.Info(ctx, "something went wrong after spotlights terminated, cancelling audience and collector") auDone() finalErr = combineErrors(ignCancel(<-th.auErrCh), finalErr) colDone() finalErr = combineErrors(ignCancel(<-th.colErrCh), finalErr)
random_line_split
conductor.go
package cmd import ( "context" "sync" "time" "github.com/cockroachdb/errors" "github.com/cockroachdb/logtags" "github.com/knz/shakespeare/pkg/crdb/log" ) // conduct runs the play. func (ap *app) conduct(ctx context.Context) (err error) { // Start the audition. This initializes the epoch, and thus needs to //...
(ctx context.Context) error { return ap.runForAllActors(ctx, "cleanup", func(a *actor) string { return a.cleanupScript }) } func (ap *app) runForAllActors( ctx context.Context, prefix string, getScript func(a *actor) string, ) (err error) { // errCh collects the errors from the concurrent actors. errCh := make(cha...
runCleanup
identifier_name
conductor.go
package cmd import ( "context" "sync" "time" "github.com/cockroachdb/errors" "github.com/cockroachdb/logtags" "github.com/knz/shakespeare/pkg/crdb/log" ) // conduct runs the play. func (ap *app) conduct(ctx context.Context) (err error) { // Start the audition. This initializes the epoch, and thus needs to //...
func collectErrors( ctx context.Context, closers []func(), errCh chan error, prefix string, ) (finalErr error) { // Wait on the first error return. select { case err := <-errCh: if err != nil { log.Errorf(ctx, "complaint during %s: %+v", prefix, err) finalErr = combineErrors(finalErr, err) } } // Sign...
{ // errCh collects the errors from the concurrent actors. errCh := make(chan error, len(ap.cfg.actors)+1) defer func() { if r := recover(); r != nil { panic(r) } // At the end of the scene, make runScene() return the collected // errors. err = collectErrors(ctx, nil, errCh, prefix) }() var wg sync....
identifier_body
creat_model_save.py
# ------------------------------------------------------------------------------------------------------------ import cv2 import time as t import os import math import operator import re import sys import numpy as np from sklearn.cluster import KMeans, MiniBatchKMeans from features import sifttest as feat import cPick...
(F, M1, M2, M3, M4): a = [0, 0, 0, 0] group = int(F / 4) if int(M1 / 4) == group: a[0] = 1 if int(M2 / 4) == group: a[1] = 1 if int(M3 / 4) == group: a[2] = 1 if int(M4 / 4) == group: a[3] = 1 return np.array(a) # Finds 4 best matches for the query def matc...
accuracy
identifier_name
creat_model_save.py
# ------------------------------------------------------------------------------------------------------------ import cv2 import time as t import os import math import operator import re import sys import numpy as np from sklearn.cluster import KMeans, MiniBatchKMeans from features import sifttest as feat import cPick...
# ------------------------------------------------------------------------------------------------------------ start = t.time() print("Extracting Features: " + rootDir + " ...") # dump all features as array features = dumpFeatures(rootDir) end = t.time() print("Time Taken: ", str(round((end - start) / 60, 2))) sta...
return int((re.findall("\d+", s))[0])
identifier_body
creat_model_save.py
# ------------------------------------------------------------------------------------------------------------ import cv2 import time as t import os import math import operator import re import sys import numpy as np from sklearn.cluster import KMeans, MiniBatchKMeans from features import sifttest as feat import cPick...
# Returns the scores of the images in the dataset def getScores(q): scores = {} n = 0 curr = [float("inf"), float("inf"), float("inf"), float("inf")] currimg = ["", "", "", ""] for fname in fileList: img = dirName + "/" + fname scores[img] = 0 for leafID in imagesInLeaves: ...
# This function returns the weight of a leaf node def weight(leafID): return math.log1p(N / 1.0 * len(imagesInLeaves[leafID]))
random_line_split
creat_model_save.py
# ------------------------------------------------------------------------------------------------------------ import cv2 import time as t import os import math import operator import re import sys import numpy as np from sklearn.cluster import KMeans, MiniBatchKMeans from features import sifttest as feat import cPick...
elif scores[img] > curr[0] and scores[img] <= curr[1]: currimg[3], curr[3] = currimg[2], curr[2] currimg[2], curr[2] = currimg[1], curr[1] currimg[1], curr[1] = img, scores[img] elif scores[img] > curr[1] and scores[img] <= curr[2]: currimg[3], curr[3] = ...
currimg[3], curr[3] = currimg[2], curr[2] currimg[2], curr[2] = currimg[1], curr[1] currimg[1], curr[1] = currimg[0], curr[0] currimg[0], curr[0] = img, scores[img]
conditional_block
pipeline_v2.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score ## Part 1: read/load data def read_data(fn, filetype = "csv"):
## Part 2: explore data def take_sample(df, fraction): return df.sample(frac = fraction) def show_columns(df): return df.columns def descrip_stats(df): return df.describe() def counts_per_variable(df, x): return df.groupby(x).size() def group_and_describe(df, x): return df.groupby(x).describe() de...
if filetype == "csv": return pd.read_csv(fn) if filetype == "excel": return pd.read_excel(fn) if filetype == "sql": return pd.read_sql(fn, con=conn) else: return print("I only have CSVs at the moment!")
identifier_body
pipeline_v2.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score ## Part 1: read/load data def read_data(fn, filetype = "csv"): if filetype == "csv": return pd.read_csv(fn) i...
(df): num_cols = len(df.columns) for i in range(0, num_cols): df.iloc[:,i] = fill_col_with_mean(df.iloc[:,i]) return def fill_allNA_mode(df): num_col = len(df.columns.tolist()) for i in range(0,num_col): df_feats.iloc[:,i] = df_feats.iloc[:,i].fillna(df_feats.iloc[:,i].mode()[0]) ...
fill_whole_df_with_mean
identifier_name
pipeline_v2.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score ## Part 1: read/load data def read_data(fn, filetype = "csv"): if filetype == "csv": return pd.read_csv(fn) i...
return (correct_pred/len(predictDF)) # temporal validation from dateutil import parser def create_datetime(df, colname): # creates a new column with datetimem objects return df[colname].apply(parser.parse) def retrieve_year(df, date_column): return df[date_column].map(lambda x: x.year) def retrieve_...
correct_pred +=1
conditional_block
pipeline_v2.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score ## Part 1: read/load data def read_data(fn, filetype = "csv"): if filetype == "csv": return pd.read_csv(fn) i...
'loss': ["deviance", "exponential"], 'learning_rate': [0.01, 0.1, 0.2, 0.3], 'n_estimators': [3, 6, 10, 20, 100, 200, 500] } } def classifier_comparison(model_params, x_train, y_train, eva_metric, cv_num): comparison_results = {} for model, param_grid in model_params.items(): # initia...
"C": [10**-5, 10**-2, 10**-1, 1, 10, 10**2, 10**5] }, GradientBoostingClassifier:{
random_line_split
xfdemo.py
# xfyun-demo import requests size10m = 10*1024*1024 base_url = "https://raasr.xfyun.cn/api" prepare_url = "/prepare" upload_url = "/upload" merge_url = "/merge" getprogress_url = "/getProgress" getresult_url = "/getResult" # logger def stg_log(msg = "test log", level="info", filenanme = "./xfdemo.log", do_print = 1...
def loadArgs(): import argparse parser = argparse.ArgumentParser() # spaces in dir names/ file names are not supported parser.add_argument( '-f', '--filename', # default='0.flac', required=True, type=str, help="File to be converted" ) parser.add_a...
return 0
random_line_split
xfdemo.py
# xfyun-demo import requests size10m = 10*1024*1024 base_url = "https://raasr.xfyun.cn/api" prepare_url = "/prepare" upload_url = "/upload" merge_url = "/merge" getprogress_url = "/getProgress" getresult_url = "/getResult" # logger def stg_log(msg = "test log", level="info", filenanme = "./xfdemo.log", do_print = 1...
loadArgs(): import argparse parser = argparse.ArgumentParser() # spaces in dir names/ file names are not supported parser.add_argument( '-f', '--filename', # default='0.flac', required=True, type=str, help="File to be converted" ) parser.add_argume...
init__(self, audio_file_name, time_offset=0): from pathlib import PurePath self.__file_path = audio_file_name pathobj = PurePath(self.__file_path) self.__file_name = pathobj.parts[-1] self.__file_size = 0 self.__slice_num = 1 self.__time_offset = time_offset ...
identifier_body
xfdemo.py
# xfyun-demo import requests size10m = 10*1024*1024 base_url = "https://raasr.xfyun.cn/api" prepare_url = "/prepare" upload_url = "/upload" merge_url = "/merge" getprogress_url = "/getProgress" getresult_url = "/getResult" # logger def stg_log(msg = "test log", level="info", filenanme = "./xfdemo.log", do_print = 1...
import argparse parser = argparse.ArgumentParser() # spaces in dir names/ file names are not supported parser.add_argument( '-f', '--filename', # default='0.flac', required=True, type=str, help="File to be converted" ) parser.add_argument( '-...
gs():
identifier_name
xfdemo.py
# xfyun-demo import requests size10m = 10*1024*1024 base_url = "https://raasr.xfyun.cn/api" prepare_url = "/prepare" upload_url = "/upload" merge_url = "/merge" getprogress_url = "/getProgress" getresult_url = "/getResult" # logger def stg_log(msg = "test log", level="info", filenanme = "./xfdemo.log", do_print = 1...
# headers not required # headers = {"Content-Type": "multipart/form-data"} headers = None req_data = {"app_id": self.__appid, "signa": sign, "ts": stamp, "task_id": self.__task_id, "slice_id": current_slice_id } # be ...
g(f"reqFileSlice file ends") break
conditional_block
crea_cig_esiti_senza_duplicati.py
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import MySQLdb import urllib import urllib2 import re import string from bs4 import BeautifulSoup from datetime import datetime import datetime as dt import calendar import time import os import json as m_json import ...
(data): data=data.replace(u'\xa0', '') if data: d = datetime.strptime(data, '%d/%m/%Y') day_string = d.strftime('%Y-%m-%d') else: day_string = "1900-01-01" return day_string def prendi_provincia_regione2(comun): try: sql_co...
data_per_db
identifier_name
crea_cig_esiti_senza_duplicati.py
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import MySQLdb import urllib import urllib2 import re import string from bs4 import BeautifulSoup from datetime import datetime import datetime as dt import calendar import time import os import json as m_json import ...
elif categoria =='OS11': n_OS11= n_OS11+1 elif categoria =='OS12-A': n_OS12A= n_OS12A+1 elif categoria =='OS12-B': n_OS12B= n_OS12B+1 elif categoria =='OS13': n_OS13= n_OS13+1 elif categoria =='OS14': n_OS14= n_OS14+1 elif categoria =='OS15': n_OS...
n_OS10= n_OS10+1
conditional_block
crea_cig_esiti_senza_duplicati.py
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import MySQLdb import urllib import urllib2 import re import string from bs4 import BeautifulSoup from datetime import datetime import datetime as dt import calendar import time import os import json as m_json import ...
def converti_data (data_py): data_ita = data_py.strftime('%d-%m-%Y') sitrng = str(data_ita) return data_ita def get_session_info(): uid = "web"; access_type= "no"; info = "uid="+uid+"&pwd="+access_type; return info; account = get_session_info() def function_config(): na...
cursore = conn.cursor() cursore.execute("SELECT * FROM gare.cpv_to_cat where CPV = '"+CPV+"'") CPV_trovati = cursore.fetchall() n_OG1= 0 n_OG2 = 0 n_OG3 = 0 n_OG4 = 0 n_OG5=0 n_OG6=0 n_OG7=0 n_OG8=0 n_OG9=0 n_OG10=0 n_OG11=0 n_OG12=0 n_OG13=0 n_OS1=0 ...
identifier_body
crea_cig_esiti_senza_duplicati.py
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import MySQLdb import urllib import urllib2 import re import string from bs4 import BeautifulSoup from datetime import datetime import datetime as dt import calendar import time import os import json as m_json import ...
n_OS12B=0 n_OS13=0 n_OS14=0 n_OS15=0 n_OS16=0 n_OS17=0 n_OS18A=0 n_OS18B=0 n_OS19=0 n_OS20A=0 n_OS20B=0 n_OS21=0 n_OS22=0 n_OS23=0 n_OS24=0 n_OS25=0 n_OS26=0 n_OS27=0 n_OS28=0 n_OS29=0 n_OS30=0 n_OS31=0 n_OS32=0 n_OS33=0 ...
n_OS9=0 n_OS10=0 n_OS11=0 n_OS12A=0
random_line_split
neuralnet.py
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> from math import exp, log from scipy.optimize import fmin_bfgs from scipy.optimize import check_grad import numpy as np from numpy import array from scipy.misc import logsumexp #for parsing the trianing data import cPickle, gzip import matplotlib.pyplot ...
if patience <= iter: done_looping = True break # for the graph self.error_testing[epoch*self._batch_number + batch] = self.calculate_zero_one_loss() print "Error in ...
if this_validation_loss < best_validation_loss * improvement_threshold: patience = max(patience, iter * patience_increase) best_params = np.copy(self._betas) best_validation_loss = this_validation_loss
conditional_block
neuralnet.py
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> from math import exp, log from scipy.optimize import fmin_bfgs from scipy.optimize import check_grad import numpy as np from numpy import array from scipy.misc import logsumexp #for parsing the trianing data import cPickle, gzip import matplotlib.pyplot ...
def calculate_zero_one_loss(self,dataset="testing"): """ Arguments: - `self`: """ # A matrix P NxC have probability for each sample (=row) and for each class (=column) # as a result we have probaility for each sample (row) for each class (co...
random_line_split
neuralnet.py
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> from math import exp, log from scipy.optimize import fmin_bfgs from scipy.optimize import check_grad import numpy as np from numpy import array from scipy.misc import logsumexp #for parsing the trianing data import cPickle, gzip import matplotlib.pyplot ...
def visualize_receptive_fields(self): import sys beta_set = cPickle.load(open(self._weights_filename,"r")) beta_set = beta_set.reshape(self._D,self._hidden_layer_size).T #print beta_set.shape plt.figure(9) sys.stdout.write('Writing visualizations of rece...
f = open(self._weights_filename, 'w') cPickle.dump(self._betas[0:self._D*self._hidden_layer_size],f) f.close()
identifier_body
neuralnet.py
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> from math import exp, log from scipy.optimize import fmin_bfgs from scipy.optimize import check_grad import numpy as np from numpy import array from scipy.misc import logsumexp #for parsing the trianing data import cPickle, gzip import matplotlib.pyplot ...
(self,W): """ This will extract the weights from we big W array. in a 1-hidden layer network. this can be easily generalized. """ wl1_size = self._D*self._hidden_layer_size bl1_size = self._hidden_layer_size wl2_size = self._hidden_layer_size*self._output...
_extract_weights
identifier_name
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
pub fn try_lock(&self) -> Option<LatchGuard> { if unsafe { ffi::box_latch_trylock(self.inner) } == 0 { Some(LatchGuard { latch_inner: self.inner, }) } else { None } } } impl Drop for Latch { fn drop(&mut self) { unsafe { ff...
/// - `None` - the latch is locked.
random_line_split
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
{ unsafe { ffi::fiber_wakeup(self.inner) } } /// Wait until the fiber is dead and then move its execution status to the caller. /// /// “Join” a joinable fiber. That is, let the fiber’s function run and wait until the fiber’s status is **dead** /// (normally a status becomes **dead** when ...
&self)
identifier_name
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
op for Latch { fn drop(&mut self) { unsafe { ffi::box_latch_delete(self.inner) } } } /// An RAII implementation of a "scoped lock" of a latch. When this structure is dropped (falls out of scope), /// the lock will be unlocked. pub struct LatchGuard { latch_inner: *mut ffi::Latch, } impl Drop for L...
e } } } impl Dr
conditional_block
fiber.rs
//! Сooperative multitasking module //! //! With the fiber module, you can: //! - create, run and manage [fibers](struct.Fiber.html), //! - use a synchronization mechanism for fibers, similar to “condition variables” and similar to operating-system //! functions such as `pthread_cond_wait()` plus `pthread_cond_signal()...
the execution of the current fiber (i.e. yield) until [signal()](#method.signal) is called. /// /// Like pthread_cond, FiberCond can issue spurious wake ups caused by explicit /// [Fiber::wakeup()](struct.Fiber.html#method.wakeup) or [Fiber::cancel()](struct.Fiber.html#method.cancel) /// calls. It is h...
{ ffi::fiber_cond_broadcast(self.inner) } } /// Suspend
identifier_body
renderer.js
"use strict"; const { app, BrowserWindow } = require("electron"); const child_process = require("child_process"); const fs = require("fs"); const mkdirp = require("mkdirp"); const os = require("os"); const path = require("path"); const url = require("url"); const yauzl = require("yauzl"); // Keep a global reference o...
}; /** * Write an error message to the loading screen * @param {string} msg an error message to display on the loading screen * @param {*} err the error object that was thrown * * If an error occurs during application initialization, all resources the * application has taken so far should be freed, the error s...
{ startupWindow.webContents.send('update', msg); }
conditional_block
renderer.js
"use strict"; const { app, BrowserWindow } = require("electron"); const child_process = require("child_process"); const fs = require("fs"); const mkdirp = require("mkdirp"); const os = require("os"); const path = require("path"); const url = require("url"); const yauzl = require("yauzl"); // Keep a global reference o...
// startupWindow.webContents.openDevTools(); startupWindow.on("closed", () => { startupWindow = null }); startupWindow.webContents.once("dom-ready", (event, msg) => { resolve(); }); }); }; /** * @param {string} msg a message to display on the loading screen */ const writeStartupMess...
preload: path.join(__dirname, "preloadStartup.js") } }); startupWindow.loadFile(path.join(__dirname, "startup.html"));
random_line_split
sampleMultiMCTSAgentTrajectory.py
import time import sys import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" DIRNAME = os.path.dirname(__file__) sys.path.append(os.path.join(DIRNAME, '..', '..')) import json import numpy as np from collections import OrderedDict import pandas as pd import mujoco_py as mujoco from src.constrainedChasingEscapingEnv.env...
def main(): #check file exists or not dirName = os.path.dirname(__file__) trajectoriesSaveDirectory = os.path.join(dirName, '..', '..', 'data', 'multiAgentTrain', 'multiMCTSAgent', 'trajectories') if not os.path.exists(trajectoriesSaveDirectory): o...
def __init__(self, composeSingleAgentGuidedMCTS, approximatePolicy, MCTSAgentIds): self.composeSingleAgentGuidedMCTS = composeSingleAgentGuidedMCTS self.approximatePolicy = approximatePolicy self.MCTSAgentIds = MCTSAgentIds def __call__(self, multiAgentNNModel): multiAgentApproximat...
identifier_body