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
instances.go
package instance import ( "errors" "fmt" "runtime/debug" "github.com/TIBCOSoftware/flogo-contrib/action/flow/definition" "github.com/TIBCOSoftware/flogo-contrib/action/flow/model" "github.com/TIBCOSoftware/flogo-contrib/action/flow/support" "github.com/TIBCOSoftware/flogo-lib/core/data" "github.com/TIBCOSoftw...
} } } func (inst *IndependentInstance) startInstance(toStart *Instance) bool { toStart.SetStatus(model.FlowStatusActive) //if pi.Attrs == nil { // pi.Attrs = make(map[string]*data.Attribute) //} // //for _, attr := range startAttrs { // pi.Attrs[attr.Name()] = attr //} //logger.Infof("FlowInstance Flow:...
//inst.scheduleEval(host) } } else { inst.returnError = err
random_line_split
instances.go
package instance import ( "errors" "fmt" "runtime/debug" "github.com/TIBCOSoftware/flogo-contrib/action/flow/definition" "github.com/TIBCOSoftware/flogo-contrib/action/flow/model" "github.com/TIBCOSoftware/flogo-contrib/action/flow/support" "github.com/TIBCOSoftware/flogo-lib/core/data" "github.com/TIBCOSoftw...
func (inst *IndependentInstance) DoStep() bool { hasNext := false inst.ResetChanges() inst.stepID++ if inst.status == model.FlowStatusActive { // get item to be worked on item, ok := inst.workItemQueue.Pop() if ok { logger.Debug("Retrieved item from Flow Instance work queue") workItem := item.(...
{ return inst.stepID }
identifier_body
instances.go
package instance import ( "errors" "fmt" "runtime/debug" "github.com/TIBCOSoftware/flogo-contrib/action/flow/definition" "github.com/TIBCOSoftware/flogo-contrib/action/flow/model" "github.com/TIBCOSoftware/flogo-contrib/action/flow/support" "github.com/TIBCOSoftware/flogo-lib/core/data" "github.com/TIBCOSoftw...
inst.scheduleEval(host) } //if containerInst.isHandlingError { // //was the error handler, so directly under instance // host,ok := containerInst.host.(*EmbeddedInstance) // if ok { // host.SetStatus(model.FlowStatusCompleted) // host.returnData = containerInst.returnData // host.retur...
{ host.SetOutput(value.Name(), value.Value()) }
conditional_block
instances.go
package instance import ( "errors" "fmt" "runtime/debug" "github.com/TIBCOSoftware/flogo-contrib/action/flow/definition" "github.com/TIBCOSoftware/flogo-contrib/action/flow/model" "github.com/TIBCOSoftware/flogo-contrib/action/flow/support" "github.com/TIBCOSoftware/flogo-lib/core/data" "github.com/TIBCOSoftw...
(taskName string, errorType string, errorText string) *ActivityEvalError { return &ActivityEvalError{taskName: taskName, errType: errorType, errText: errorText} } type ActivityEvalError struct { taskName string errType string errText string } func (e *ActivityEvalError) TaskName() string { return e.taskName } ...
NewActivityEvalError
identifier_name
ffi.rs
//! Internals of the `libsvm` FFI. //! //! Objects whose names start with `Libsvm` are for the most part //! things that we pass or get directly from `libsvm`, and are highly //! fragile. //! //! Their safe, memory-owning counterparts start with `Svm`. use std::ffi::CStr; use std::os::raw::c_char; use std::slice; use...
} } /// Fit a `libsvm` model. pub fn fit<'a, T>(X: &'a T, y: &Array, parameters: &SvmParameter) -> Result<SvmModel, &'static str> where T: IndexableMatrix, &'a T: RowIterable, { let problem = SvmProblem::new(X, y); let libsvm_problem = problem.build_problem(); let libsvm_param = parameters.bu...
{ Err(CStr::from_ptr(message).to_str().unwrap().to_owned()) }
conditional_block
ffi.rs
//! Internals of the `libsvm` FFI. //! //! Objects whose names start with `Libsvm` are for the most part //! things that we pass or get directly from `libsvm`, and are highly //! fragile. //! //! Their safe, memory-owning counterparts start with `Svm`. use std::ffi::CStr; use std::os::raw::c_char; use std::slice; use...
cache_size: f64, eps: f64, C: f64, nr_weight: i32, weight_label: *const i32, weight: *const f64, nu: f64, p: f64, shrinking: i32, probability: i32, } /// Safe representation of `LibsvmParameter`. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct SvmParameter { svm_t...
kernel_type: KernelType, degree: i32, gamma: f64, coef0: f64,
random_line_split
ffi.rs
//! Internals of the `libsvm` FFI. //! //! Objects whose names start with `Libsvm` are for the most part //! things that we pass or get directly from `libsvm`, and are highly //! fragile. //! //! Their safe, memory-owning counterparts start with `Svm`. use std::ffi::CStr; use std::os::raw::c_char; use std::slice; use...
<T: NonzeroIterable>(row: T) -> Vec<LibsvmNode> { let mut nodes = Vec::new(); for (index, value) in row.iter_nonzero() { nodes.push(LibsvmNode::new(index as i32, value as f64)); } // Sentinel value for end of row nodes.push(LibsvmNode::new(-1, 0.0)); nodes } impl SvmProblem { ///...
row_to_nodes
identifier_name
ffi.rs
//! Internals of the `libsvm` FFI. //! //! Objects whose names start with `Libsvm` are for the most part //! things that we pass or get directly from `libsvm`, and are highly //! fragile. //! //! Their safe, memory-owning counterparts start with `Svm`. use std::ffi::CStr; use std::os::raw::c_char; use std::slice; use...
/// Returns the unsafe object that can be passed into `libsvm`. fn build_problem(&self) -> LibsvmProblem { LibsvmProblem { l: self.nodes.len() as i32, y: self.y.as_ptr(), svm_node: self.node_ptrs.as_ptr(), } } } /// `libsvm` representation of training p...
{ let mut nodes = Vec::with_capacity(X.rows()); for row in X.iter_rows() { let row_nodes = row_to_nodes(row); nodes.push(row_nodes) } let node_ptrs = nodes.iter().map(|x| x.as_ptr()).collect::<Vec<_>>(); SvmProblem { nodes: nodes, ...
identifier_body
auxiliary_plots.py
"""This module contains auxiliary functions for plotting which are used in the main notebook.""" import numpy as np import pandas as pd import pandas.io.formats.style import seaborn as sns import statsmodels as sm import statsmodels.formula.api as smf import statsmodels.api as sm_api import matplotlib.pyplot as plt im...
### def quali_descriptive_plots(data, liste): sns.set_theme(style="whitegrid") fig, axes = plt.subplots(3, 2, figsize=(14, 16)) # Use the axes for plotting axes[0,0].set_title(liste[0]) sns.violinplot(x=liste[0], y="OFn_all", data=data, ax=axes[0,0], inner = "quartiles"); axes[...
sns.set_theme(style="whitegrid") f, axs = plt.subplots(2,1, figsize = (12,10)) plt.subplots_adjust(wspace=0.25) plt.subplot(211) ODA_like = data[data.flow_class == "ODA-like"].flow.value_counts() ax = sns.barplot(y=ODA_like.index, x=ODA_like.values) ax.set_xlabel("Number of projects") ...
identifier_body
auxiliary_plots.py
"""This module contains auxiliary functions for plotting which are used in the main notebook.""" import numpy as np import pandas as pd import pandas.io.formats.style import seaborn as sns import statsmodels as sm import statsmodels.formula.api as smf import statsmodels.api as sm_api import matplotlib.pyplot as plt im...
### def flow_class_plot(data): sns.set_theme(style="whitegrid") fig, ax = plt.subplots(1,2, figsize = (14,6)) plt.subplots_adjust(wspace=0.5) plotting = data.flow_class.value_counts(1) plt.subplot(121) ax = sns.barplot(x=plotting.index, y=plotting.values) ax.set_ylabel("share")...
fig.suptitle('Chinese Development Finance (probability)', fontsize=25) world_df.plot(column=pc, ax = ax, legend=True, cmap='jet', legend_kwds={"label":"\n Probability of receiving Chinese Development Finance (2000-2014)",###ADDDDJUST!!!!! ...
conditional_block
auxiliary_plots.py
"""This module contains auxiliary functions for plotting which are used in the main notebook.""" import numpy as np import pandas as pd import pandas.io.formats.style import seaborn as sns import statsmodels as sm import statsmodels.formula.api as smf import statsmodels.api as sm_api import matplotlib.pyplot as plt im...
ax3.set_ylabel("Average growth p.c.") ax3.set_title("Panel B: Average Growth along countries within groups") plt.legend(fontsize=15) plt.subplot(223) ax = sns.lineplot(x= "year", y= "lower_probOFn_ln", data = results_df, label = "below median OFn") ax = sns.lineplot(x= "year", y= "u...
ax3.set_xticklabels(["2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"]);
random_line_split
auxiliary_plots.py
"""This module contains auxiliary functions for plotting which are used in the main notebook.""" import numpy as np import pandas as pd import pandas.io.formats.style import seaborn as sns import statsmodels as sm import statsmodels.formula.api as smf import statsmodels.api as sm_api import matplotlib.pyplot as plt im...
(data, cc, pc): """ Function to plot a custom colored worldmap with help of a standart GeoPandas dataframe. I used the iso3 number of the countries in order to clearly identify the countries and assign the choosen value (financial amount or project count) to the specific country For plotting, we h...
worldplot_2
identifier_name
binge-watch.mock.ts
import { Movie } from "../models/movie"; import { TvSeries } from "../models/tvSeries"; export const Genres = [ "Action", "Animation", "Comedy", "Crime", "Drama", "Experimental", "Fantasy", "Historical", "Horror", "Romance", "Science Fiction", "Thriller", "Western", "Other"...
"https://m.media-amazon.com/images/M/MV5BODEwZjEzMjAtNjQxMy00Yjc4LWFlMDAtYjhjZTAxNDU3OTg3XkEyXkFqcGdeQXVyOTM2NTM4MjA@._V1_SY1000_SX750_AL_.jpg" }, { id: 5, name: "Peaky Blinders", genres: ["romantic"], releaseYear: "1988", noEpisodes: 6, noSeasons: 7, director: "Marcel Oph...
noSeasons: 18, director: "Marcel Ophüls", description: "In a wacky Rhode Island town, a dysfunctional family strive to cope with everyday life as they are thrown from one crazy scenario to another.", image:
random_line_split
lib.rs
use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE}; use eztrans_rs::{Container, EzTransLib}; use fxhash::FxHashMap; use serde_derive::{Deserialize, Serialize}; use std::ffi::CStr; use std::fs; use std::path::Path; use std::ptr::null_mut; pub struct EzDictItem { key: String, value: String, } impl Ez...
if !self.sort { return; } self.after_dict .sort_unstable_by(|l, r| l.key().cmp(r.key())); } pub fn sort(&mut self) { self.sort_after_dict(); self.sort_before_dict(); } } mod dict_items { use super::EzDictItem; use serde::de::{MapAccess...
; } self.before_dict .sort_unstable_by(|l, r| l.key().cmp(r.key())); } pub fn sort_after_dict(&mut self) {
identifier_body
lib.rs
use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE}; use eztrans_rs::{Container, EzTransLib}; use fxhash::FxHashMap; use serde_derive::{Deserialize, Serialize}; use std::ffi::CStr; use std::fs; use std::path::Path; use std::ptr::null_mut; pub struct EzDictItem { key: String, value: String, } impl Ez...
impl EzDict { pub fn sort_before_dict(&mut self) { if !self.sort { return; } self.before_dict .sort_unstable_by(|l, r| l.key().cmp(r.key())); } pub fn sort_after_dict(&mut self) { if !self.sort { return; } self.after_dict...
random_line_split
lib.rs
use encoding_rs::{EncoderResult, EUC_KR, SHIFT_JIS, UTF_16LE}; use eztrans_rs::{Container, EzTransLib}; use fxhash::FxHashMap; use serde_derive::{Deserialize, Serialize}; use std::ffi::CStr; use std::fs; use std::path::Path; use std::ptr::null_mut; pub struct EzDictItem { key: String, value: String, } impl Ez...
t dict = &mut self.dict; let lib = &self.lib; let buf = &mut self.encode_buffer; let str_buf = &mut self.string_buffer; self.cache.entry(text.into()).or_insert_with(move || { str_buf.push_str(text); let mut encoder = SHIFT_JIS.new_encoder(); let mut ...
r { le
identifier_name
bksv.go
package bksv // Package for posting a {ComplainerProfile,Complaint} to BKSV's web form // Bug 1: Edits to profile should call to maps to reparse the address; ignore what's in the form fields. import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/sk...
return vals } // }}} // {{{ PostComplaint // https://complaints-staging.bksv.com/sfo2?json=1&resp=json // {"result":"1", // "title":"Complaint Received", // "body":"Thank you. We have received your complaint."} func PostComplaint(client *http.Client, c complaintdb.Complaint) (*complaintdb.Submission, error) { ...
{ vals.Add("acid", c.AircraftOverhead.Callsign) vals.Add("aacode", c.AircraftOverhead.Id2) vals.Add("tailnumber", c.AircraftOverhead.Registration) //vals.Add("adflag", "??") // Operation type (A, D or O for Arr, Dept or Overflight) //vals.Add("beacon", "??") // Squawk SSR code (eg 2100) }
conditional_block
bksv.go
package bksv // Package for posting a {ComplainerProfile,Complaint} to BKSV's web form // Bug 1: Edits to profile should call to maps to reparse the address; ignore what's in the form fields. import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/sk...
(c complaintdb.Complaint, submitkey string) url.Values { first,last := c.Profile.SplitName() if c.Activity == "" { c.Activity = "Loud noise" } address1 := "" addr := c.Profile.GetStructuredAddress() if addr.Street == "" { address1 = c.Profile.Address // default to the raw string, if we don't have a structured o...
PopulateForm
identifier_name
bksv.go
package bksv // Package for posting a {ComplainerProfile,Complaint} to BKSV's web form // Bug 1: Edits to profile should call to maps to reparse the address; ignore what's in the form fields. import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/sk...
} indentedBytes,_ := json.MarshalIndent(jsonMap, "", " ") s.Log += "\n-- JsonMap:-\n"+string(indentedBytes)+"\n--\n" /* on success ... -- JsonMap:- { "body": "Thank you, your submission has been received. Would you like to save these details for next time?", "receipt_key": "adasdsdadsdasds786dsa87d6as87d6as",...
return debug,fmt.Errorf("Returned response did not say 'received your complaint'") } else { debug += "Success !\n"+string(body) } */
random_line_split
bksv.go
package bksv // Package for posting a {ComplainerProfile,Complaint} to BKSV's web form // Bug 1: Edits to profile should call to maps to reparse the address; ignore what's in the form fields. import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/sk...
// }}} // {{{ Notes /* These POST fields were sent by browser, for happy success nowebtrak:1 submitkey:4aef9c8831919524ec35ae8af8ff25ba defaulttime:0 webtraklinkback: title: name:Adam surname:Worrall address1:1 Some Drive address2: city:Scotts Valley state:CA homephone: workphone: cellphone: email:adam-foosite@wor...
{ // Initialize a new submission object, inheriting from previous s := complaintdb.Submission{ Attempts: c.Submission.Attempts + 1, Log: c.Submission.Log+fmt.Sprintf("\n--------=={ PostComplaint @ %s }==-\n", time.Now()), Key: c.Submission.Key, // We're now keyless, should prob strip this out T:...
identifier_body
write.go
package packer import ( "bufio" "bytes" "crypto/sha256" "fmt" "io" "io/fs" "io/ioutil" "log" "os" "path" "path/filepath" "sort" "strings" "time" "github.com/gokrazy/internal/config" "github.com/gokrazy/internal/deviceconfig" "github.com/gokrazy/internal/fat" "github.com/gokrazy/internal/humanize" "...
(f io.WriteSeeker, root *FileInfo) error { fmt.Printf("\n") fmt.Printf("Creating root file system\n") done := measure.Interactively("creating root file system") defer func() { done("") }() // TODO: make fw.Flush() report the size of the root fs fw, err := squashfs.NewWriter(f, time.Now()) if err != nil { ...
writeRoot
identifier_name
write.go
package packer import ( "bufio" "bytes" "crypto/sha256" "fmt" "io" "io/fs" "io/ioutil" "log" "os" "path" "path/filepath" "sort" "strings" "time" "github.com/gokrazy/internal/config" "github.com/gokrazy/internal/deviceconfig" "github.com/gokrazy/internal/fat" "github.com/gokrazy/internal/humanize" "...
} // if not found add complete subtree directly if f == nil { fi.Dirents = append(fi.Dirents, ent2) continue } // file overwrite is not supported -> return error if f.isFile() || ent2.isFile() { return fmt.Errorf("file already exist: %s", ent2.Filename) } if err := f.combine(ent2); err != ni...
if ent.Filename == ent2.Filename { f = ent break }
random_line_split
write.go
package packer import ( "bufio" "bytes" "crypto/sha256" "fmt" "io" "io/fs" "io/ioutil" "log" "os" "path" "path/filepath" "sort" "strings" "time" "github.com/gokrazy/internal/config" "github.com/gokrazy/internal/deviceconfig" "github.com/gokrazy/internal/fat" "github.com/gokrazy/internal/humanize" "...
func findBins(cfg *config.Struct, buildEnv *packer.BuildEnv, bindir string) (*FileInfo, error) { result := FileInfo{Filename: ""} // TODO: doing all three packer.MainPackages calls concurrently hides go // module proxy latency gokrazyMainPkgs, err := buildEnv.MainPackages(cfg.GokrazyPackagesOrDefault()) if err...
{ for _, ent := range fi.Dirents { // TODO: split path into components and compare piecemeal if ent.Filename == path { return ent } } log.Panicf("mustFindDirent(%q) did not find directory entry", path) return nil }
identifier_body
write.go
package packer import ( "bufio" "bytes" "crypto/sha256" "fmt" "io" "io/fs" "io/ioutil" "log" "os" "path" "path/filepath" "sort" "strings" "time" "github.com/gokrazy/internal/config" "github.com/gokrazy/internal/deviceconfig" "github.com/gokrazy/internal/fat" "github.com/gokrazy/internal/humanize" "...
result.Dirents = append(result.Dirents, &gokrazy) mainPkgs, err := buildEnv.MainPackages(cfg.Packages) if err != nil { return nil, err } user := FileInfo{Filename: "user"} for _, pkg := range mainPkgs { binPath := filepath.Join(bindir, pkg.Basename()) fileIsELFOrFatal(binPath) user.Dirents = append(user...
{ initMainPkgs, err := buildEnv.MainPackages([]string{cfg.InternalCompatibilityFlags.InitPkg}) if err != nil { return nil, err } for _, pkg := range initMainPkgs { if got, want := pkg.Basename(), "init"; got != want { log.Printf("Error: -init_pkg=%q produced unexpected binary name: got %q, want %q", c...
conditional_block
circular.menu.helpers.ts
/***************************************************************************************** * * Utility functions * *****************************************************************************************/ /** * Distance between two points p1 and p2 */ const getDistance...
(){ // Constants to regulate the positioning algorithm const angularSpace = Math.PI / 2; const angularAnchor = Math.PI; const menuExpansionSteps = 5; // Node items involved const navs = Array.from(document.querySelectorAll(".nav__item")); const menu = document.querySelector(".hamburger-men...
positionMenuItem
identifier_name
circular.menu.helpers.ts
/***************************************************************************************** * * Utility functions * *****************************************************************************************/ /** * Distance between two points p1 and p2 */ const getDistance...
{ // Constants to regulate the positioning algorithm const angularSpace = Math.PI / 2; const angularAnchor = Math.PI; const menuExpansionSteps = 5; // Node items involved const navs = Array.from(document.querySelectorAll(".nav__item")); const menu = document.querySelector(".hamburger-menu"...
identifier_body
circular.menu.helpers.ts
/***************************************************************************************** * * Utility functions * *****************************************************************************************/ /**
*/ const getDistance = (p1, p2 = {x:0,y:0}) => Math.sqrt((p2.x - p1.x)*(p2.x - p1.x) + (p2.y - p1.y)*(p2.y - p1.y)); /** * Comptute vector v such that OP1 + v = OP2 */ const getTranslator = (p1, p2 = {x:0,y:0}) => ({deltaX: p2.x - p1.x, deltaY: p2.y - p1.y}); /** * Comptute vector v such that OP1 + OP2 = v */ co...
* Distance between two points p1 and p2
random_line_split
DiffStreamOplogFilter.js
const http = require('http'); const stream = require('stream'); const { shuffle } = require('arsenal'); const DiffStreamOplogFilter = require('../../../CompareRaftMembers/DiffStreamOplogFilter'); const HTTP_TEST_PORT = 9090; class MockRaftOplogStream extends stream.Readable { constructor(entriesToEmit, refreshP...
} }, 10); } else { setTimeout(() => { this.push({ entry: null }); }, this.refreshPeriodMs); } } } describe('DiffStreamOplogFilter', () => { let httpServer; let reqCount = 0; beforeAll(done => { const handleGetBu...
if (this.entriesToEmit.length === 0) { this.push({ entry: null });
random_line_split
DiffStreamOplogFilter.js
const http = require('http'); const stream = require('stream'); const { shuffle } = require('arsenal'); const DiffStreamOplogFilter = require('../../../CompareRaftMembers/DiffStreamOplogFilter'); const HTTP_TEST_PORT = 9090; class MockRaftOplogStream extends stream.Readable {
(entriesToEmit, refreshPeriodMs) { super({ objectMode: true }); this.entriesToEmit = entriesToEmit; this.refreshPeriodMs = refreshPeriodMs; } _read() { if (this.entriesToEmit.length > 0) { // introduce a little delay between events to make sure // the fil...
constructor
identifier_name
DiffStreamOplogFilter.js
const http = require('http'); const stream = require('stream'); const { shuffle } = require('arsenal'); const DiffStreamOplogFilter = require('../../../CompareRaftMembers/DiffStreamOplogFilter'); const HTTP_TEST_PORT = 9090; class MockRaftOplogStream extends stream.Readable { constructor(entriesToEmit, refreshP...
} // check that no other entry than what was expected has been output expect(filteredDiffEntries.size).toEqual(0); done(); }) .on('error', err => { fail(`an error occurred during filtering: ${err}`); });...
{ for (let k = 1; k <= 5; ++k) { const bucketName = `bucket${b}-on-rs${rs}`; const key = `key${k}`; const outputDiffEntry = [{ key: `${bucketName}/${key}`, ...
conditional_block
lib.rs
//! Colorful and clean backtraces on panic. //! //! This library aims to make panics a little less painful by nicely colorizing //! them, skipping over frames of functions called after the panic was already //! initiated and printing relevant source snippets. Frames of functions in your //! application are colored in a...
self, i: usize, out: &mut impl WriteColor, s: &BacktracePrinter) -> IOResult { let is_dependency_code = self.is_dependency_code(); // Print frame index. write!(out, "{:>2}: ", i)?; if s.should_print_addresses() { if let Some((module_name, module_base)) = self.module_info() ...
int(&
identifier_name
lib.rs
//! Colorful and clean backtraces on panic. //! //! This library aims to make panics a little less painful by nicely colorizing //! them, skipping over frames of functions called after the panic was already //! initiated and printing relevant source snippets. Frames of functions in your //! application are colored in a...
"___rust_", "__pthread", "_main", "main", "__scrt_common_main_seh", "BaseThreadInitThunk", "_start", "__libc_start_main", "start_thread", ]; // Inspect name. if let Some(ref name) = self....
random_line_split
lib.rs
//! Colorful and clean backtraces on panic. //! //! This library aims to make panics a little less painful by nicely colorizing //! them, skipping over frames of functions called after the panic was already //! initiated and printing relevant source snippets. Frames of functions in your //! application are colored in a...
lse { &s.colors.crate_code })?; if has_hash_suffix { write!(out, "{}", &name[..name.len() - 19])?; if s.strip_function_hash { writeln!(out)?; } else { out.set_color(if is_dependency_code { &s.colors.depe...
&s.colors.dependency_code } e
conditional_block
lib.rs
//! Colorful and clean backtraces on panic. //! //! This library aims to make panics a little less painful by nicely colorizing //! them, skipping over frames of functions called after the panic was already //! initiated and printing relevant source snippets. Frames of functions in your //! application are colored in a...
/// Alter the color scheme. /// /// Defaults to `ColorScheme::classic()`. pub fn color_scheme(mut self, colors: ColorScheme) -> Self { self.colors = colors; self } /// Controls the "greeting" message of the panic. /// /// Defaults to `"The application panicked (crashed)"...
Self::default() }
identifier_body
u2eve.py
#! /usr/bin/env python # # Copyright (c) 2015 Jason Ish # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this li...
else: LOG.info("Loaded %s rule message map entries.", msgmap.size()) if classmap.size() == 0: LOG.warn("WARNING: No classifications loaded.") else: LOG.info("Loaded %s classifications.", classmap.size()) eve_filter = EveFilter(msgmap, classmap) outputs = [] if args.o...
LOG.warn("WARNING: No alert message map entries loaded.")
conditional_block
u2eve.py
#! /usr/bin/env python # # Copyright (c) 2015 Jason Ish # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this li...
(self, protocol): return proto_map.get(protocol, str(protocol)) class OutputWrapper(object): def __init__(self, filename, fileobj=None): self.filename = filename self.fileobj = fileobj if self.fileobj is None: self.reopen() self.isfile = True else: ...
getprotobynumber
identifier_name
u2eve.py
#! /usr/bin/env python # # Copyright (c) 2015 Jason Ish # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this li...
def load_from_snort_conf(snort_conf, classmap, msgmap): snort_etc = os.path.dirname(os.path.expanduser(snort_conf)) classification_config = os.path.join(snort_etc, "classification.config") if os.path.exists(classification_config): LOG.debug("Loading %s.", classification_config) classmap.l...
if self.isfile: if not os.path.exists(self.filename): self.reopen() self.fileobj.write(buf) self.fileobj.write("\n") self.fileobj.flush()
identifier_body
u2eve.py
# Copyright (c) 2015 Jason Ish # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
#! /usr/bin/env python #
random_line_split
executor.go
package executor import ( "encoding/json" "fmt" "strings" "sync" "sync/atomic" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/dock...
k.updateChan <- update statusUpdate := &mesos.TaskStatus{ TaskId: mutil.NewTaskID(taskId), State: mesos.TaskState_TASK_STARTING.Enum(), Message: proto.String(messages.CreateBindingSuccess), Data: data, } k.sendStatus(driver, statusUpdate) // Delay reporting 'task running' until container is up. g...
{ update.Pods = append(update.Pods, *p) }
conditional_block
executor.go
package executor import ( "encoding/json" "fmt" "strings" "sync" "sync/atomic" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/dock...
} // KillTask is called when the executor receives a request to kill a task. func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) { if k.isDone() { return } log.Infof("Kill task %v\n", taskId) if !k.isConnected() { //TODO(jdefelice) sent TASK_LOST here? log.Warningf("I...
} else { log.V(2).Infof("Task %v no longer registered, stop monitoring for lost pods", taskId) } return true
random_line_split
executor.go
package executor import ( "encoding/json" "fmt" "strings" "sync" "sync/atomic" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/dock...
(from, to stateType) bool { return atomic.CompareAndSwapInt32((*int32)(&k.state), int32(from), int32(to)) } // New creates a new kubernetes executor. func New(kl *kubelet.Kubelet, ch chan<- interface{}, ns string, cl *client.Client, w watch.Interface, dc dockertools.DockerInterface) *KubernetesExecutor { //TODO(jdef...
swapState
identifier_name
executor.go
package executor import ( "encoding/json" "fmt" "strings" "sync" "sync/atomic" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet" "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/dock...
func (k *KubernetesExecutor) swapState(from, to stateType) bool { return atomic.CompareAndSwapInt32((*int32)(&k.state), int32(from), int32(to)) } // New creates a new kubernetes executor. func New(kl *kubelet.Kubelet, ch chan<- interface{}, ns string, cl *client.Client, w watch.Interface, dc dockertools.DockerInter...
{ return connectedState == k.getState() }
identifier_body
IoManager.py
import ast import os from os import listdir from os.path import isfile, join import requests import shutil import pandas as pd from pathlib import Path import time import numpy as np class IoManager: """ Handles every input/output of the program Currently: * loads cube list and cards base data of start...
@staticmethod def get_arch_presence(): return pd.read_csv(IoManager.ARCH_PRESENCE_PATH, index_col=[0]) def save_arch_presence(self, arch_presence_entries): """ Adds the new entries to the db :param arch_presence_entries: [[1, 0, 0, 1, 1, 0], [1, 0, 1...]...] 1 for archetyp...
print("Initialising arch presence") df = pd.DataFrame(columns=self.archetypes.get_archetype_names(as_feature_names=True)) df.to_csv(IoManager.ARCH_PRESENCE_PATH) return df
identifier_body
IoManager.py
import ast import os from os import listdir from os.path import isfile, join import requests import shutil import pandas as pd from pathlib import Path import time import numpy as np class IoManager: """ Handles every input/output of the program Currently: * loads cube list and cards base data of start...
def clean_double_faced_from_cube_list(cube_list_file_name): # removes the second face name for each double faced card f = open("data/" + cube_list_file_name, "r") lines = f.readlines() f.close() def rm_second_face(line): if "//" in line: return li...
@staticmethod
random_line_split
IoManager.py
import ast import os from os import listdir from os.path import isfile, join import requests import shutil import pandas as pd from pathlib import Path import time import numpy as np class IoManager: """ Handles every input/output of the program Currently: * loads cube list and cards base data of start...
(): """ :return: list of card names, cube list """ f = open(IoManager.CUBE_LIST_FILE_PATH, "r") lines = f.readlines() f.close() # removing '\n' at then end of each name lines = [card_name[:-1] for card_name in lines] return lines @staticmetho...
get_cube_list
identifier_name
IoManager.py
import ast import os from os import listdir from os.path import isfile, join import requests import shutil import pandas as pd from pathlib import Path import time import numpy as np class IoManager: """ Handles every input/output of the program Currently: * loads cube list and cards base data of start...
return new_ratings @staticmethod def load_cards_df(): df = pd.read_csv("data/cube_list_base_data.csv") for list_feature in ["colors", "color_identity"]: df[list_feature] = df[list_feature].apply(lambda e: e if type(e) != float else "[]") df[list_feature] = df[list...
tingsInitializer.save_csv(new_ratings) exit()
conditional_block
clean_summaries.py
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ import json import os from unidecode import unidecode import re from tqdm import t...
summary = summary.replace(to_remove, "") pat_prefix = '((.*?){}) (.*$)'.format(name) if re.search(pat_prefix, summary, re.IGNORECASE): matched_str = re.match(pat_prefix, summary, re.IGNORECASE) print (matched_str.groups()) to_remove = matched_str.group(2...
if re.search(pat_suffix, summary, re.IGNORECASE): matched_str = re.match(pat_suffix, summary, re.IGNORECASE) to_remove = matched_str.group(2) # Everything after the Commentary keyword
random_line_split
clean_summaries.py
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ import json import os from unidecode import unidecode import re from tqdm import t...
(line): pat = '^((.*?)summary|analysis|summary and analysis|summary & analysis)[ ]{0,}[-:]?' if re.search(pat, line, re.IGNORECASE): to_replace = re.match(pat, line, re.IGNORECASE).group(0) line = line.replace(to_replace,"") return line.strip() def remove_chapter_p...
remove_summary_analysis_prefix
identifier_name
clean_summaries.py
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ import json import os from unidecode import unidecode import re from tqdm import t...
print ("book_count: ", book_count)
ary_path = os.path.join(item_dir, section) fp = open(summary_path,"r") try: summary_json = json.loads(fp.readlines()[0]) except: print (item_dir, "=Error reading json==", section) # continue new_json_dict = {}...
conditional_block
clean_summaries.py
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ import json import os from unidecode import unidecode import re from tqdm import t...
def remove_summary_analysis_prefix(line): pat = '^((.*?)summary|analysis|summary and analysis|summary & analysis)[ ]{0,}[-:]?' if re.search(pat, line, re.IGNORECASE): to_replace = re.match(pat, line, re.IGNORECASE).group(0) line = line.replace(to_replace,"") retu...
pat_suffix = '(.*)(Commentary (.*))' if re.search(pat_suffix, summary, re.IGNORECASE): matched_str = re.match(pat_suffix, summary, re.IGNORECASE) to_remove = matched_str.group(2) # Everything after the Commentary keyword summary = summary.replace(to_remove, "") pat_...
identifier_body
Util.js
/* * Copyright 2015-2023 G-Labs. All Rights Reserved. * * https://zuixjs.org * * 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...
(node) { for (; node; node = node.parentNode) { if (node instanceof ShadowRoot) { return node; } } return false; } } }; module.exports = Utils;
getShadowRoot
identifier_name
Util.js
/* * Copyright 2015-2023 G-Labs. All Rights Reserved. * * https://zuixjs.org * * 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...
, /** * @namespace dom * @memberof Utils */ dom: { /** * Gets CSS query for matching the given value in a list of specified attributes. * @param {string} name Comma separated list of attribute names. * @param {string} value The value to match. * @param {QuerySelectors} appendValue...
{ try { fn(); } catch (err) { ctx._error = err; if (errorCallback) errorCallback(err); if (err && ctx.options().error) { (ctx.options().error) .call(ctx, err, ctx); } else { console.error(err); } } }
identifier_body
Util.js
/* * Copyright 2015-2023 G-Labs. All Rights Reserved. * * https://zuixjs.org * * 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...
// TODO: should warn when clone is not possible } return temp; }, // TODO: deprecate `hasPassiveEvents` /** * Returns true if browser supports passive events. * @return {boolean} True if supported, otherwise false. * @memberOf Utils */ hasPassiveEvents() { let supportsPassive = fa...
random_line_split
lib.rs
//! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates. // Needed to use traits associated with std::io::BufReader. use std::io::BufRead; use std::io::Read; /// Type-erased errors. pub type BoxError = std::boxed...
(&'a mut self) -> MountsIteratorMut<'a> { self.into_iter() } } // Encapsulate individual nom parsers in a private submodule. The `pub(self)` keyword allows the inner method [parsers::parse_line()] to be called by code within this module, but not my users of our crate. pub(self) mod parsers { use super::Mount; ...
iter_mut
identifier_name
lib.rs
//! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates. // Needed to use traits associated with std::io::BufReader. use std::io::BufRead; use std::io::Read; /// Type-erased errors. pub type BoxError = std::boxed...
}
Mounts::new()
random_line_split
lib.rs
//! Example crate demonstrating how to use nom to parse `/proc/mounts`. Browse crates.io for sys-mount, proc-mounts, and libmount for more stable, usable crates. // Needed to use traits associated with std::io::BufReader. use std::io::BufRead; use std::io::Read; /// Type-erased errors. pub type BoxError = std::boxed...
{ Mounts::new() }
identifier_body
stringutils.go
package codegen import ( "errors" "fmt" "strings" "github.com/gertd/go-pluralize" ) var pluralizer = pluralize.NewClient() // edgecaseDataTypes return hardcoded types for specific properties which are problematic to parse var edgecaseDatatypes = map[string]string{ "locale": "string", "Per...
"mns:eventdelivery": "string", "mns:eventdescription": "string", "mns:eventsubscription": "string", "mns:embeddedserviceliveagent": "string", "mns: flow": "string", "https://developer.salesforce.com/docs/atlas.en-us.api_meta...
"mns:embeddedservicefieldservice": "string", "mns: customobject": "string",
random_line_split
stringutils.go
package codegen import ( "errors" "fmt" "strings" "github.com/gertd/go-pluralize" ) var pluralizer = pluralize.NewClient() // edgecaseDataTypes return hardcoded types for specific properties which are problematic to parse var edgecaseDatatypes = map[string]string{ "locale": "string", "Per...
(s string) string { return toCamelInitCase(s, true) } // ToLowerCamelCase converts a string to lowerCamelCase func toLowerCamelCase(s string) string { return toCamelInitCase(s, false) } func toFieldName(str string) string { return convertInitialisms(toCamelCase(str)) } // enforceLineLimit adds line breaks to a do...
toCamelCase
identifier_name
stringutils.go
package codegen import ( "errors" "fmt" "strings" "github.com/gertd/go-pluralize" ) var pluralizer = pluralize.NewClient() // edgecaseDataTypes return hardcoded types for specific properties which are problematic to parse var edgecaseDatatypes = map[string]string{ "locale": "string", "Per...
else if i == 0 { if vIsCap { v += 'a' v -= 'A' } } if vIsCap || vIsLow { n.WriteByte(v) capNext = false } else if vIsNum := v >= '0' && v <= '9'; vIsNum { n.WriteByte(v) capNext = true } else { capNext = v == '_' || v == ' ' || v == '-' || v == '.' } } return n.String() } // T...
{ if vIsLow { v += 'A' v -= 'a' } }
conditional_block
stringutils.go
package codegen import ( "errors" "fmt" "strings" "github.com/gertd/go-pluralize" ) var pluralizer = pluralize.NewClient() // edgecaseDataTypes return hardcoded types for specific properties which are problematic to parse var edgecaseDatatypes = map[string]string{ "locale": "string", "Per...
var keywords = map[string]string{ "break": "salesforce_break", "default": "salesforce_default", "func": "salesforce_func", "interface": "salesforce_interface", "select": "salesforce_select", "case": "salesforce_case", "defer": "salesforce_defer", "go": "salesforce...
{ for i := 0; i < len(commonInitialisms); i++ { s = strings.ReplaceAll(s, commonInitialisms[i][0], commonInitialisms[i][1]) } return s }
identifier_body
deepracer_racetrack_env.py
from __future__ import print_function import bisect import boto3 import json import logging import math import os import time import gym import numpy as np from gym import spaces from PIL import Image logger = logging.getLogger(__name__) # Type of worker SIMULATION_WORKER = "SIMULATION_WORKER" SAGEMAKER_TRAINING_WO...
(self, action): if node_type == SAGEMAKER_TRAINING_WORKER: return self.observation_space.sample(), 0, False, {} # Initialize next state, reward, done flag self.next_state = None self.reward = None self.done = False # Send this action to Gazebo and increment ...
step
identifier_name
deepracer_racetrack_env.py
from __future__ import print_function import bisect import boto3 import json import logging import math import os import time import gym import numpy as np from gym import spaces from PIL import Image logger = logging.getLogger(__name__) # Type of worker SIMULATION_WORKER = "SIMULATION_WORKER" SAGEMAKER_TRAINING_WO...
return self.is_simulation_done def is_number(self, value_to_check): try: float(value_to_check) return True except ValueError: return False def cancel_simulation_job(self): self.send_action(0, 0) session = boto3.session.Session() ...
self.is_simulation_done = True
conditional_block
deepracer_racetrack_env.py
from __future__ import print_function import bisect import boto3 import json import logging import math import os import time import gym import numpy as np from gym import spaces from PIL import Image logger = logging.getLogger(__name__) # Type of worker SIMULATION_WORKER = "SIMULATION_WORKER" SAGEMAKER_TRAINING_WO...
def racecar_reset(self): rospy.wait_for_service('/gazebo/set_model_state') # Compute the starting position and heading next_point_index = bisect.bisect(self.center_dists, self.start_dist) start_point = self.center_line.interpolate(self.start_dist, normalized=True) start_ya...
if node_type == SAGEMAKER_TRAINING_WORKER: return self.observation_space.sample() # Simulation is done - so RoboMaker will start to shut down the app. # Till RoboMaker shuts down the app, do nothing more else metrics may show unexpected data. if (node_type == SIMULATION_WORKER) and ...
identifier_body
deepracer_racetrack_env.py
from __future__ import print_function import bisect import boto3 import json import logging import math import os import time import gym import numpy as np from gym import spaces from PIL import Image logger = logging.getLogger(__name__) # Type of worker SIMULATION_WORKER = "SIMULATION_WORKER" SAGEMAKER_TRAINING_WO...
Namespace=self.metric_namespace ) else: print("{}: {}".format(self.metric_name, reward)) class DeepRacerRacetrackCustomActionSpaceEnv(DeepRacerRacetrackEnv): def __init__(self): DeepRacerRacetrackEnv.__init__(self) try: # Try loading the c...
],
random_line_split
rabbitmq_server_relations.py
#!/usr/bin/python # # Copyright 2016 Canonical Ltd # # 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 agr...
if is_leader(): log('Leader peer_storing cookie', level=INFO) cookie = open(rabbit.COOKIE_PATH, 'r').read().strip() peer_store('cookie', cookie) peer_store('leader_node_ip', unit_private_ip()) peer_store('leader_node_hostname', rabbit.get_unit_hostname()) @hooks.hook('clu...
log('erlang cookie missing from %s' % rabbit.COOKIE_PATH, level=ERROR) return
conditional_block
rabbitmq_server_relations.py
#!/usr/bin/python # # Copyright 2016 Canonical Ltd # # 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 agr...
def update_clients(): """Update amqp client relation hooks IFF leader node is ready. Client nodes are considered ready once the leader has already run amqp_changed. """ if rabbit.leader_node_is_ready() or rabbit.client_node_is_ready(): for rid in relation_ids('amqp'): for uni...
password = rabbit.get_rabbit_password(username) # update vhost rabbit.create_vhost(vhost) rabbit.create_user(username, password, admin) rabbit.grant_permissions(username, vhost) # NOTE(freyes): after rabbitmq-server 3.0 the method to define HA in the # queues is different # http://www.rabb...
identifier_body
rabbitmq_server_relations.py
#!/usr/bin/python # # Copyright 2016 Canonical Ltd # # 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 agr...
(): if os.path.isdir(NAGIOS_PLUGINS): rsync(os.path.join(os.getenv('CHARM_DIR'), 'scripts', 'check_rabbitmq.py'), os.path.join(NAGIOS_PLUGINS, 'check_rabbitmq.py')) rsync(os.path.join(os.getenv('CHARM_DIR'), 'scripts', 'check_rabbit...
update_nrpe_checks
identifier_name
rabbitmq_server_relations.py
#!/usr/bin/python # # Copyright 2016 Canonical Ltd # # 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 agr...
log('Unknown hook {} - skipping.'.format(e)) # Gated client updates update_clients() rabbit.assess_status(rabbit.ConfigRenderer(rabbit.CONFIG_FILES))
hooks.execute(sys.argv) except UnregisteredHookError as e:
random_line_split
preference_aggregation_featureless_online.py
import logging from copy import deepcopy import gin import numpy as np from backend.rating_fields import MAX_VALUE from matplotlib import pyplot as plt from scipy.optimize import golden from .preference_aggregation_featureless_np import loss_fcn_np @gin.configurable class FeaturelessOnlineUpdater(objec...
hst = [initial] + hst plt.axhline(initial) if np.min(hst) > 0: plt.yscale('log') plt.plot(hst) plt.show() def lstdct2dctlst(lst): """List of dictionaries -> dictionary of lists.""" keys = lst[0].keys() res = {ke...
initial = initial_value[ind]['metrics'][key]
random_line_split
preference_aggregation_featureless_online.py
import logging from copy import deepcopy import gin import numpy as np from backend.rating_fields import MAX_VALUE from matplotlib import pyplot as plt from scipy.optimize import golden from .preference_aggregation_featureless_np import loss_fcn_np @gin.configurable class FeaturelessOnlineUpdater(objec...
# setting data online.set_minibatch(mb_np_copy) online.set_model_tensor(model_tensor_copy) online.set_subtract() online.silent = True # CONFIGURATION FOR INDICES indices_lst = [] for i in range(model_tensor_orig.shape[0]): indices_lst.append((i, obj1, 0)) ...
online.golden_params[key] = value
conditional_block
preference_aggregation_featureless_online.py
import logging from copy import deepcopy import gin import numpy as np from backend.rating_fields import MAX_VALUE from matplotlib import pyplot as plt from scipy.optimize import golden from .preference_aggregation_featureless_np import loss_fcn_np @gin.configurable class
(object): """Update weights online.""" def __init__(self, hypers=None, golden_params=None): if golden_params is None: golden_params = {} self.golden_params = golden_params self.hypers = hypers self.model_tensor = None self.minibatch = None s...
FeaturelessOnlineUpdater
identifier_name
preference_aggregation_featureless_online.py
import logging from copy import deepcopy import gin import numpy as np from backend.rating_fields import MAX_VALUE from matplotlib import pyplot as plt from scipy.optimize import golden from .preference_aggregation_featureless_np import loss_fcn_np @gin.configurable class FeaturelessOnlineUpdater(objec...
def lstdct2dctlst(lst): """List of dictionaries -> dictionary of lists.""" keys = lst[0].keys() res = {key: [x[key] for x in lst] for key in keys} return res def compute_online_update(rating_value, mb_np_orig, model_tensor_orig, idx_se...
for ind in set(indices_lst): res = get_history(result, ind) res_dct = lstdct2dctlst(res) plt.figure(figsize=(13, 3)) for i, key in enumerate(sorted(res_dct.keys()), 1): hst = res_dct[key] plt.subplot(1, len(res_dct), i) plt.title(key + ' ' +...
identifier_body
smd.rs
use std::fs::File; use std::io::{BufReader}; use std::path::PathBuf; use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation}; use soto::task::{task_log}; use soto::Error; use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode}; use sotolib_fbx::animation::{Animation}; use soto...
} fn calculate_parent_after_rot_translation(fbx: &SimpleFbx, obj: &Object) -> Vector3<f32> { // First actually get the parent's model data let parent_obj = if let Some(v) = fbx.parent_of(obj.id) { if v == 0 { // At root, no extra translation return Vector3::new(0.0, 0.0, 0.0) ...
(translation, rotation)
random_line_split
smd.rs
use std::fs::File; use std::io::{BufReader}; use std::path::PathBuf; use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation}; use soto::task::{task_log}; use soto::Error; use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode}; use sotolib_fbx::animation::{Animation}; use soto...
(rot_degs: [f32; 3]) -> Matrix4<f32> { Matrix4::from_angle_z(Deg(rot_degs[2])) * Matrix4::from_angle_y(Deg(rot_degs[1])) * Matrix4::from_angle_x(Deg(rot_degs[0])) }
euler_rotation_to_matrix
identifier_name
smd.rs
use std::fs::File; use std::io::{BufReader}; use std::path::PathBuf; use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation}; use soto::task::{task_log}; use soto::Error; use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode}; use sotolib_fbx::animation::{Animation}; use soto...
fn calculate_parent_after_rot_translation(fbx: &SimpleFbx, obj: &Object) -> Vector3<f32> { // First actually get the parent's model data let parent_obj = if let Some(v) = fbx.parent_of(obj.id) { if v == 0 { // At root, no extra translation return Vector3::new(0.0, 0.0, 0.0) ...
{ let properties = ModelProperties::from_generic(&obj.properties); // Get the bone's translation let parent_after_rot_translation = calculate_parent_after_rot_translation(fbx, obj); let prop_translation: Vector3<_> = properties.translation.into(); let prop_rot_offset: Vector3<_> = properties.rotati...
identifier_body
smd.rs
use std::fs::File; use std::io::{BufReader}; use std::path::PathBuf; use cgmath::{Matrix4, Deg, Vector4, SquareMatrix, Vector3, Euler, Quaternion, Rotation}; use soto::task::{task_log}; use soto::Error; use sotolib_fbx::{RawFbx, id_name, friendly_name, ObjectTreeNode}; use sotolib_fbx::animation::{Animation}; use soto...
else { Euler::from(post_rotation.invert() * rotation.invert() * pre_rotation) }; let rotation = Vector3::new( total_rotation.x.0, total_rotation.y.0, total_rotation.z.0, ); (translation, rotation) } fn calculate_parent_after_rot_translation(fbx: &SimpleFbx, obj: &Objec...
{ Euler::from(post_rotation.invert() * rotation * pre_rotation) }
conditional_block
tf_linear_reg.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 23 11:54:38 2018 @author: s.agrawalairan """ import tensorflow as tf import numpy as np import os import pickle as pk import csv import pandas as pd import logging import pprint import pdb flags = tf.app.flags FLAGS = flags.FLAGS logging.basicConfi...
(filenames, batch_size): # Define a `tf.contrib.data.Dataset` for iterating over one epoch of the data. dataset = (tf.data.TFRecordDataset(filenames). shuffle(buffer_size=MIN_AFTER_DEQUEUE). batch(batch_size)) return dataset.make_initializable_iterator() def get_features...
input_pipeline
identifier_name
tf_linear_reg.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 23 11:54:38 2018 @author: s.agrawalairan """ import tensorflow as tf import numpy as np import os import pickle as pk import csv import pandas as pd import logging import pprint import pdb flags = tf.app.flags FLAGS = flags.FLAGS logging.basicConfi...
tfr_vald_filenames = [loaddir+"SynDataset2.tfrecords",loaddir+"SynDataset4.tfrecords"] tf.reset_default_graph() # Get a batch of y and X in tr_features train_iterator, train_features = get_features(tfr_tr_filenames, BATCH_SIZE) batch_labels = train_features["label"] batch_ids = train_features[...
# Get all FileNames tfr_tr_filenames = [loaddir+"SynDataset1.tfrecords",loaddir+"SynDataset3.tfrecords"]
random_line_split
tf_linear_reg.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 23 11:54:38 2018 @author: s.agrawalairan """ import tensorflow as tf import numpy as np import os import pickle as pk import csv import pandas as pd import logging import pprint import pdb flags = tf.app.flags FLAGS = flags.FLAGS logging.basicConfi...
def get_features(tfrecords_file,batch_size): iterator = input_pipeline(tfrecords_file, batch_size) features_obj = iterator.get_next() features = tf.parse_example( features_obj, # Defaults are not specified since both keys are required. features={ ...
dataset = (tf.data.TFRecordDataset(filenames). shuffle(buffer_size=MIN_AFTER_DEQUEUE). batch(batch_size)) return dataset.make_initializable_iterator()
identifier_body
tf_linear_reg.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 23 11:54:38 2018 @author: s.agrawalairan """ import tensorflow as tf import numpy as np import os import pickle as pk import csv import pandas as pd import logging import pprint import pdb flags = tf.app.flags FLAGS = flags.FLAGS logging.basicConfi...
def linear_reg_inference(sparse_ids,sparse_values,hidden_nodes,num_layers): # train_sz = np.shape(Xtrain)[0] W_ls = [] Bias_ls = [] # Reset the graph # tf.reset_default_graph() with tf.variable_scope("linear_reg"): W_ls.append(tf.get_variable( "weights_0", ...
print("Unknow optimizer, exit now") exit(1)
conditional_block
lexer.go
package lexer import ( "bytes" "fmt" "github.com/fadion/aria/reader" "github.com/fadion/aria/reporter" "github.com/fadion/aria/token" ) // Lexer represents the lexer. type Lexer struct { reader *reader.Reader char rune row int col int token token.Token rewinded bool symbol *Symbol } ...
// Check characters ahead but don't move the cursor. func (l *Lexer) peek() rune { rn, err := l.reader.Peek() if err != nil { l.reportError(fmt.Sprintf("Invalid '%s' character in source file", string(rn))) } return rn } // Move the cursor to the previous character. func (l *Lexer) rewind() { if err := l.read...
{ rn, err := l.reader.Advance() if err != nil { l.reportError(fmt.Sprintf("Invalid '%s' character in source file", string(rn))) } // Don't move the location if it was a // rewind, or it will report an incorrect // line and column. if !l.rewinded { l.moveLocation() } l.rewinded = false l.char = rn }
identifier_body
lexer.go
package lexer import ( "bytes" "fmt" "github.com/fadion/aria/reader" "github.com/fadion/aria/reporter" "github.com/fadion/aria/token" ) // Lexer represents the lexer. type Lexer struct { reader *reader.Reader char rune row int col int token token.Token rewinded bool symbol *Symbol } ...
() { switch l.char { case '\n': l.row += 1 l.col = 2 default: l.col += 1 } } // Pass a token to the active token cursor. func (l *Lexer) assignToken(toktype token.TokenType, value string) { l.token = token.Token{ Type: toktype, Lexeme: value, Location: token.Location{Row: l.row, Col: l.col}, } ...
moveLocation
identifier_name
lexer.go
package lexer import ( "bytes" "fmt" "github.com/fadion/aria/reader" "github.com/fadion/aria/reporter" "github.com/fadion/aria/token" ) // Lexer represents the lexer. type Lexer struct { reader *reader.Reader char rune row int col int token token.Token rewinded bool symbol *Symbol } ...
} default: out.WriteRune(l.char) } l.advance() } l.assignToken(token.COMMENT, out.String()) } // Read multiline comment. func (l *Lexer) consumeMultilineComment() { var out bytes.Buffer loop: for { l.advance() switch l.char { case '*': switch l.peek() { case '/': // Multiline comments en...
break loop default: l.reportError("Unexpected comment line ending") break loop
random_line_split
lexer.go
package lexer import ( "bytes" "fmt" "github.com/fadion/aria/reader" "github.com/fadion/aria/reporter" "github.com/fadion/aria/token" ) // Lexer represents the lexer. type Lexer struct { reader *reader.Reader char rune row int col int token token.Token rewinded bool symbol *Symbol } ...
l.rewinded = false l.char = rn } // Check characters ahead but don't move the cursor. func (l *Lexer) peek() rune { rn, err := l.reader.Peek() if err != nil { l.reportError(fmt.Sprintf("Invalid '%s' character in source file", string(rn))) } return rn } // Move the cursor to the previous character. func (l *...
{ l.moveLocation() }
conditional_block
watcher.go
package consul import ( "crypto/x509" "sync" "time" slog "github.com/go-eden/slf4go" "github.com/hashicorp/consul/api" ) const ( errorWaitTime = 5 * time.Second ) var log = slog.NewLogger("consul-watcher") type ConsulConfig struct { // Address is the address of the Consul server Address string // Scheme...
func (w *Watcher) watchService(service string, first bool, kind string) { log.Infof("watching downstream: %s", service) dFirst := true var lastIndex uint64 var nSpace string for { if kind != "terminating-gateway" { if &w.services[service].gatewayService.Service.Namespace != nil { nSpace = w.services[ser...
{ var lastIndex uint64 first := true for { gwServices, meta, err := w.consul.Catalog().GatewayServices(w.name, &api.QueryOptions{ WaitTime: 10 * time.Minute, WaitIndex: lastIndex, }) if err != nil { log.Errorf("error fetching linked services for gateway %s: %s", w.name, err) time.Sleep(errorWaitTi...
identifier_body
watcher.go
package consul import ( "crypto/x509" "sync" "time" slog "github.com/go-eden/slf4go" "github.com/hashicorp/consul/api" ) const ( errorWaitTime = 5 * time.Second ) var log = slog.NewLogger("consul-watcher") type ConsulConfig struct { // Address is the address of the Consul server Address string // Scheme...
log.Infof("initializing Consul watcher for gateway: %+v", gatewayName) w.name = gatewayName w.namespace = namespace w.settings = *api.DefaultConfig() w.settings.Address = c.Address w.settings.Scheme = c.Scheme w.settings.Token = c.Token w.settings.Namespace = c.Namespace w.consul, err = api.NewClient(&w.setti...
var err error
random_line_split
watcher.go
package consul import ( "crypto/x509" "sync" "time" slog "github.com/go-eden/slf4go" "github.com/hashicorp/consul/api" ) const ( errorWaitTime = 5 * time.Second ) var log = slog.NewLogger("consul-watcher") type ConsulConfig struct { // Address is the address of the Consul server Address string // Scheme...
for name := range w.services { if !keep[name] { w.removeService(name) } } } func (w *Watcher) startService(down *api.GatewayService, first bool) { d := &service{ name: down.Service.Name, gatewayService: down, } w.lock.Lock() w.services[down.Service.Name] = d w.lock.Unlock() d.ready.Ad...
{ for _, down := range *gwServices { keep[down.Service.Name] = true w.lock.Lock() _, ok := w.services[down.Service.Name] w.lock.Unlock() if !ok { if first { w.ready.Add(3) } w.startService(down, first) } } }
conditional_block
watcher.go
package consul import ( "crypto/x509" "sync" "time" slog "github.com/go-eden/slf4go" "github.com/hashicorp/consul/api" ) const ( errorWaitTime = 5 * time.Second ) var log = slog.NewLogger("consul-watcher") type ConsulConfig struct { // Address is the address of the Consul server Address string // Scheme...
() { w.C <- w.genCfg() } func (w *Watcher) watchLeaf(service string, first bool) { log.Debugf("watching leaf cert for %s", service) dFirst := true var lastIndex uint64 for { if w.services[service] == nil { return } else if w.services[service].done { return } cert, meta, err := w.consul.Agent().Conne...
Reload
identifier_name
practice.js
// -- PRELOAD -- // Note: Waiting for init() call var preload = new createjs.LoadQueue(); preload.on("progress", handleOverallProgress, this); preload.on("complete", handleComplete, this); var manifest = [ {src: 'img/practice_bg.png', id: 'bg'}, {src: 'img/life.png', id: 'life'}, {src: 'img/no_life.png', i...
function initializeAnswerPositions() { for (a = 0; a < 5; a++) { // x and y of the CENTER of the container. (not top left) answers[a].x = (properties.ANS_SIZE / 2) + (a)*(properties.ANS_SIZE); console.log("Ans x: " + answers[a].x + " y: " + answers[a].y); } } // AUDIO function bgm(e...
{ for (q=0; q<3; q++) { switch (q) { case 0: questions[q].y = layout.MID3; // Lowest questions[q].scaleY = 1.66; questions[q].txt.scaleY = 1.00; questions[q].txt.scaleX = 1.66; break; case 1: ...
identifier_body
practice.js
// -- PRELOAD -- // Note: Waiting for init() call var preload = new createjs.LoadQueue(); preload.on("progress", handleOverallProgress, this); preload.on("complete", handleComplete, this); var manifest = [ {src: 'img/practice_bg.png', id: 'bg'}, {src: 'img/life.png', id: 'life'}, {src: 'img/no_life.png', i...
while (answer%numA != 0) var numB = answer / numA; var numSet = [numA, numB]; return numSet; } function generateDivision(answer) { var numA = getRandomInt(1, 10); var numB = answer * numA; var numSet = [numB, numA]; return numSet; } // Move all objects up one position (overwritting th...
{ var numA = getRandomInt(1,10); }
conditional_block
practice.js
// -- PRELOAD -- // Note: Waiting for init() call var preload = new createjs.LoadQueue(); preload.on("progress", handleOverallProgress, this); preload.on("complete", handleComplete, this); var manifest = [ {src: 'img/practice_bg.png', id: 'bg'}, {src: 'img/life.png', id: 'life'}, {src: 'img/no_life.png', i...
(answer) { return (answer == questions[0].answer); } function answerCorrect() { // GAME-LOGIC correct++; correctIndicator.txt.text = correct; updateDifficulty(); // Play sound correctSfx(); // GAME-FUNCTIONS advanceAnswers(generateNextAnswer()); // Create the next answer, anima...
checkAnswer
identifier_name
practice.js
// -- PRELOAD -- // Note: Waiting for init() call var preload = new createjs.LoadQueue(); preload.on("progress", handleOverallProgress, this); preload.on("complete", handleComplete, this); var manifest = [ {src: 'img/practice_bg.png', id: 'bg'}, {src: 'img/life.png', id: 'life'}, {src: 'img/no_life.png', i...
function prepareNextQuestion() { // Obtain information about the current board var availableArray = []; // Note: foreach loop not working very well for (a=0; a<answers.length; a++) { if (answers[a].available == true) { availableArray.push(answers[a]); } } // Select o...
// Gathers are all the necessary info before generating the next answer
random_line_split
in_memory.rs
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT //! Implementation of an in-memory repository. use std::{ borrow::Cow, collections::{hash_map::DefaultHasher, BTreeMap, VecDeque}, hash::Hasher, mem::size_of, sync::{atomic::Ordering, Arc}, ...
self.free_ids.as_mut()?.pop().ok() } pub(crate) fn insert_value_at( &mut self, hash_id: HashId, value: Arc<[u8]>, ) -> Result<(), HashIdError> { self.values_bytes = self.values_bytes.saturating_add(value.len()); if let Some(old) = self.values.insert_at(hash_i...
fn get_free_id(&mut self) -> Option<HashId> {
random_line_split
in_memory.rs
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT //! Implementation of an in-memory repository. use std::{ borrow::Cow, collections::{hash_map::DefaultHasher, BTreeMap, VecDeque}, hash::Hasher, mem::size_of, sync::{atomic::Ordering, Arc}, ...
pub fn put_context_hash_impl(&mut self, commit_hash_id: HashId) -> Result<(), DBError> { let commit_hash = self .hashes .get_hash(commit_hash_id)? .ok_or(DBError::MissingObject { hash_id: commit_hash_id, })?; let mut hasher = Default...
{ let mut hasher = DefaultHasher::new(); hasher.write(context_hash.as_ref()); let hashed = hasher.finish(); self.context_hashes.get(&hashed).cloned() }
identifier_body
in_memory.rs
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT //! Implementation of an in-memory repository. use std::{ borrow::Cow, collections::{hash_map::DefaultHasher, BTreeMap, VecDeque}, hash::Hasher, mem::size_of, sync::{atomic::Ordering, Arc}, ...
(&self) -> RepositoryMemoryUsage { let values_bytes = self.values_bytes; let values_capacity = self.values.capacity(); let hashes_capacity = self.hashes.capacity(); let total_bytes = values_bytes .saturating_add(values_capacity * size_of::<Option<Arc<[u8]>>>()) .s...
get_memory_usage
identifier_name
ghttp_server_router.go
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 路由控制. package ghttp import ( "errors" "strin...
on 匹配 /user 的规则 if k == len(array) - 1 { if _, ok := p.(map[string]interface{})["*fuzz"]; ok { p = p.(map[string]interface{})["*fuzz"] } if _, ok := p.(map[string]interface{})["*list"]; ok { lists = append(lists, p.(map[...
如:/user/*acti
identifier_name
ghttp_server_router.go
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 路由控制. package ghttp import ( "errors" "strin...
}) if strings.EqualFold(s, v) { regrule += "/" + v } else { regrule += "/" + s } } } regrule += `$` return } // 生成回调方法查询的Key func (s *Server) handlerKey(method, path, domain string) string { ...
default: s, _ := gregex.ReplaceStringFunc(`{[\w\.\-]+}`, v, func(s string) string { names = append(names, s[1 : len(s) - 1]) return `([\w\.\-]+)`
random_line_split
ghttp_server_router.go
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 路由控制. package ghttp import ( "errors" "strin...
pushed = true break } } if pushed { if len(address) > 0 { pushedItemSet.Add(address) } } else { l.PushBack(registerItem) } } } //gutil.Dump(s.han...
if s.compareRouterPriority(router, item.router) { l.InsertBefore(registerItem, e)
conditional_block
ghttp_server_router.go
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 路由控制. package ghttp import ( "errors" "strin...
1 { if _, ok := p.(map[string]interface{})["*fuzz"]; ok { p = p.(map[string]interface{})["*fuzz"] } if _, ok := p.(map[string]interface{})["*list"]; ok { lists = append(lists, p.(map[string]interface{})["*list"].(*list.List)) ...
identifier_body
licensePlateDetectorOptimized.py
print("\n\nLOADING PROGRAM\n\n") import cv2 as cv print("Loaded CV") import numpy as np print("Loaded NP") import tensorflow as tf print("Loaded TF") import imutils print("Loaded IMUTILS") import os print("Loaded OS") ''' SOME NOTES ABOUT THE PROGRAM: 1) Make sure to change the paths at the top of the file to refle...
######################################################################################## #################################### CONTOUR SORTING ################################### ######################################################################################## def sort_contours_left(self, co...
print("VIDEO PAUSED @ FRAME {}".format(cap.get(cv.CAP_PROP_POS_FRAMES))) while True: key = cv.waitKey(25) & 0xFF if key == ord('p'): #unpause break elif key == ord('q'): #quit the program bu...
conditional_block