file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
common.py
self.items = items if items else [] self.mapping = mapping self.keys = [] for key in mapping.keys(): self.keys.append(key) def add(self, items): """Add items to output.""" if isinstance(items, list): self.items.extend(items) else: ...
def __get_items(self, sort_keys_function=None): """Return a sorted copy of self.items if sort_keys_function is given, a reference to self.items otherwise.""" if sort_keys_function: return sorted(list(self.items), key=sort_keys_function) return self.items class Boto3ClientFact...
"""Return number of items in Output.""" return len(self.items)
identifier_body
common.py
self.items = items if items else [] self.mapping = mapping self.keys = [] for key in mapping.keys(): self.keys.append(key) def add(self, items): """Add items to output.""" if isinstance(items, list): self.items.extend(items) else: ...
("job_definition", "BatchJobDefinitionArn", "output"), ("head_node_ip", "HeadNodePrivateIP", "output"), ] for config_param, cfn_param, cfn_prop_type in config_to_cfn_map: try: log.debug("%s = %s", config_param, getattr(self, config_param)) ...
random_line_split
common.py
self.items = items if items else [] self.mapping = mapping self.keys = [] for key in mapping.keys(): self.keys.append(key) def add(self, items): """Add items to output.""" if isinstance(items, list): self.items.extend(items) else: ...
(self, keys=None, sort_keys_function=None): """ Print the items table. :param keys: show a specific list of keys (optional) :param sort_keys_function: function to sort table rows (optional) """ rows = [] output_keys = keys or self.keys for item in self._...
show_table
identifier_name
common.py
self.items = items if items else [] self.mapping = mapping self.keys = [] for key in mapping.keys(): self.keys.append(key) def add(self, items): """Add items to output.""" if isinstance(items, list): self.items.extend(items) else: ...
class AWSBatchCliConfig: """AWS ParallelCluster AWS Batch CLI configuration object.""" def __init__(self, log, cluster): """ Initialize the object. Search for the [cluster cluster-name] section in the /etc/awsbatch-cli.cfg configuration file, if there or ask to the pcluster ...
if not self.COMPARISON_OPERATORS[req.operator]( packaging.version.parse(get_installed_version(req.package)), packaging.version.parse(req.version), ): fail(f"The cluster requires {req.package}{req.operator}{req.version}")
conditional_block
client.go
type ConnCallback func(c *Client) // ResponseValidator validates a response type ResponseValidator func(c *Client, resp *http.Response) error // Client handles an incoming server stream type Client struct { Retry time.Time ReconnectStrategy backoff.BackOff disconnectcb ConnCallback connectedcb ...
var err error if c.ReconnectStrategy != nil { err = backoff.RetryNotify(operation, c.ReconnectStrategy, c.ReconnectNotify) } else { err = backoff.RetryNotify(operation, backoff.NewExponentialBackOff(), c.ReconnectNotify) } return err } // SubscribeChan sends all events to the provided channel func (c *Client)...
} // Apply user specified reconnection strategy or default to standard NewExponentialBackOff() reconnection method
random_line_split
client.go
ConnCallback func(c *Client) // ResponseValidator validates a response type ResponseValidator func(c *Client, resp *http.Response) error // Client handles an incoming server stream type Client struct { Retry time.Time ReconnectStrategy backoff.BackOff disconnectcb ConnCallback connectedcb ...
// SubscribeChanRawWithContext sends all events to the provided channel with context func (c *Client) SubscribeChanRawWithContext(ctx context.Context, ch chan *Event) error { return c.SubscribeChanWithContext(ctx, "", ch) } // Unsubscribe unsubscribes a channel func (c *Client) Unsubscribe(ch chan *Event) { c.mu.L...
{ return c.SubscribeChan("", ch) }
identifier_body
client.go
type ConnCallback func(c *Client) // ResponseValidator validates a response type ResponseValidator func(c *Client, resp *http.Response) error // Client handles an incoming server stream type Client struct { Retry time.Time ReconnectStrategy backoff.BackOff disconnectcb ConnCallback connectedcb ...
else if resp.StatusCode != 200 { resp.Body.Close() return fmt.Errorf("could not connect to stream: %s", http.StatusText(resp.StatusCode)) } defer resp.Body.Close() reader := NewEventStreamReader(resp.Body, c.maxBufferSize) eventChan, errorChan := c.startReadLoop(reader) for { select { case err ...
{ err = validator(c, resp) if err != nil { return err } }
conditional_block
client.go
type ConnCallback func(c *Client) // ResponseValidator validates a response type ResponseValidator func(c *Client, resp *http.Response) error // Client handles an incoming server stream type Client struct { Retry time.Time ReconnectStrategy backoff.BackOff disconnectcb ConnCallback connectedcb ...
(stream string, ch chan *Event) error { return c.SubscribeChanWithContext(context.Background(), stream, ch) } // SubscribeChanWithContext sends all events to the provided channel with context func (c *Client) SubscribeChanWithContext(ctx context.Context, stream string, ch chan *Event) error { var connected bool err...
SubscribeChan
identifier_name
sin-gen.go
'0' || c > '9' { panic(fmt.Errorf("Character #%d from SIN_Str '%c' is invalid\n", i, c)) } result = append(result, int(c-'0')) } return result } /* Validation Procedure http://www.ryerson.ca/JavaScript/lectures/forms/textValidation/sinProject.html Fortunately, the Canadian Government provides social in...
return (10 - sum%10) % 10 } func pow10(e int) int { if e == 0 { return 1 } ret := 10 for ii := 1; ii < e; ii++ { ret *= 10 } return ret } func main() { // There will be only one command line argument if len(os.Args) != 2 { usage() } // the first command line argument is SIN# prefix sinStr := os.A...
{ sum += (d * multiply[i]) % 9 }
conditional_block
sin-gen.go
'0' || c > '9' { panic(fmt.Errorf("Character #%d from SIN_Str '%c' is invalid\n", i, c)) } result = append(result, int(c-'0')) } return result } /* Validation Procedure http://www.ryerson.ca/JavaScript/lectures/forms/textValidation/sinProject.html Fortunately, the Canadian Government provides social in...
(da []int) int { if len(da) != 8 { panic(fmt.Errorf("Internal error: func validate need 8 SIN digits in array as input\n")) } sum := 0 for i, d := range da { sum += (d * multiply[i]) % 9 } return (10 - sum%10) % 10 } func pow10(e int) int { if e == 0 { return 1 } ret := 10 for ii := 1; ii < e; ii++ { ...
validate
identifier_name
sin-gen.go
'0' || c > '9' { panic(fmt.Errorf("Character #%d from SIN_Str '%c' is invalid\n", i, c)) } result = append(result, int(c-'0')) } return result } /* Validation Procedure http://www.ryerson.ca/JavaScript/lectures/forms/textValidation/sinProject.html Fortunately, the Canadian Government provides social in...
The check digit is (50 - 43) 7 = 7 Social Insurance Numbers that do not pass the validation check If the SIN provided by an individual does not pass the verification check, the preparer should confirm the SIN with the employer who received the original number. If you are unable to obtain the correct number for the ...
random_line_split
sin-gen.go
'0' || c > '9' { panic(fmt.Errorf("Character #%d from SIN_Str '%c' is invalid\n", i, c)) } result = append(result, int(c-'0')) } return result } /* Validation Procedure http://www.ryerson.ca/JavaScript/lectures/forms/textValidation/sinProject.html Fortunately, the Canadian Government provides social in...
func pow10(e int) int { if e == 0 { return 1 } ret := 10 for ii := 1; ii < e; ii++ { ret *= 10 } return ret } func main() { // There will be only one command line argument if len(os.Args) != 2 { usage() } // the first command line argument is SIN# prefix sinStr := os.Args[1] padlen := 8 - len(si...
{ if len(da) != 8 { panic(fmt.Errorf("Internal error: func validate need 8 SIN digits in array as input\n")) } sum := 0 for i, d := range da { sum += (d * multiply[i]) % 9 } return (10 - sum%10) % 10 }
identifier_body
_stats.py
[ReferenceType[ba.SessionTeam]] = None self.streak = 0 self.associate_with_sessionplayer(sessionplayer) @property def team(self) -> ba.SessionTeam: """The ba.SessionTeam the last associated player was last on. This can still return a valid result even if the player is gone. ...
for s_player in list(self._player_records.values()): s_player.cancel_multi_kill_timer() s_player.accumscore = 0 s_player.accum_kill_count = 0 s_player.accum_killed_count = 0 s_player.streak = 0 def register_sessionplayer
p_entry.cancel_multi_kill_timer() self._player_records = {} def reset_accum(self) -> None: """Reset per-sound sub-scores."""
random_line_split
_stats.py
ReferenceType[ba.SessionTeam]] = None self.streak = 0 self.associate_with_sessionplayer(sessionplayer) @property def team(self) -> ba.SessionTeam: """The ba.SessionTeam the last associated player was last on. This can still return a valid result even if the player is gone. ...
register_sessionplayer
identifier_name
_stats.py
[ReferenceType[ba.SessionTeam]] = None self.streak = 0 self.associate_with_sessionplayer(sessionplayer) @property def team(self) -> ba.SessionTeam: """The ba.SessionTeam the last associated player was last on. This can still return a valid result even if the player is gone. ...
PopupText(Lstr( value=(('+' + str(score2) + ' ') if showpoints2 else '') + '${N}', subs=[('${N}', name2)]), color=color2, scale=scale2, position=our_pos).autoretain()...
from bastd.actor.popuptext import PopupText # Only award this if they're still alive and we can get # a current position for them. our_pos: Optional[ba.Vec3] = None if self._sessionplayer: if self._sessionplayer.activityplayer is not None: ...
identifier_body
_stats.py
[ReferenceType[ba.SessionTeam]] = None self.streak = 0 self.associate_with_sessionplayer(sessionplayer) @property def team(self) -> ba.SessionTeam: """The ba.SessionTeam the last associated player was last on. This can still return a valid result even if the player is gone. ...
def _apply(name2: Lstr, score2: int, showpoints2: bool, color2: Tuple[float, float, float, float], scale2: float, sound2: Optional[ba.Sound]) -> None: from bastd.actor.popuptext import PopupText # Only award this if they're still alive and we can ...
score = 100 name = Lstr(resource='multiKillText', subs=[('${COUNT}', str(self._multi_kill_count))]) color = (1.0, 0.5, 0.0, 1) scale = 1.3 delay = 1.0 sound = stats.orchestrahitsound4
conditional_block
pattern.rs
/// The length of the smallest pattern, in bytes. minimum_len: usize, /// The largest pattern identifier. This should always be equivalent to /// the number of patterns minus one in this collection. max_pattern_id: PatternID, /// The total number of pattern bytes across the entire collection. Th...
{ // Why not just use memcmp for this? Well, memcmp requires calling out // to libc, and this routine is called in fairly hot code paths. Other // than just calling out to libc, it also seems to result in worse // codegen. By rolling our own memcpy in pure Rust, it seems to appear ...
identifier_body
pattern.rs
ties broken by the order in which they /// were provided by the caller. kind: MatchKind, /// The collection of patterns, indexed by their identifier. by_id: Vec<Vec<u8>>, /// The order of patterns defined for iteration, given by pattern /// identifiers. The order of `by_id` and `order` is alway...
self.i += 1; Some((id, p)) } } /// A pattern that is used in packed searching. #[derive(Clone)] pub struct Pattern<'a>(&'a [u8]); impl<'a> fmt::Debug for Pattern<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Pattern") .field("lit", &String...
if self.i >= self.patterns.len() { return None; } let id = self.patterns.order[self.i]; let p = self.patterns.get(id);
random_line_split
pattern.rs
ties broken by the order in which they /// were provided by the caller. kind: MatchKind, /// The collection of patterns, indexed by their identifier. by_id: Vec<Vec<u8>>, /// The order of patterns defined for iteration, given by pattern /// identifiers. The order of `by_id` and `order` is alway...
(&self) -> usize { self.minimum_len } /// Returns the match semantics used by these patterns. pub fn match_kind(&self) -> &MatchKind { &self.kind } /// Return the pattern with the given identifier. If such a pattern does /// not exist, then this panics. pub fn get(&self, id...
minimum_len
identifier_name
pattern.rs
broken by the order in which they /// were provided by the caller. kind: MatchKind, /// The collection of patterns, indexed by their identifier. by_id: Vec<Vec<u8>>, /// The order of patterns defined for iteration, given by pattern /// identifiers. The order of `by_id` and `order` is always the...
MatchKind::LeftmostLongest => { let (order, by_id) = (&mut self.order, &mut self.by_id); order.sort_by(|&id1, &id2| { by_id[id1 as usize] .len() .cmp(&by_id[id2 as usize].len()) .reve...
{ self.order.sort(); }
conditional_block
pbb_wgangp.py
the Victim GAN model') parser.add_argument('--pos_data_dir', '-posdir', type=str, help='the directory for the positive (training) query images set') parser.add_argument('--neg_data_dir', '-negdir', type=str, help='the directory for the negative (testing) query im...
### define variables global BATCH_SIZE BATCH_SIZE = args.batch_size x = tf.placeholder(tf.float32, shape=(None, OUTPUT_SIZE, OUTPUT_SIZE, 3), name='x') ### initialization init_val_ph = None init_val = {'pos': None, 'neg': None} if args.initialize_type == ...
args, save_dir, load_dir = check_args(parse_arguments()) config_path = os.path.join(load_dir, 'params.pkl') if os.path.exists(config_path): config = pickle.load(open(config_path, 'rb')) OUTPUT_SIZE = config['OUTPUT_SIZE'] GAN_TYPE = config['Architecture'] Z_DIM = config['Z_DIM'] ...
identifier_body
pbb_wgangp.py
the Victim GAN model') parser.add_argument('--pos_data_dir', '-posdir', type=str, help='the directory for the positive (training) query images set') parser.add_argument('--neg_data_dir', '-negdir', type=str, help='the directory for the negative (testing) query im...
try: x_gt = query_imgs[i * BATCH_SIZE:(i + 1) * BATCH_SIZE] if os.path.exists(save_dir_batch): pass else: visualize_gt(x_gt, check_folder(save_dir_batch)) ### initialize z if init_val_ph is not None: ...
for i in tqdm(range(size // BATCH_SIZE)): save_dir_batch = os.path.join(save_dir, str(i))
random_line_split
pbb_wgangp.py
the Victim GAN model') parser.add_argument('--pos_data_dir', '-posdir', type=str, help='the directory for the positive (training) query images set') parser.add_argument('--neg_data_dir', '-negdir', type=str, help='the directory for the negative (testing) query im...
save_files(os.path.join(save_dir, str(i)), ['full_loss', 'z', 'xhat', 'loss_progress'], [vec_loss_curr, z_curr, x_hat_curr, np.array(loss_progress)]) except KeyboardInterrupt: print('Stop optimization\n') break ...
val = sess.run(vec_loss_dict[key], feed_dict={x: x_gt}) save_files(os.path.join(save_dir, str(i)), [key], [val])
conditional_block
pbb_wgangp.py
the Victim GAN model') parser.add_argument('--pos_data_dir', '-posdir', type=str, help='the directory for the positive (training) query images set') parser.add_argument('--neg_data_dir', '-negdir', type=str, help='the directory for the negative (testing) query im...
(sess, z, x, x_hat, init_val_ph, init_val, query_imgs, save_dir, opt, vec_loss, vec_loss_dict): """ z = argmin_z \lambda_1*|x_hat -x|^2 + \lambda_2 * LPIPS(x_hat,x)+ \lambda_3* L_reg where x_hat = G(z) :param sess: session :param z: latent variable ...
optimize_z
identifier_name
oci8_test.go
ContextTimeoutString) if err != nil { fmt.Println("parse context timeout error:", err) return 4 } if !TestDisableDatabase { TestDB = testGetDB() if TestDB == nil { return 6 } } TestTimeString = time.Now().UTC().Format("20060102150405") var i int var buffer bytes.Buffer for i = 0; i < 1000; i++ {...
testRunQueryResults
identifier_name
oci8_test.go
") flag.StringVar(&TestUsername, "username", "", "the username for the Oracle database") flag.StringVar(&TestPassword, "password", "", "the password for the Oracle database") flag.StringVar(&TestContextTimeoutString, "contextTimeout", "30s", "the context timeout for queries") flag.BoolVar(&TestDisableDestructive, "...
var buffer bytes.Buffer for i = 0; i < 1000; i++ { buffer.WriteRune(rune(i)) } testString1 = buffer.String() testByteSlice1 = make([]byte, 2000) for i = 0; i < 2000; i++ { testByteSlice1[i] = byte(i) } testTimeLocUTC, _ = time.LoadLocation("UTC") testTimeLocGMT, _ = time.LoadLocation("GMT") testTimeLocE...
var i int
random_line_split
oci8_test.go
") flag.StringVar(&TestUsername, "username", "", "the username for the Oracle database") flag.StringVar(&TestPassword, "password", "", "the password for the Oracle database") flag.StringVar(&TestContextTimeoutString, "contextTimeout", "30s", "the context timeout for queries") flag.BoolVar(&TestDisableDestructive, "...
fmt.Println("db is nil") return nil } ctx, cancel := context.WithTimeout(context.Background(), TestContextTimeout) err = db.PingContext(ctx) cancel() if err != nil { fmt.Println("ping error:", err) return nil } db.Exec("drop table foo") _, err = db.Exec(sql1) if err != nil { fmt.Println("sql1 erro...
{ os.Setenv("NLS_LANG", "American_America.AL32UTF8") var openString string // [username/[password]@]host[:port][/instance_name][?param1=value1&...&paramN=valueN] if len(TestUsername) > 0 { if len(TestPassword) > 0 { openString = TestUsername + "/" + TestPassword + "@" } else { openString = TestUsername +...
identifier_body
oci8_test.go
!= nil { panic(err) } var dsnTests = []struct { dsnString string expectedDSN *DSN }{ {"oracle://xxmc:xxmc@107.20.30.169:1521/ORCL?loc=America%2FLos_Angeles", &DSN{Username: "xxmc", Password: "xxmc", Connect: "107.20.30.169:1521/ORCL", prefetch_rows: 10, Location: pacific}}, {"xxmc/xxmc@107.20.30.169:152...
{ t.Errorf("get rows error: %v - query: %v", err, queryResult.query) continue }
conditional_block
segment_accountant.rs
segments // always link together, so that we can detect torn // segments during recovery. self.ensure_safe_free_distance(); } segment.draining_to_free(lsn); if self.tip != segment_start && !...
clean_tail_tears
identifier_name
segment_accountant.rs
self.lsn = Some(new_lsn); self.state = Active; } /// Transitions a segment to being in the Inactive state. /// Called in: /// /// PageCache::advance_snapshot for marking when a /// segment has been completely read /// /// SegmentAccountant::recover for when pub fn ac...
); assert_eq!(self.state, Free); self.present.clear(); self.removed.clear();
random_line_split
segment_accountant.rs
.ok { error!( "read corrupted segment header during recovery of segment {}", lid ); tear_at = Some(i); continue; } let expected_prev = segment_header.prev; let actual_prev = logica...
{ self.ordering.remove(&old_lsn); }
conditional_block
Detail.controller.js
.getResourceBundle(); }, /* =========================================================== */ /* event handlers */ /* =========================================================== */ /* =========================================================== */ /* begin: internal ...
ll); MessageToast.show( this.getView().getModel("i18n").getResourceBundle().getText("msgItemAdded")); }, parseProductId: function (sProdId) { return sProdId.split("(")[1].split(")")[0]; }, getProductFromCache: function (sId, sProdPath) { var aOrders = this.getView().getModel("appView").getProperty("/t...
{ sProdId = oEvt.getSource().getBindingContext().getPath(); var sId = this.parseProductId(sProdId); var aOrders = this.getView().getModel("appView").getProperty("/tempOrder"); var oProduct = this.getProductFromCache(sId, sProdId); oProduct.Quantity = Number(sQuant); aOrders = aOrders.filter(fu...
conditional_block
Detail.controller.js
this.getResourceBundle(); }, /* =========================================================== */ /* event handlers */ /* =========================================================== */ /* =========================================================== */ /* begin: inte...
oViewModel = this.getModel("detailView"); // Make sure busy indicator is displayed immediately when // detail view is displayed for the first time oViewModel.setProperty("/delay", 0); // Binding the view will set it to not busy - so the view is always busy if it is not bound oViewModel.setProperty("/...
var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(),
random_line_split
Map.js
ultedTimeOfWaypoints = (routelist, store_address) => { // routelist=routelist.map(({order})=> ) let update_store_address = { address: store_address }; let allorders = routelist.map(({ order }) => order); allorders = [update_store_address, ...allorders]; let count = 0; for (let i = 0; i < allorde...
lng: null, }; if (store_address) { origin.lat = parseFloat(store_address.latitude); origin.lng = parseFloat(store_address.longitude); } let pointlength = 0; if (type === "multiple") { let firstpoint = point[0]; if (this.markerPositions.length > 0) { this.markerP...
makewayPoints(point, type, store_address) { let origin = { lat: null,
random_line_split
Map.js
extends PureComponent { constructor(props) { super(props); this.origin = null; this.firstOrigin = null; this.markerPositions = []; this.markerCounts = 0; this.orignmarker = null; this.destmarker = null; this.destination = null; this.Mode = null; this.google = window.google; ...
Map
identifier_name
Map.js
ultedTimeOfWaypoints = (routelist, store_address) => { // routelist=routelist.map(({order})=> ) let update_store_address = { address: store_address }; let allorders = routelist.map(({ order }) => order); allorders = [update_store_address, ...allorders]; let count = 0; for (let i = 0; i < allorde...
} else { this.markerPositions.push(point); pointlength = point.length - 2; this.origin = new this.google.maps.LatLng(origin.lat, origin.lng); this.orignmarker = this.origin; } let dest = { lat: null, lng: null }; dest.lat = point[point.length - 1].order.address.latitude; de...
{ let firstpoint = point[0]; if (this.markerPositions.length > 0) { this.markerPositions.push(point); } else { this.markerPositions.push(point); } if (this.destination) { pointlength = point.length - 2; pointlength = point.length; } else { poi...
conditional_block
db.go
iB // 12 MiB BlockSize = 8 * units.KiB // 8 KiB // rocksDBByteOverhead is the number of bytes of constant overhead that // should be added to a batch size per operation. rocksDBByteOverhead = 8 ) var ( errFailedToCreateIterator = errors.New("failed to create iterator") _ database.Database = &Database{}...
iteratorOptions := grocksdb.NewDefaultReadOptions() iteratorOptions.SetFillCache(false) return &Database{ db: db, readOptions: grocksdb.NewDefaultReadOptions(), iteratorOptions: iteratorOptions, writeOptions: grocksdb.NewDefaultWriteOptions(), log: log, }, nil } // Has ...
{ return nil, err }
conditional_block
db.go
.ReadWriteExecute); err != nil { return nil, err } db, err := grocksdb.OpenDb(options, file) if err != nil { return nil, err } iteratorOptions := grocksdb.NewDefaultReadOptions() iteratorOptions.SetFillCache(false) return &Database{ db: db, readOptions: grocksdb.NewDefaultReadOptions(...
{ return it.it.Err() }
identifier_body
db.go
errored uint64 } // New returns a wrapped RocksDB object. // TODO: use configBytes to config the database options func New(file string, configBytes []byte, log logging.Logger) (database.Database, error) { filter := grocksdb.NewBloomFilter(BitsPerKey) blockOptions := grocksdb.NewDefaultBlockBasedTableOptions() blo...
for it.Next() { rec := it.Record()
random_line_split
db.go
] == 1, Has, Get, Put, // Delete and batch writes fail with ErrAvoidCorruption. errored uint64 } // New returns a wrapped RocksDB object. // TODO: use configBytes to config the database options func New(file string, configBytes []byte, log logging.Logger) (database.Database, error) { filter := grocksdb.NewBloomFilt...
Replay
identifier_name
history.rs
_MAX_SIZE, max_file_size: DEFAULT_MAX_SIZE, append_duplicate_entries: false, inc_append: false, share: false, file_size: 0, load_duplicates: true, compaction_writes: 0, } } /// Clears out the history. pub fn clear_h...
pub fn len(&self) -> usize { self.buffers.len() } /// Is the history empty pub fn is_empty(&self) -> bool { self.buffers.is_empty() } /// Add a command to the history buffer and remove the oldest commands when the max history /// size has been met. If writing to the disk is...
#[inline(always)]
random_line_split
history.rs
_SIZE, max_file_size: DEFAULT_MAX_SIZE, append_duplicate_entries: false, inc_append: false, share: false, file_size: 0, load_duplicates: true, compaction_writes: 0, } } /// Clears out the history. pub fn clear_histo...
// Every 30 writes "compact" the history file by writing just in memory history. This // is to keep the history file clean and at a reasonable size (not much over max // history size at it's worst). if self.compaction_writes > 29 { if ...
{ // buffers[0] is the oldest entry // the new entry goes to the end if !self.append_duplicate_entries && self.buffers.back().map(|b| b.to_string()) == Some(new_item.to_string()) { return Ok(()); } let item_str = String::from(new_item.clone()); ...
identifier_body
history.rs
mut buf: VecDeque<String> = VecDeque::new(); let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(line) => { if !line.starts_with('#') { buf.push_back(line); } } ...
into_iter
identifier_name
history.rs
). Only loads if length is not equal to current file size. fn load_history_file_test<P: AsRef<Path>>( &mut self, path: P, length: u64, append: bool, ) -> io::Result<u64> { let path = path.as_ref(); let file = if path.exists() { File::open(path)? ...
{ v.push(*i); }
conditional_block
source.py
from itertools import islice from rowgenerators.util import md5_file from .appurl.web.download import Downloader class RowGenerator(object): """Main class for accessing row generators""" def __init__(self, url, *args, downloader=None, **kwargs): from .appurl.url import parse_app_url self._...
random_line_split
source.py
from itertools import islice from rowgenerators.util import md5_file from .appurl.web.download import Downloader class RowGenerator(object): """Main class for accessing row generators""" def __init__(self, url, *args, downloader=None, **kwargs): from .appurl.url import parse_app_url self._...
if len(header_lines) == 1: return header_lines[0] # If there are gaps in the values of a line, copy them forward, so there # is some value in every position for hl in header_lines: last = None for i in range(len(hl)): hli = str(hl[i]...
return []
conditional_block
source.py
from itertools import islice from rowgenerators.util import md5_file from .appurl.web.download import Downloader class RowGenerator(object): """Main class for accessing row generators""" def __init__(self, url, *args, downloader=None, **kwargs): from .appurl.url import parse_app_url self._...
def geoframe(self, *args, **kwargs): """Return a Geopandas dataframe""" try: return self.url.geoframe(*args, **kwargs) except AttributeError: pass try: return self.url.geo_generator.geoframe(*args, **kwargs) except AttributeError: ...
"""Return a pandas dataframe""" try: return self.url.generator.dataframe(*args, **kwargs) except AttributeError: pass try: return self.url.dataframe(*args, **kwargs) except AttributeError: pass raise NotImplementedError("Url '{}'...
identifier_body
source.py
from itertools import islice from rowgenerators.util import md5_file from .appurl.web.download import Downloader class RowGenerator(object): """Main class for accessing row generators""" def __init__(self, url, *args, downloader=None, **kwargs): from .appurl.url import parse_app_url self._...
(object): """Proxies an iterator to remove headers, comments, blank lines from the row stream. The header will be emitted first, and comments are available from properties """ def __init__(self, seq, start=0, header_lines=[], comments=[], end=[], load_headers=True, **kwargs): """ An iterata...
SelectiveRowGenerator
identifier_name
rxcb.rs
>, id: &Window, parent: Option<xcb_window_t>, x: i16, y: i16, width: u16, height: u16, border_width: u16, class: WindowIOClass, visual: Option<VisualID>, valuelist: &WindowValueList) -> Result<(), GenericError> { let serialized = valuelist.serialize(); unsafe { CheckedCookie(xcb_create_window_checked(self...
} } pub type WindowID = xcb_window_t; pub struct Window(WindowID); impl Window { pub(crate) fn id(&self) -> WindowID { self.0 } pub fn replace_property<T: PropertyType + ?Sized>(&self, con: &Connection, property: Atom, value: &T) { value.change_property_of(con, self, property, XCB_PROP_MODE_REPLACE) } } pub tr...
{ let p = self.0.data as *mut _; unsafe { xcb_screen_next(&mut self.0); Some(&*p) } }
conditional_block
rxcb.rs
>, id: &Window, parent: Option<xcb_window_t>, x: i16, y: i16, width: u16, height: u16, border_width: u16, class: WindowIOClass, visual: Option<VisualID>, valuelist: &WindowValueList) -> Result<(), GenericError> { let serialized = valuelist.serialize(); unsafe { CheckedCookie(xcb_create_window_checked(self...
} } } impl<E: PropertyType> PropertyType for [E] { const TYPE_ATOM: Atom = E::TYPE_ATOM; const DATA_STRIDE: u32 = E::DATA_STRIDE; fn change_property_of(&self, con: &Connection, window: &Window, props: Atom, mode: u32) { unsafe { xcb_change_property(con.0, mode as _, window.0, props, E::TYPE_ATOM, E::DATA_S...
{ unsafe { xcb_change_property(con.0, mode as _, window.0, props, XCB_ATOM_ATOM, 32, 1, self as *const Atom as *const _);
random_line_split
rxcb.rs
{ xcb_change_property(con.0, mode as _, window.0, props, E::TYPE_ATOM, E::DATA_STRIDE as _, self.len() as _, self.as_ptr() as _); } } } pub use self::xcb::ffi::XCB_ATOM_WM_NAME; pub struct CheckedCookie<'s>(xcb_void_cookie_t, &'s Connection); impl<'s> CheckedCookie<'s> { pub fn check(&self) -> Result<(), Ge...
{ unsafe { &*self.0 } }
identifier_body
rxcb.rs
(&self) -> Window { Window(self.new_id()) } /*pub fn try_intern(&self, name: &str) -> AtomCookie { AtomCookie(unsafe { xcb_intern_atom(self.0, 0, name.len() as _, name.as_ptr()) }, self) }*/ pub fn intern(&self, name: &str) -> AtomCookie { AtomCookie(unsafe { xcb_intern_atom(self.0, 1, name.len() as _, name.a...
new_window_id
identifier_name
workflow.go
use Workflow ID and RunID of // child workflow to cancel or send signal to child workflow. GetChildWorkflowExecution() Future } // WorkflowType identifies a workflow type. WorkflowType struct { Name string } // WorkflowExecution Details. WorkflowExecution struct { ID string RunID string } // En...
} // NewFuture creates a new future as well as associated Settable that is used to set its value. func NewFuture(ctx Context) (Future, Settable) { impl := &futureImpl{channel: NewChannel(ctx).(*channelImpl)} return impl, impl } // ExecuteActivity requests activity execution in the context of a workflow. // - Conte...
// Name appears in stack traces that are blocked on this Channel. func GoNamed(ctx Context, name string, f func(ctx Context)) { state := getState(ctx) state.dispatcher.newNamedCoroutine(ctx, name, f)
random_line_split
workflow.go
use Workflow ID and RunID of // child workflow to cancel or send signal to child workflow. GetChildWorkflowExecution() Future } // WorkflowType identifies a workflow type. WorkflowType struct { Name string } // WorkflowExecution Details. WorkflowExecution struct { ID string RunID string } // En...
(ctx Context, name string) Channel { return &channelImpl{name: name} } // NewBufferedChannel create new buffered Channel instance func NewBufferedChannel(ctx Context, size int) Channel { return &channelImpl{size: size} } // NewNamedBufferedChannel create new BufferedChannel instance with a given human readable name...
NewNamedChannel
identifier_name
workflow.go
ToCloseTimeout - The end to end timeout for the child workflow execution. // Mandatory: no default ExecutionStartToCloseTimeout time.Duration // TaskStartToCloseTimeout - The decision task timeout for the child workflow. // Optional: default is 10s if this is not provided (or if 0 is provided). TaskStartToCl...
{ if childWorkflowExecution != nil { getWorkflowEnvironment(ctx).RequestCancelWorkflow( *options.domain, childWorkflowExecution.ID, childWorkflowExecution.RunID) } }
conditional_block
workflow.go
use Workflow ID and RunID of // child workflow to cancel or send signal to child workflow. GetChildWorkflowExecution() Future } // WorkflowType identifies a workflow type. WorkflowType struct { Name string } // WorkflowExecution Details. WorkflowExecution struct { ID string RunID string } // En...
// NewChannel create new Channel instance func NewChannel(ctx Context) Channel { state := getState(ctx) state.dispatcher.channelSequence++ return NewNamedChannel(ctx, fmt.Sprintf("chan-%v", state.dispatcher.channelSequence)) } // NewNamedChannel create new Channel instance with a given human readable name. // Nam...
{ thImpl := getHostEnvironment() err := thImpl.RegisterWorkflow(workflowFunc) if err != nil { panic(err) } }
identifier_body
d3viz.js
== 'shapefile') { map = new ShpMap(name, new ShpReader(reader.result), L, lmap, prj); } else if (type == 'geojson' || type == 'json') { var json = JSON.parse(reader.result); map = new JsonMap(name, json, L, lmap, prj); } self._setupGeoVizMap(isMainMap, map, type, c...
window["d3viz"] = d3viz;
random_line_split
d3viz.js
.uuids.indexOf(uuid) == -1 ) { this.uuids.push(uuid); this.mapMeta[uuid] = metaData; } // set uuid to mapcanvas this.geoviz.getMap(this.uuids.length-1).uuid = uuid; }, GetMapMeta: function() { return this.mapMeta[this.GetUUID()]; }, PanMaps : function(offsetX, offsetY) { thi...
{ select_ids += ids[i] + ","; }
conditional_block
input_layer.py
import SpatialRelationCNN.model.augmentation as augment import numpy as np import tensorflow as tf import tfquaternion as tfq class InputLayer(object): """The input pipeline base class, from RelationDataset to projection.""" def __init__(self, dataset, more_augmentation=False): """The input pipeli...
@utility.scope_wrapper def _input_fn(self, obj_ids, translations, rotations, train_batch_size, num_objs, do_augmentation): """The input function 's part that is shared. This function creates the scene point clouds from scene descriptions. Returns: Two tf.Tensors, th...
"""Repeat a[i] repeats[i] times.""" return tf.cond(tf.equal(batch_size, 1), lambda: utility.repeat(a, repeats, num_repeats=2), lambda: utility.repeat(a, repeats, training_batch_size))
identifier_body
input_layer.py
Factory import SpatialRelationCNN.model.augmentation as augment import numpy as np import tensorflow as tf import tfquaternion as tfq class InputLayer(object): """The input pipeline base class, from RelationDataset to projection.""" def __init__(self, dataset, more_augmentation=False): """The input...
one. split: `int` in the interval [1, 15], the index of the split. """ self._create_tf_datasets(split, train_batch_size) next_el = self.iterator.get_next() obj_ids, translations, rotations, labels, is_augmented = next_el points, segment_ids = self._inp...
random_line_split
input_layer.py
import SpatialRelationCNN.model.augmentation as augment import numpy as np import tensorflow as tf import tfquaternion as tfq class InputLayer(object): """The input pipeline base class, from RelationDataset to projection.""" def __init__(self, dataset, more_augmentation=False): """The input pipeli...
@staticmethod def _repeat(a, repeats, batch_size, training_batch_size): """Repeat a[i] repeats[i] times.""" return tf.cond(tf.equal(batch_size, 1), lambda: utility.repeat(a, repeats, num_repeats=2), lambda: utility.repeat(a, repeats, training_batch...
try: self.generators[p] = self.generator_factory.scene_desc_generator(split, p) except ValueError: continue out_shapes = tuple([np.array(x).shape for x in next(self.generators[p]())]) d = tf.data.Dataset.from_generator(self.generators[p], out_types, ...
conditional_block
input_layer.py
import SpatialRelationCNN.model.augmentation as augment import numpy as np import tensorflow as tf import tfquaternion as tfq class InputLayer(object): """The input pipeline base class, from RelationDataset to projection.""" def __init__(self, dataset, more_augmentation=False): """The input pipeli...
(self): """Create two `tf.constant`s of the obj point clouds and their ranges. The point clouds have differing numbers of points. To efficiently process them, all object point clouds are concatenated into one constant. To retrieve them afterwards, we create a second constant with ...
create_cloud_constants
identifier_name
world.py
| | | | | | `--' | # # \______/ |_______/ |__| |__| \______/ # # # # # ##################################################### # This program is free software: you can redistribute it and/or modify...
self.frame_count = 0 self.database = [] self.timer = [Consts["MAX_TIME"], Consts["MAX_TIME"]] self.result = None # Define the players first self.cells.append(Cell(0, [Consts["WORLD_X"] / 4, Consts["WORLD_Y"] / 2], [0, 0], Consts["DEFAULT_RADIUS"])) self.cells.appe...
def __init__(self, player0, player1, names = None): # Variables and setup self.cells_count = 0 # Init self.new_game() self.player0 = player0 self.player1 = player1 self.names = names # Methods def new_game(self): """Create a new game. Arg...
identifier_body
world.py
| | | | | | `--' | # # \______/ |_______/ |__| |__| \______/ # # # # # ##################################################### # This program is free software: you can redistribute it and/or modify #...
print(cause) def eject(self, player, theta): """Create a new cell after the ejection process. Args: player: the player. theta: angle. Returns: """ if player.dead or theta == None: return # Reduce force in pr...
print("Game ends in a draw.")
conditional_block
world.py
| | | | | | `--' | # # \______/ |_______/ |__| |__| \______/ # # # # # ##################################################### # This program is free software: you can redistribute it and/or modify #...
(self, winner, cause, detail = None): """Game over. Args: winner: id of the winner. cause: reason for the end of the game. Returns: """ self.result = { "players": self.names, "winner": winner, "cause": cau...
game_over
identifier_name
world.py
copy import deepcopy from time import perf_counter as pf from consts import Consts from cell import Cell class World(): def __init__(self, player0, player1, names = None): # Variables and setup self.cells_count = 0 # Init self.new_game() self.player0 = player0 self...
tf = pf() self.timer[1] -= tf - ti except Exception as e: logging.error(traceback.format_exc())
random_line_split
stress.go
ResponseLogin{} url := ctx.w.Url("/login", nil) statusCode, err := ctx.w.Post(ctx.c, url, data, body) if err != nil { if isDebugMode { fmt.Printf("Request login error: %v\n", err) } ctx.w.r.requestSent <- false return false } if statusCode == http.StatusOK { ctx.user.AccessToken = body.AccessToken c...
fmt.Printf("Time taken for tests: %dms\n", msTakenTotal) fmt.Printf("Complete requests: %d\n", r.nRequestOk)
random_line_split
stress.go
(err.Error()) } // root user // ss.rootToken = userId2Token(ss.UserMap["root"].Id) } // Load items from item csv file func LoadItems(itemCsv string) { // read items if file, err := os.Open(itemCsv); err == nil { reader := csv.NewReader(file) defer file.Close() for strs, err := reader.Read(); err == nil; st...
() bool { if !ctx.Login() || !ctx.GetItems() || !ctx.CreateCart() { return false } // count := rand.Intn(3) + 1 count := 2 for i := 0; i < count; i++ { if !ctx.CartAddItem() { return false } } data := &RequestMakeOrder{ctx.cartId} body := &ResponseMakeOrder{} url := ctx.UrlWithToken("/orders") status...
MakeOrder
identifier_name
stress.go
(err.Error()) } // root user // ss.rootToken = userId2Token(ss.UserMap["root"].Id) } // Load items from item csv file func LoadItems(itemCsv string) { // read items if file, err := os.Open(itemCsv); err == nil { reader := csv.NewReader(file) defer file.Close() for strs, err := reader.Read(); err == nil; st...
// Get json from uri. func (w *Worker) Get(c *http.Client, url string, bind interface{}) (int, error) { r, err := c.Get(url) if err != nil { if r != nil { ioutil.ReadAll(r.Body) r.Body.Close() } return 0, err } defer r.Body.Close() err = json.NewDecoder(r.Body).Decode(bind) if bind == nil { return...
{ // random choice one host for load balance i := rand.Intn(len(w.ctx.addrs)) addr := w.ctx.addrs[i] s := fmt.Sprintf("http://%s%s", addr, path) if params == nil { return s } p := params.Encode() return fmt.Sprintf("%s?%s", s, p) }
identifier_body
stress.go
(err.Error()) } // root user // ss.rootToken = userId2Token(ss.UserMap["root"].Id) } // Load items from item csv file func LoadItems(itemCsv string) { // read items if file, err := os.Open(itemCsv); err == nil { reader := csv.NewReader(file) defer file.Close() for strs, err := reader.Read(); err == nil; st...
req.Header.Set("Content-Type", "application/json") res, err := c.Do(req) if err != nil { if res != nil { ioutil.ReadAll(res.Body) res.Body.Close() } return 0, err } defer res.Body.Close() err = json.NewDecoder(res.Body).Decode(bind) if res.StatusCode == http.StatusNoContent || bind == nil { return...
{ return 0, err }
conditional_block
geohash.go
2Byte != '0' && base32Dict[base32Byte] == 0 { return false } } return true } func binaryToBase32(binaryBytes []byte) ([]byte, error) { base32Len := (len(binaryBytes) + 4) / 5 resultBase32Bytes := make([]byte, base32Len) tmpIntVal, err := strconv.ParseInt(string(binaryBytes), 2, 64) if err != nil { return ...
binaryEncode := make([]byte, precisonParam.latBinBits+precisonParam.lngBinBits) // merge lat encode and lng encode for i := 0; i < precisonParam.latBinBits+precisonParam.lngBinBits; i++ { if i%2 == 0 { binaryEncode[i] = longitudeBinaryEncode[int(i/2)] } else { binaryEncode[i] = latitudeBinaryEncode[int(i/...
{ longitudeCode, nextLngRange := findBinaryCode(lngRange, longitude) lngRange = nextLngRange longitudeBinaryEncode[i] = longitudeCode }
conditional_block
geohash.go
2Byte != '0' && base32Dict[base32Byte] == 0 { return false } } return true } func binaryToBase32(binaryBytes []byte) ([]byte, error) { base32Len := (len(binaryBytes) + 4) / 5 resultBase32Bytes := make([]byte, base32Len) tmpIntVal, err := strconv.ParseInt(string(binaryBytes), 2, 64) if err != nil { return ...
(base32Bytes []byte) ([]byte, error) { if !checkValidBase32(base32Bytes) { return []byte{}, errors.New("wrong format base32 bytes") } base32Len := len(base32Bytes) var tmpIntVal int64 for i, v := range base32Bytes { tmpIntVal += int64(base32Dict[v]) * int64(math.Pow(32, float64(base32Len-i-1))) } binaryByte...
base32ToBinary
identifier_name
geohash.go
} globalLatitudeRange = Range{minVal: -90, maxVal: 90} globalLongitudeRange = Range{minVal: -180, maxVal: 180} base32Dict = func() []int { baseDictResult := make([]int, 128) for i, v := range base32 { baseDictResult[v] = i } return baseDictResult }() ) func checkValidBase32(base32Bytes []byt...
9: encodePrecison{precision: 9, latBinBits: 22, lngBinBits: 23, vagueRange: 4.78}, 10: encodePrecison{precision: 10, latBinBits: 25, lngBinBits: 25, vagueRange: 0.59}, 11: encodePrecison{precision: 11, latBinBits: 27, lngBinBits: 28, vagueRange: 0.15}, 12: encodePrecison{precision: 12, latBinBits: 30, lngBinBi...
random_line_split
geohash.go
i++ { resultBase32Bytes[base32Len-i-1] = base32[tmpIntVal%32] tmpIntVal /= 32 } return resultBase32Bytes, nil } func base32ToBinary(base32Bytes []byte) ([]byte, error) { if !checkValidBase32(base32Bytes) { return []byte{}, errors.New("wrong format base32 bytes") } base32Len := len(base32Bytes) var tmpIntV...
{ if fromLat, fromLng, err := Decode(fromGeohash); err == nil { if toLat, toLng, err := Decode(toGeohash); err == nil { fromPoint := NewLocation(fromLat, fromLng) toPoint := NewLocation(toLat, toLng) return fromPoint.EuclideanDistance(toPoint), nil } } return -1, errors.New("Invalid geohash") }
identifier_body
thanos.py
APL' ./composites/mylist ## composites saved to ./composites/mylist_{date}.csv import mail_client import math, datetime import pandas import pathlib import numpy as np import seaborn as sns import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import scipy.stats as st import os, sys...
mail_client.mail('xjcarter@gmail.com','THANOS Heartbeat FAILURE! Check Process!',text=uni_list) def get_universe(universe_fn): univ = [line.strip() for line in open(universe_fn)] return univ def thanosize(symbol,df,show_charts=False): CLOSE = 'close' #CLOSE = 'adjusted_close' ## calc ...
mail_client.mail('xjcarter@gmail.com','THANOS Heartbeat!',text=message) except:
random_line_split
thanos.py
,AAPL' ./composites/mylist ## composites saved to ./composites/mylist_{date}.csv import mail_client import math, datetime import pandas import pathlib import numpy as np import seaborn as sns import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import scipy.stats as st import os, s...
(symbol,df,low_bound,high_bound): ## check for a significant deviation within the last 5 days ## if so - send an email!! snapshot = df.tail(5) current_stats = df.tail(1).iloc[0].apply(str).tolist() # initilaize log file if one does not exist if not os.path.isfile(THANOS_LOG): wi...
send_alert
identifier_name
thanos.py
THANOS_DATA = f'{HOME}/thanos_data/' THANOS_CHARTS = f'{HOME}/thanos_charts/' THANOS_LOG = f'{HOME}/thanos_data/thanos_log.csv' ## table formating HEADER_STYLE = r'<th style="padding-top: 10px; padding-bottom: 8px; color: #D8D8D8;" align="center" bgcolor="#2F4F4F">' ROW_STYLE = r'<td style="padding: 8px ...
uni = get_universe(universe_fn) for symbol in uni: df = get_data(symbol) if df is None: print(f'ERROR: {symbol} data fetch error.') else: zz, chart = thanosize(symbol,df) if chart is not None: chart.clf() # send_alert(symbol,zz,0.15,0.85) ...
identifier_body
thanos.py
,AAPL' ./composites/mylist ## composites saved to ./composites/mylist_{date}.csv import mail_client import math, datetime import pandas import pathlib import numpy as np import seaborn as sns import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import scipy.stats as st import os, s...
return plt def send_alert(symbol,df,low_bound,high_bound): ## check for a significant deviation within the last 5 days ## if so - send an email!! snapshot = df.tail(5) current_stats = df.tail(1).iloc[0].apply(str).tolist() # initilaize log file if one does not exist if n...
dates = dts.tail(N) s1 = a.tail(N) s2 = b.tail(N) plt.subplot(1,2,i) plt.title("%s %s: %d days" % (symbol,current_date,N)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m_%d')) #u = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates.tolist()] ...
conditional_block
keras_cnn_pretrain-embedding_classification.py
[word] = coefs f.close() print('Found %s word vectors.' % len(embeddings_index)) # second, prepare text samples and their labels print('Processing text dataset') # texts,labels,word_dict = ReadData.ReadRaw2HierData(TEXT_DATA_DIR,50) texts = [] # list of text samples labels_index =...
for name in sorted(os.listdir(TEXT_DATA_DIR)): path = os.path.join(TEXT_DATA_DIR, name) if os.path.isdir(path): # 是否是 目录 label_id = len(labels_index) labels_index[name] = label_id j = 0 for fname in sorted(os.listdir(path)): if j < N: ...
dex = {} # embedding后的词典 word2vec_results=r"H:\corpus_trained_model\glove.6B\glove.6B.50d.txt" word2vec_results = r"H:\EclipseWorkspace\NetFault_Analysis\Pre-processing\data\vector_list_cut1000-all-50D-w2v.txt" f = open(word2vec_results,'r') for line in f: values = line.split() word = va...
identifier_body
keras_cnn_pretrain-embedding_classification.py
'在训练的过程中训练embedding向量' TEXT_DATA_DIR =r'H:\network_diagnosis_data\cut-500' TEXT_DATA_DIR = r'H:\corpus_trained_model\imdb-large' print('Indexing word vectors.') embeddings_index = {} # embedding后的词典 f = open(word2vec_results,'r') for line in f: values = line.split() word = valu...
w():
identifier_name
keras_cnn_pretrain-embedding_classification.py
_index[word] = coefs f.close() print('Found %s word vectors.' % len(embeddings_index)) # second, prepare text samples and their labels print('Processing text dataset') # texts,labels,word_dict = ReadData.ReadRaw2HierData(TEXT_DATA_DIR,50) texts = [] # list of text samples labels_i...
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) x = Conv1D(128, 5, activation='relu')(embedded_sequences) x = MaxPooling1D(5)(x) x = Conv1D(128, 5, activation='relu')(x) x = MaxPooling1D(5)(x) x = Conv1D(128, 5, activat...
# trainable=False)# 注意weight 的输入形式 print('Training model.') # train a 1D convnet with global maxpooling
random_line_split
keras_cnn_pretrain-embedding_classification.py
.shuffle(indices) data = data[indices] labels = labels[indices] nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0]) x_train = data[:-nb_validation_samples] y_train = labels[:-nb_validation_samples] x_test = data[-nb_validation_samples:] y_test = labels[-nb_validation_samples:]...
ENCE_LENGTH,), dtype='int32') embedded_sequences = embedding_layer(sequence_input) x = Conv1D(128
conditional_block
git.rs
’ve extracted from the repository, but only after we’ve /// actually done so. After { statuses: Git, }, } impl GitRepo { /// Searches through this repository for a path (to a file or directory, /// depending on the prefix-lookup flag) and returns its Git status. /// /// Actually qu...
s if s.contains(git2::Status::WT_TYPECHANGE) => f::GitStatus::TypeChange, s if s.contains(git2::Status::IGNORED) => f::GitStatus::Ignored, s if s.contains(git2::Status::CONFLICTED) => f::GitStatus::Conflicted, _ => f::GitStatus::Not...
random_line_split
git.rs
_iter<I>(iter: I) -> Self where I: IntoIterator<Item=PathBuf> { let iter = iter.into_iter(); let mut git = Self { repos: Vec::with_capacity(iter.size_hint().0), misses: Vec::new(), }; for path in iter { if git.misses.contains(&path) { ...
t { let path = reorient(dir); let s = self.statuses.iter() .filter(|p| if p.1 == git2::Status::IGNORED { path.starts_with(&p.0) } else { p.0.starts_with(&path) }) .fold(g
) -> f::Gi
identifier_name
split.go
(leftRef.key, leftRef.value) // An error should not happen because of the size of the tree if err != nil { panic(err.Error()) } left.rootItem = leftRefNum right := New(1) rightRef := &tree.externalRefs[rootNode.child[1]] rightRefNum, err := tree.addExternalRef(rightRef.key, rightRef.value) // An error should...
(direction byte) { // Walk down from the root, eliding the root as necessary. if tree.rootItemType() == kChildIntNode { rootNode := &tree.internalNodes[tree.rootItem] for rootNode.getChildType(direction) == kChildNil { prevRootItem := tree.rootItem tree.rootItem = tree.internalNodes[prevRootItem].child[1-di...
postSplitElideRootIfNeeded
identifier_name
split.go
(leftRef.key, leftRef.value) // An error should not happen because of the size of the tree if err != nil { panic(err.Error()) } left.rootItem = leftRefNum right := New(1) rightRef := &tree.externalRefs[rootNode.child[1]] rightRefNum, err := tree.addExternalRef(rightRef.key, rightRef.value) // An error should...
key: item.key, value: item.value, } } var popupItem splitItem = splitItem{metaType: kSplitItemPopUp} func createLeftSplit(wg *sync.WaitGroup, tree *Critbit, itemChan chan *splitItem) { defer wg.Done() // Populate the tree _ = tree.populateFromSplitChannel("left", itemChan) // Elide the root and s...
itemID: item.itemID, direction: item.direction, offset: item.offset, bit: item.bit,
random_line_split
split.go
(leftRef.key, leftRef.value) // An error should not happen because of the size of the tree if err != nil { panic(err.Error()) } left.rootItem = leftRefNum right := New(1) rightRef := &tree.externalRefs[rootNode.child[1]] rightRefNum, err := tree.addExternalRef(rightRef.key, rightRef.value) // An error should...
itemID: itemID, direction: childDirection, key: key, value: value, } default: panic(fmt.Sprintf("Node %d has unexpected child type %d in direction %d", nodeNum, node.getChildType(childDirection), childDirection)) } } const ( kSplitItemTreeData = 1 kSplitItemPopUp = 2 ) type spl...
{ node := &tree.internalNodes[nodeNum] itemType := node.getChildType(childDirection) switch itemType { case kChildIntNode: return &splitItem{ metaType: kSplitItemTreeData, itemType: kChildIntNode, itemID: node.child[childDirection], direction: childDirection, offset: node.offset, bit: ...
identifier_body
split.go
Ref.key, leftRef.value) // An error should not happen because of the size of the tree if err != nil { panic(err.Error()) } left.rootItem = leftRefNum right := New(1) rightRef := &tree.externalRefs[rootNode.child[1]] rightRefNum, err := tree.addExternalRef(rightRef.key, rightRef.value) // An error should not ...
switch item.itemType { case kChildIntNode: nodeNum, node := tree.addInternalNode() item.newTreeID = nodeNum node.offset = item.offset node.bit = item.bit case kChildExtRef: refNum, err := tree.addExternalRef(item.key, item.value) // An error should not happen because of the size of the tree ...
{ path = path[:len(path)-1] continue }
conditional_block
usage.go
:= pipe.IncrBy(ctx, key, delta) pipe.Expire(ctx, key, counterTTL) // make sure we expire the counters _, err := pipe.Exec(ctx) if err != nil { return 0, err } return incr.Result() } func (c *counter) decr(ctx context.Context, userID, path string, delta int64, t time.Time) (int64, error) { t = t.UTC() key := ...
TLSConfig: &tls.Config{ InsecureSkipVerify: false, }, }) p := &UsageSvc{ c: &counter{redisClient: rc}, dbService: dbService, } go p.consumeEvents() return p } func (p *UsageSvc) Read(ctx context.Context, request *pb.ReadRequest, response *pb.ReadResponse) error { acc, ok := auth.AccountFromCo...
{ redisConfig := struct { Address string User string Password string }{} val, err := config.Get("micro.usage.redis") if err != nil { log.Fatalf("No redis config found %s", err) } if err := val.Scan(&redisConfig); err != nil { log.Fatalf("Error parsing redis config %s", err) } if len(redisConfig.P...
identifier_body
usage.go
} iter := sc.Iterator() res := []listEntry{} for { if !iter.Next(ctx) { break } key := iter.Val() i, err := c.redisClient.Get(ctx, key).Int64() if err != nil { return nil, err } res = append(res, listEntry{ Service: strings.TrimPrefix(key, keyPrefix), Count: i, }) } return res, iter.E...
{ return err }
conditional_block
usage.go
:= pipe.IncrBy(ctx, key, delta) pipe.Expire(ctx, key, counterTTL) // make sure we expire the counters _, err := pipe.Exec(ctx) if err != nil { return 0, err } return incr.Result() } func (c *counter) decr(ctx context.Context, userID, path string, delta int64, t time.Time) (int64, error) { t = t.UTC() key := ...
return err } if len(keys) == 0 { return nil } if err := c.redisClient.Del(ctx, keys...).Err(); err != nil && err != redis.Nil { return err } return nil } type listEntry struct { Service string Count int64 } func (c *counter) listForUser(userID string, t time.Time) ([]listEntry, error) { ctx := conte...
if err != nil { if err == redis.Nil { return nil }
random_line_split
usage.go
:= pipe.IncrBy(ctx, key, delta) pipe.Expire(ctx, key, counterTTL) // make sure we expire the counters _, err := pipe.Exec(ctx) if err != nil { return 0, err } return incr.Result() } func (c *counter)
(ctx context.Context, userID, path string, delta int64, t time.Time) (int64, error) { t = t.UTC() key := fmt.Sprintf("%s:%s:%s:%s", prefixCounter, userID, t.Format("20060102"), path) pipe := c.redisClient.TxPipeline() decr := pipe.DecrBy(ctx, key, delta) pipe.Expire(ctx, key, counterTTL) // make sure we expire cou...
decr
identifier_name
peer.go
*PeerCom conn *PeerConn //connection To this peer internalChan chan message.Message sendChan chan *InternalMsg recvChan chan<- *InternalMsg quitChan chan interface{} lock sync.RWMutex isRunning int32 knownMsgs *common.RingBuffer } // NewInboundPeer new inbound peer instance...
case <-peer.quitChan: return } switch msg.(type) { case *message.Version: reject := &message.RejectMsg{ Reason: "invalid message, as version messages can only be sent once ", } peer.conn.SendMessage(reject) peer.disconnectNotify(errors.New("receive an invalid message From remote")) retur...
{ peer.knownMsgs.AddElement(msg.MsgId(), struct{}{}) }
conditional_block
peer.go
*PeerCom conn *PeerConn //connection To this peer internalChan chan message.Message sendChan chan *InternalMsg recvChan chan<- *InternalMsg quitChan chan interface{} lock sync.RWMutex isRunning int32 knownMsgs *common.RingBuffer } // NewInboundPeer new inbound peer instance...
// message receive handler func (peer *Peer) recvHandler() { for { var msg message.Message select { case msg = <-peer.internalChan: log.Debug("receive %v type message From peer %s", msg.MsgType(), peer.GetAddr().ToString()) if msg.MsgId() != message.EmptyHash { peer.knownMsgs.AddElement(msg.MsgId(), ...
{ log.Debug("start init the connection To peer %s", peer.addr.ToString()) dialAddr := peer.addr.IP + ":" + strconv.Itoa(int(peer.addr.Port)) conn, err := net.Dial("tcp", dialAddr) if err != nil { log.Info("failed To dial To peer %s, as : %v", peer.addr.ToString(), err) return fmt.Errorf("failed To dial To peer ...
identifier_body
peer.go
"github.com/DSiSc/p2p/message" "net" "strconv" "sync" "sync/atomic" "time" ) const ( MAX_BUF_LEN = 1024 * 256 //the maximum buffer To receive message WRITE_DEADLINE = 60 //deadline of conn write ) // PeerCom provides the basic information of a peer type PeerCom struct { version string ...
random_line_split
peer.go
sync.RWMutex isRunning int32 knownMsgs *common.RingBuffer } // NewInboundPeer new inbound peer instance func NewInboundPeer(serverInfo *PeerCom, addr *common.NetAddress, msgChan chan<- *InternalMsg, conn net.Conn) *Peer { return newPeer(serverInfo, addr, false, false, msgChan, conn) } // NewInboundP...
IsPersistent
identifier_name
data_plt.py
def grid_get(self, X, y, param_grid): grid_search = GridSearchCV(self.model, param_grid, cv=5, scoring="neg_mean_squared_error") grid_search.fit(X, y) print(grid_search.best_params_, np.sqrt(-grid_search.best_score_)) grid_search.cv_results_['mean_test_score'] = np.sqrt(-grid_searc...
self.model = model
identifier_body
data_plt.py
(self, model): self.model = model def grid_get(self, X, y, param_grid): grid_search = GridSearchCV(self.model, param_grid, cv=5, scoring="neg_mean_squared_error") grid_search.fit(X, y) print(grid_search.best_params_, np.sqrt(-grid_search.best_score_)) grid_search.cv_results_...
__init__
identifier_name
data_plt.py
60 - int(h1) * 3600) / 3600 else: tm = (int(h2) * 3600 + int(m2) * 60 - int(m1) * 60 - int(h1) * 3600) / 3600 + 24 return tm def timeTranSecond(t): try: t, m, s = t.split(":") except: if t == '1900/1/9 7:00': return 7 * 3600 / 3600 elif t == '1900/1/1 2:30':...
s2 = ["B1", "B2", "B3", "B8", "B12", "B13", "A21", "A23"] for col in cols2: full[col].fillna(full[col].mode()[0], inplace=True) full['a21_a22_a23'] = full['A21']+full['A22']+full['A23'] cols3 = ["A25", "A27"] for col in cols3: full[col] = full.groupby(['a21_a22_a23'])[col].transform(lambda x: x.fillna(x.median(...
[col].fillna(-1, inplace=True) col
conditional_block
data_plt.py
def timeTranSecond(t): try: t, m, s = t.split(":") except: if t == '1900/1/9 7:00': return 7 * 3600 / 3600 elif t == '1900/1/1 2:30': return (2 * 3600 + 30 * 60) / 3600 elif t == -1: return -1 else: return 0 try: ...
tm = (int(h2) * 3600 + int(m2) * 60 - int(m1) * 60 - int(h1) * 3600) / 3600 else: tm = (int(h2) * 3600 + int(m2) * 60 - int(m1) * 60 - int(h1) * 3600) / 3600 + 24 return tm
random_line_split