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 |
|---|---|---|---|---|
lambda.rs | use dotenv;
use fastspring_keygen_integration::fastspring;
use fastspring_keygen_integration::keygen;
use fastspring_keygen_integration::keygen::{generate_licenses, suspend_license};
use fastspring_keygen_integration::util;
use fastspring_keygen_integration::patreon;
use http::header::CONTENT_TYPE;
use lambda_http::{la... |
let events_json = util::body_to_json(req.body())?;
let events_json = events_json["events"].as_array().ok_or("invalid format")?;
// TODO do not reply OK every time: check each event
for e in events_json {
let ty = e["type"].as_str().ok_or("invalid format")?;
let data = &e["data"];
... | {
return Ok(Response::builder()
.status(http::StatusCode::UNAUTHORIZED)
.body(Body::default())
.unwrap());
} | conditional_block |
state.rs | use std::cmp::min;
use std::collections::BTreeMap;
use chrono::Utc;
use tako::gateway::{
CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage,
TaskState, TaskUpdate, ToGatewayMessage,
};
use tako::ItemId;
use tako::{define_wrapped_type, TaskId};
use crate::server::autoalloc... |
pub fn new_job_id(&mut self) -> JobId {
let id = self.job_id_counter;
self.job_id_counter += 1;
id.into()
}
pub fn revert_to_job_id(&mut self, id: JobId) {
self.job_id_counter = id.as_num();
}
pub fn last_n_ids(&self, n: u32) -> impl Iterator<Item = JobId> {
... | {
let job_id: JobId = *self.base_task_id_to_job_id.range(..=task_id).next_back()?.1;
let job = self.jobs.get_mut(&job_id)?;
if task_id
< TakoTaskId::new(
job.base_task_id.as_num() + job.n_tasks() as <TaskId as ItemId>::IdType,
)
{
Some(... | identifier_body |
state.rs | use std::cmp::min;
use std::collections::BTreeMap;
use chrono::Utc;
use tako::gateway::{
CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage,
TaskState, TaskUpdate, ToGatewayMessage,
};
use tako::ItemId;
use tako::{define_wrapped_type, TaskId};
use crate::server::autoalloc... | (&mut self, msg: TaskUpdate, backend: &Backend) {
log::debug!("Task id={} updated {:?}", msg.id, msg.state);
let (mut job_id, mut is_job_terminated): (Option<JobId>, bool) = (None, false);
match msg.state {
TaskState::Running {
worker_ids,
context,
... | process_task_update | identifier_name |
state.rs | use std::cmp::min;
use std::collections::BTreeMap;
use chrono::Utc;
use tako::gateway::{
CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage,
TaskState, TaskUpdate, ToGatewayMessage,
};
use tako::ItemId;
use tako::{define_wrapped_type, TaskId};
use crate::server::autoalloc... |
self.event_storage
.on_worker_added(msg.worker_id, msg.configuration);
}
pub fn process_worker_lost(
&mut self,
_state_ref: &StateRef,
_tako_ref: &Backend,
msg: LostWorkerMessage,
) {
log::debug!("Worker lost id={}", msg.worker_id);
let ... | {
autoalloc.on_worker_connected(msg.worker_id, &msg.configuration);
} | conditional_block |
state.rs | use std::cmp::min;
use std::collections::BTreeMap;
use chrono::Utc;
use tako::gateway::{
CancelTasks, FromGatewayMessage, LostWorkerMessage, NewWorkerMessage, TaskFailedMessage,
TaskState, TaskUpdate, ToGatewayMessage,
};
use tako::ItemId;
use tako::{define_wrapped_type, TaskId};
use crate::server::autoalloc... | assert_eq!(
state
.get_job_mut_by_tako_task_id(task_id.into())
.map(|j| j.job_id.as_num()),
expected
);
}
#[test]
fn test_find_job_id_by_task_id() {
let state_ref = create_hq_state();
let mut state = state_ref.get_mut()... | random_line_split | |
parse.rs | use crate::{
parse_utils::*,
substitute::{substitute, Substitution},
SubstitutionGroup,
};
use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree};
use std::{collections::HashSet, iter::Peekable};
/// Parses the attribute part of an invocation of duplicate, returning
/// all the substitutions ... | (
tree: TokenTree,
existing: &Option<HashSet<String>>,
) -> Result<SubstitutionGroup, (Span, String)>
{
// Must get span now, before it's corrupted.
let tree_span = tree.span();
let group = check_group(
tree,
"Hint: When using verbose syntax, a substitutions must be enclosed in a \
group.\nExample:\n..\n[\n... | extract_verbose_substitutions | identifier_name |
parse.rs | use crate::{
parse_utils::*,
substitute::{substitute, Substitution},
SubstitutionGroup,
};
use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree};
use std::{collections::HashSet, iter::Peekable};
/// Parses the attribute part of an invocation of duplicate, returning
/// all the substitutions ... |
/// Validates that the attribute part of a duplicate invocation uses
/// the short syntax and returns the substitution that should be made.
fn validate_short_attr(
attr: TokenStream,
) -> Result<Vec<(String, Vec<String>, Vec<TokenStream>)>, (Span, String)>
{
if attr.is_empty()
{
return Err((Span::call_site(), "N... | {
// Must get span now, before it's corrupted.
let tree_span = tree.span();
let group = check_group(
tree,
"Hint: When using verbose syntax, a substitutions must be enclosed in a \
group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \
]\n]",
)?;
if group.stream().into... | identifier_body |
parse.rs | use crate::{
parse_utils::*,
substitute::{substitute, Substitution},
SubstitutionGroup,
};
use proc_macro::{token_stream::IntoIter, Ident, Span, TokenStream, TokenTree};
use std::{collections::HashSet, iter::Peekable};
/// Parses the attribute part of an invocation of duplicate, returning
/// all the substitutions ... | let group = check_group(
tree,
"Hint: When using verbose syntax, a substitutions must be enclosed in a \
group.\nExample:\n..\n[\n\tidentifier1 [ substitution1 ]\n\tidentifier2 [ substitution2 \
]\n]",
)?;
if group.stream().into_iter().count() == 0
{
return Err((group.span(), "No substitution groups fo... | ) -> Result<SubstitutionGroup, (Span, String)>
{
// Must get span now, before it's corrupted.
let tree_span = tree.span(); | random_line_split |
font.go | // Copyright 2015, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.
package eweygewey
/*
Based primarily on gltext found at https://github.com/go-gl/gltext
But also based on examples from the freetype-go project:
https://github.com/golang/freetype
This implementation differs in th... |
// loadRGBAToTextureExt takes a byte slice and throws it into an OpenGL texture.
func (f *Font) loadRGBAToTextureExt(rgba []byte, imageSize, magFilter, minFilter, wrapS, wrapT int32) graphics.Texture {
tex := f.Owner.gfx.GenTexture()
f.Owner.gfx.ActiveTexture(graphics.TEXTURE0)
f.Owner.gfx.BindTexture(graphics.TEX... | {
return f.loadRGBAToTextureExt(rgba, imageSize, graphics.LINEAR, graphics.LINEAR, graphics.CLAMP_TO_EDGE, graphics.CLAMP_TO_EDGE)
} | identifier_body |
font.go | // Copyright 2015, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.
package eweygewey
/*
Based primarily on gltext found at https://github.com/go-gl/gltext
But also based on examples from the freetype-go project:
https://github.com/golang/freetype
This implementation differs in th... | (fixedInt fixed.Int26_6) float32 {
var result float32
i := int32(fixedInt)
result += float32(i >> 6)
result += float32(i&0x003F) / float32(64.0)
return result
}
// TextRenderData is a structure containing the raw OpenGL VBO data needed
// to render a text string for a given texture.
type TextRenderData struct {
... | fixedInt26ToFloat | identifier_name |
font.go | // Copyright 2015, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.
package eweygewey
/*
Based primarily on gltext found at https://github.com/go-gl/gltext
But also based on examples from the freetype-go project:
https://github.com/golang/freetype
This implementation differs in th... |
return w * fontScale
}
// fixedInt26ToFloat converts a fixed int 26:6 precision to a float32.
func fixedInt26ToFloat(fixedInt fixed.Int26_6) float32 {
var result float32
i := int32(fixedInt)
result += float32(i >> 6)
result += float32(i&0x003F) / float32(64.0)
return result
}
// TextRenderData is a structure ... | {
// calculate up to the stopIndex but do not include it
if i+charStartIndex >= stopIndex {
break
}
adv, _ := f.face.GlyphAdvance(ch)
w += fixedInt26ToFloat(adv)
} | conditional_block |
font.go | // Copyright 2015, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.
package eweygewey
/*
Based primarily on gltext found at https://github.com/go-gl/gltext
But also based on examples from the freetype-go project:
https://github.com/golang/freetype
This implementation differs in th... | }
// OffsetForIndex returns the width offset that will fit just before the `stopIndex`
// number character in the msg.
func (f *Font) OffsetForIndex(msg string, stopIndex int) float32 {
return f.OffsetForIndexAdv(msg, 0, stopIndex)
}
// OffsetForIndexAdv returns the width offset that will fit just before the `stopIn... |
return w * fontScale | random_line_split |
component_catalog.py | #
# Copyright 2018-2023 Elyra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
def on_modified(self, event):
"""Fires when the component manifest file is modified."""
self.log.debug(f"ManifestFileChangeHandler: file '{event.src_path}' has been modified.")
manifest = self.component_cache._load_manifest(filename=event.src_path)
if manifest: # only update the m... | """Dispatches delete and modification events pertaining to the manifest filename"""
if "elyra-component-manifest" in event.src_path:
super().dispatch(event) | identifier_body |
component_catalog.py | #
# Copyright 2018-2023 Elyra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
else:
self.log.debug(f"CacheUpdateWorker completed for catalog: '{thread.name}', action: '{thread.action}'.")
# Thread has been joined and can be removed from the list
self._threads.remove(thread)
# Mark cache task as complete
... | outstanding_threads = True
# Report on a long-running thread if CATALOG_UPDATE_TIMEOUT is exceeded
time_since_last_check = int(time.time() - thread.last_warn_time)
if time_since_last_check > CATALOG_UPDATE_TIMEOUT:
thread.last_warn_time = time.time()
... | conditional_block |
component_catalog.py | #
# Copyright 2018-2023 Elyra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | (template_name: str) -> Template:
"""
Loads the jinja template of the given name from the
elyra/templates/components folder
"""
loader = PackageLoader("elyra", "templates/components")
template_env = Environment(loader=loader)
template_env.policies["json.dumps_kwar... | load_jinja_template | identifier_name |
component_catalog.py | #
# Copyright 2018-2023 Elyra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | if self.is_server_process:
# Remove all existing manifest files from previous processes
self._remove_all_manifest_files()
# Start the watchdog if it's not alive, prevents redundant starts
if not self.observer.is_alive():
se... | # Proceed only if singleton instance has been created
if self.initialized:
# The cache manager will work on manifest and cache tasks on an
# in-process basis as load() is only called during startup from
# the server process. | random_line_split |
run.py | #!/usr/bin/env python
from time import sleep
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.debug("Setup logging")
from miniboa import TelnetServer
from . import state
PRODUCT_NAME = "iMyFace"
AUTH_DB = {}
SERVER_RUN = True
AUTH_RETRY = 2
def on_connect(client):
... |
def process_clients():
"""
Check each client, if client.cmd_ready == True then there is a line of
input available via client.get_command().
"""
for client in state.CLIENT_LIST:
if client.active and client.cmd_ready:
logging.debug("Found a message, processing...")
ms... | """ lost, or disconnected clients
"""
logging.info("Lost connection to %s" % client.addrport() )
state.prune_client_state(client)
state.prune_client_list(client)
#broadcast('%s leaves the conversation.\n' % client.addrport() ) | identifier_body |
run.py | #!/usr/bin/env python
from time import sleep
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.debug("Setup logging")
from miniboa import TelnetServer
from . import state
PRODUCT_NAME = "iMyFace"
AUTH_DB = {}
SERVER_RUN = True
AUTH_RETRY = 2
def on_connect(client):
... |
if not CLIENT_STATE[client].has_key('auth_retry'):
CLIENT_STATE[client]['auth_retry'] = 0
if auth(client, msg):
logging.info("Client %s logged in." % (CLIENT_STATE[client]['user_id']))
_main_menu(client, msg)
else:
logging.debug("Client not logged in")
if CLIENT_ST... | logging.debug(str(state.CLIENT_STATE))
logging.debug(str(AUTH_DB))
logging.debug(str(state.CLIENT_LIST))
return | conditional_block |
run.py | #!/usr/bin/env python
from time import sleep
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.debug("Setup logging")
from miniboa import TelnetServer
from . import state
PRODUCT_NAME = "iMyFace"
AUTH_DB = {}
SERVER_RUN = True
AUTH_RETRY = 2
def on_connect(client):
... | # Main
#------------------------------------------------------------------------------
if __name__ == '__main__':
telnet_server = TelnetServer(
port=7777,
address='',
on_connect=on_connect,
on_disconnect=on_disconnect,
timeout = .05
)
logging.info("Listen... | # elif cmd == 'shutdown':
# SERVER_RUN = False
#------------------------------------------------------------------------------ | random_line_split |
run.py | #!/usr/bin/env python
from time import sleep
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.debug("Setup logging")
from miniboa import TelnetServer
from . import state
PRODUCT_NAME = "iMyFace"
AUTH_DB = {}
SERVER_RUN = True
AUTH_RETRY = 2
def on_connect(client):
... | ():
if not AUTH_DB.has_key(msg):
CLIENT_STATE[client]['user_id'] = msg
CLIENT_STATE[client]['auth_status'] = 'enroll_pass'
client.send("New password: ")
client.password_mode_on()
else:
client.send("%s already taken, try something else: " % msg)... | enroll_user | identifier_name |
editorBrowser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | */
position: editorCommon.IPosition;
/**
* Placement preference for position, in order of preference.
*/
preference: ContentWidgetPositionPreference[];
}
/**
* A content widget renders inline with the text and can be easily placed 'near' an editor position.
*/
export interface IContentWidget {
/**
* Rende... | * Desired position for the content widget.
* `preference` will also affect the placement. | random_line_split |
dag_abm_catalogo_ubm.js | app.controller('dag_abm_catalogo_ubmController', function ($scope, $route,$rootScope, DreamFactory, CONFIG,sessionService,ngTableParams,$filter,sweet,$timeout, $routeParams, $location, $http, Data, LogGuardarInfo, $sce, registroLog, FileUploader, $window) {
// muestra la imagen guardada en el servidor
$scope.imprimi... | };
// adicionar nodo en el arbol
$scope.addNode = function() {
if ($scope.agregado == "false") {
var nameNode = $scope.datos.DAG_CAT_PRESUP_ITEM;
var idNode = parseInt($scope.nodoAr.children.length) + 1;
var padreNode = parseInt($scope.nodoAr.id);
//console.log(nameNode, " ", idNode);
$('#tree1').t... | ode is null
// a node was deselected
// e.previous_node contains the deselected node
}
}
}
);
| conditional_block |
dag_abm_catalogo_ubm.js | app.controller('dag_abm_catalogo_ubmController', function ($scope, $route,$rootScope, DreamFactory, CONFIG,sessionService,ngTableParams,$filter,sweet,$timeout, $routeParams, $location, $http, Data, LogGuardarInfo, $sce, registroLog, FileUploader, $window) {
// muestra la imagen guardada en el servidor
$scope.imprimi... | caracteristicas1: $scope.caracteristicas1
});
}
//console.log($scope.item);
}
})
.error(function(data){
sweet.show('', 'Error al cargar la informacion del item: ', 'error');
});
};
// Adiciona items
$scope.pushItem = function () {
var size = Object.... | $scope.item.push({
id: DetItem[j].id,
partida: $scope.partida,
nombre: DetItem[j].nombre,
caracteristicas: nodo_carac, | random_line_split |
Buy.js | import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import emailjs from "emailjs-com";
class Buy extends React.Component {
constructor(props) {
super(props);
this.state = {
productEmail: "",
};
}
obtainProductsLocalStorage() {
let productLS;
if (loc... | else {
const loadingGif = document.querySelector("#load");
loadingGif.style.display = "block";
const send = document.createElement("img");
send.src = "../images/mail.gif";
send.id = "mailImage";
let productsLS, product;
productsLS = JSON.parse(localStorage.getItem("productos")... | {
window.alert("Por favor, diligencie todos los campos");
} | conditional_block |
Buy.js | import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import emailjs from "emailjs-com";
class Buy extends React.Component {
constructor(props) {
super(props);
this.state = {
productEmail: "",
};
}
obtainProductsLocalStorage() {
let productLS;
if (loc... | obtainEvent(e) {
e.preventDefault();
this.totalCalculate();
let id, cant, product, productsLS;
if (e.target.classList.contains("cantidad")) {
product = e.target.parentElement.parentElement;
id = product.querySelector("a").getAttribute("data-id");
cant = product.querySelector("input")... | {
e.preventDefault();
if (this.obtainProductsLocalStorage().length === 0) {
window.alert(
"No se puede realizar la compra porque no hay productos seleccionados"
);
window.location.href = "/menu";
} else if (
document.getElementById("client").value === "" ||
document.get... | identifier_body |
Buy.js | import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import emailjs from "emailjs-com";
class Buy extends React.Component {
constructor(props) {
super(props);
this.state = {
productEmail: "",
};
}
obtainProductsLocalStorage() { | productLS = JSON.parse(localStorage.getItem("productos"));
}
return productLS;
}
totalCalculate() {
let productLS;
let total = 0,
subtotal = 0,
igv = 0;
productLS = this.obtainProductsLocalStorage();
for (let i = 0; i < productLS.length; i++) {
let element = Number(p... | let productLS;
if (localStorage.getItem("productos") === null) {
productLS = [];
} else { | random_line_split |
Buy.js | import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import emailjs from "emailjs-com";
class Buy extends React.Component {
constructor(props) {
super(props);
this.state = {
productEmail: "",
};
}
obtainProductsLocalStorage() {
let productLS;
if (loc... | () {
let productLS;
let total = 0,
subtotal = 0,
igv = 0;
productLS = this.obtainProductsLocalStorage();
for (let i = 0; i < productLS.length; i++) {
let element = Number(productLS[i].precio * productLS[i].cantidad);
total = total + element;
}
igv = parseFloat(total * 0.1... | totalCalculate | identifier_name |
message.pb.go | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Soft... |
func (m *VectorClock) XXX_Merge(src proto.Message) {
xxx_messageInfo_VectorClock.Merge(m, src)
}
func (m *VectorClock) XXX_Size() int {
return m.Size()
}
func (m *VectorClock) XXX_DiscardUnknown() {
xxx_messageInfo_VectorClock.DiscardUnknown(m)
}
var xxx_messageInfo_VectorClock proto.InternalMessageInfo
func (m *... | {
if deterministic {
return xxx_messageInfo_VectorClock.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
} | identifier_body |
message.pb.go | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Soft... |
b := dAtA[iNdEx]
iNdEx++
m.Clock |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field ClusterId", wireType)
}
m.ClusterId = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
retu... | {
return io.ErrUnexpectedEOF
} | conditional_block |
message.pb.go | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Soft... | 0xff, 0xff, 0xc4, 0x11, 0xe0, 0xe1, 0x11, 0x01, 0x00, 0x00,
}
func (this *VectorClock) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*VectorClock)
if !ok {
that2, ok := that.(VectorClock)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil ... | 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x23, 0x3d, 0x5f, 0x0f, 0xee, 0xea,
0xcc, 0x7c, 0x6c, 0x9e, 0xb4, 0x06, 0x33, 0x92, 0xd8, 0xc0, 0x7e, 0x34, 0x06, 0x04, 0x00, 0x00, | random_line_split |
message.pb.go | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Soft... | () int64 {
if m != nil {
return m.ClusterId
}
return 0
}
func init() {
proto.RegisterType((*VectorClock)(nil), "temporal.server.api.clock.v1.VectorClock")
}
func init() {
proto.RegisterFile("temporal/server/api/clock/v1/message.proto", fileDescriptor_86d20c4676353367)
}
var fileDescriptor_86d20c4676353367 = [... | GetClusterId | identifier_name |
scripts.py | import os
import sys
import codecs
import re
from ansi2html import Ansi2HTMLConverter
from mtaac_package.CoNLL_file_parser import conll_file
from mtaac_package.common_functions import *
from cdliconll2conllu.converter import CdliCoNLLtoCoNLLUConverter
##from conllu.convert import convert as conllu2brat
from SPARQLTrans... | return None
command = self.CoNLLRDFFormatter_command() + ['-conll'] \
+ columns
(CONLLstr, errors) = self.run(
command,
cwd_path=f_path,
stdin_str=stdin_str,
decode_stdout=True)
CONLLstr = CONLLstr.replace(' #', ' \n#') \
.replace('\t#', '\n#').repl... | if f_path==None and stdin_str==None:
print('rdf2conll wrapper: specify path OR string.') | random_line_split |
scripts.py | import os
import sys
import codecs
import re
from ansi2html import Ansi2HTMLConverter
from mtaac_package.CoNLL_file_parser import conll_file
from mtaac_package.common_functions import *
from cdliconll2conllu.converter import CdliCoNLLtoCoNLLUConverter
##from conllu.convert import convert as conllu2brat
from SPARQLTrans... | (self, filename):
'''
Convert CDLI-CoNLL to CoNLL-U from file.
'''
sp.run(['cdliconll2conllu', '-i', filename, '-v'], print_stdout=False)
cdli_conll_u = CC2CU()
#---/ CONLL-U <> CONLL-RDF /---------------------------------------------------
#
class CoNLL2RDF(common_functions):
'''
Wrapper around C... | convert_from_file | identifier_name |
scripts.py | import os
import sys
import codecs
import re
from ansi2html import Ansi2HTMLConverter
from mtaac_package.CoNLL_file_parser import conll_file
from mtaac_package.common_functions import *
from cdliconll2conllu.converter import CdliCoNLLtoCoNLLUConverter
##from conllu.convert import convert as conllu2brat
from SPARQLTrans... |
def conll2rdf(self, f_path, columns_typ):
'''
Run Java CoNNL2RDF script to convert CoNLL file to RDF.
'''
#self.define_columns(columns_typ)
command = self.CoNLLStreamExtractor_command() + ['../data/'] \
+ self.columns
self.dump_rdf(rdf_str, f_path)
def rdf2conll(self, column... | '''
Run Java compiler with command.
'''
self.run([r'%s' %self.JAVAC_PATH,
'-d', r'%s' %target_path,
'-g',
'-cp', r'%s' %cp_path,
]+[r'%s' %f for f in src_files_lst],
cwd_path=cwd_path) | identifier_body |
scripts.py | import os
import sys
import codecs
import re
from ansi2html import Ansi2HTMLConverter
from mtaac_package.CoNLL_file_parser import conll_file
from mtaac_package.common_functions import *
from cdliconll2conllu.converter import CdliCoNLLtoCoNLLUConverter
##from conllu.convert import convert as conllu2brat
from SPARQLTrans... |
stdout_lst = [b for b in stdout.split(b'\n') if b not in shell_lst]
if typ==bytes:
errors = b'\n'.join(shell_lst)
stdout = b'\n'.join(stdout_lst)
## print(stdout.decode('utf-8'))
## print(errors.decode('utf-8'))
elif typ==str:
errors = b'\n'.join(shell_lst).decode('utf-8')
... | for m in shell_markers:
if m in b:
shell_lst.append(b)
break | conditional_block |
imp.rs | use std::mem;
use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder};
use memchr::{memchr, memchr2, memchr3, memmem};
use regex_syntax::hir::literal::{Literal, Literals};
/// A prefix extracted from a compiled regular expression.
///
/// A regex prefix is a set of literal strings that *must* be matched at ... |
}
#[derive(Debug)]
pub enum LiteralIter<'a> {
Empty,
Bytes(&'a [u8]),
Single(&'a [u8]),
AC(&'a [Literal]),
Packed(&'a [Literal]),
}
impl<'a> Iterator for LiteralIter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
match *self {
LiteralIter::Empt... | {
if lits.literals().is_empty() {
return Matcher::Empty;
}
if sset.dense.len() >= 26 {
// Avoid trying to match a large number of single bytes.
// This is *very* sensitive to a frequency analysis comparison
// between the bytes in sset and the comp... | identifier_body |
imp.rs | use std::mem;
use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder};
use memchr::{memchr, memchr2, memchr3, memmem};
use regex_syntax::hir::literal::{Literal, Literals};
/// A prefix extracted from a compiled regular expression.
///
/// A regex prefix is a set of literal strings that *must* be matched at ... | (&self, haystack: &[u8]) -> Option<(usize, usize)> {
for lit in self.iter() {
if lit.len() > haystack.len() {
continue;
}
if lit == &haystack[0..lit.len()] {
return Some((0, lit.len()));
}
}
None
}
/// Like ... | find_start | identifier_name |
imp.rs | use std::mem;
use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder};
use memchr::{memchr, memchr2, memchr3, memmem};
use regex_syntax::hir::literal::{Literal, Literals};
/// A prefix extracted from a compiled regular expression.
///
/// A regex prefix is a set of literal strings that *must* be matched at ... | }
}
fn prefixes(lits: &Literals) -> SingleByteSet {
let mut sset = SingleByteSet::new();
for lit in lits.literals() {
sset.complete = sset.complete && lit.len() == 1;
if let Some(&b) = lit.get(0) {
if !sset.sparse[b as usize] {
... | complete: true,
all_ascii: true, | random_line_split |
imp.rs | use std::mem;
use aho_corasick::{self, packed, AhoCorasick, AhoCorasickBuilder};
use memchr::{memchr, memchr2, memchr3, memmem};
use regex_syntax::hir::literal::{Literal, Literals};
/// A prefix extracted from a compiled regular expression.
///
/// A regex prefix is a set of literal strings that *must* be matched at ... | else {
let next = &one[..];
*one = &[];
Some(next)
}
}
LiteralIter::AC(ref mut lits) => {
if lits.is_empty() {
None
} else {
let next = &lits[0];
... | {
None
} | conditional_block |
GetOutput.py | from Actor import *
import common
import string, os, time
from crab_util import *
class GetOutput(Actor):
def __init__(self, *args):
self.cfg_params = args[0]
self.jobs = args[1]
self.log=0
dir = os.getcwd()+'/'
self.outDir = self.cfg_params.get('USER.outputdir' ,c... |
def parseFinalReport(self, input):
"""
Parses the FJR produced by job in order to retrieve
the WrapperExitCode and ExeExitCode.
Updates the BossDB with these values.
"""
from ProdCommon.FwkJobRep.ReportParser import readJobReport
codeValue = {}
... | """
Untar Output
"""
listCode = []
job_id = []
success_ret = 0
size = 0 # in kB
for id in list_id:
runningJob = task.getJob( id ).runningJob
if runningJob.isError() :
continue
file = 'out_files_'+ str(id)+'.tgz'
... | identifier_body |
GetOutput.py | from Actor import *
import common
import string, os, time
from crab_util import *
class GetOutput(Actor):
def __init__(self, *args):
self.cfg_params = args[0]
self.jobs = args[1]
self.log=0
dir = os.getcwd()+'/'
self.outDir = self.cfg_params.get('USER.outputdir' ,c... |
codeValue["storage"] = pfns
codeValue["lfn"] = lfns
return codeValue
def moveOutput(self,id, max_id,path,file):
"""
Move output of job already retrieved
into the correct backup directory
"""
Dir_Base=path +'Submission_'
for i in ran... | if common.scheduler.name().upper() not in ['LSF', 'CAF', 'PBS', 'PBSV2'] and codeValue["wrapperReturnCode"] == 60308:
pfns.append(os.path.dirname(aFile['SurlForGrid'])+'/')
else:
pfns.append(os.path.dirname(aFile['PFN'])+'/')
##... | conditional_block |
GetOutput.py | from Actor import *
import common
import string, os, time
from crab_util import *
class GetOutput(Actor):
def __init__(self, *args):
self.cfg_params = args[0]
self.jobs = args[1]
self.log=0
dir = os.getcwd()+'/'
self.outDir = self.cfg_params.get('USER.outputdir' ,c... | (self):
"""
Get output for a finished job with id.
"""
self.checkBeforeGet()
# Get first job of the list
if not self.dontCheckSpaceLeft and not has_freespace(self.outDir, 10*1024): # First check for more than 10 Mb
msg = "You have LESS than 10 MB of free space... | getOutput | identifier_name |
GetOutput.py | from Actor import *
import common
import string, os, time
from crab_util import *
class GetOutput(Actor):
def __init__(self, *args):
self.cfg_params = args[0]
self.jobs = args[1]
self.log=0
dir = os.getcwd()+'/'
self.outDir = self.cfg_params.get('USER.outputdir' ,c... | #### Filling BOSS DB with SE name and LFN, for edm and not_edm files ####
lfns=[]
pfns=[]
if (len(jobReport.files) != 0):
for f in jobReport.files:
if f['LFN']:
lfns.append(f['LFN'])
if f['PFN']:
... | codeValue.pop("applicationReturnCodeOrig")
| random_line_split |
connect_four.py | # This script implements connect four and highlights winning series,
# series with greater than three consecutive Xs or Os.
# The pick_markers module for the start of the game.
def pick_markers():
'''
Module to assign X or O to the two players. Returns a list with two elements,
where index 0 is pla... |
def vertical_win(marker):
for x2 in range(0,7):
# Iterate up a columns checking for four-in-a-row. Run this check on spaces in first four rows (x3) of the
# to avoid going off the board (an indexing error).
for x3 in range(0,4):
if marker == space... | for x2 in [0,7,14,21,28,35,42]:
for x3 in range(0,4): # Can't be 7
if marker == spaces[x2+x3] == spaces[x2+x3+1] == spaces[x2+x3+2] == spaces[x2+x3+3]:
return [True, x2+x3, x2+x3+1, x2+x3+2, x2+x3+3]
#return True, and the first winning horizontal ... | identifier_body |
connect_four.py | # This script implements connect four and highlights winning series,
# series with greater than three consecutive Xs or Os.
# The pick_markers module for the start of the game.
def | ():
'''
Module to assign X or O to the two players. Returns a list with two elements,
where index 0 is player 1's marker, index 1 is player 2's marker.
'''
import string
plyr1 = input("Player 1, choose X or O as your marker: ")
plyr1_mkr = plyr1.lower()
while True:
... | pick_markers | identifier_name |
connect_four.py | # This script implements connect four and highlights winning series,
# series with greater than three consecutive Xs or Os.
# The pick_markers module for the start of the game.
def pick_markers():
'''
Module to assign X or O to the two players. Returns a list with two elements,
where index 0 is pla... | ''' Uses the the contents of spaces (list variable) to construct/update
the gameboard on the console. '''
clear()
while len(spaces) < 49:
spaces.append(' ')
# Start with 7 empty lists... Index 0 corresponds to the TOP ROW of the printed board!!!
board = [[], [], [], [], []... | clear = lambda: os.system('cls')
import colorama
# This module constructs the intitial, and print the updated board throughout the game.
def print_board(spaces):
| random_line_split |
connect_four.py | # This script implements connect four and highlights winning series,
# series with greater than three consecutive Xs or Os.
# The pick_markers module for the start of the game.
def pick_markers():
'''
Module to assign X or O to the two players. Returns a list with two elements,
where index 0 is pla... |
else:
print('Goodbye!')
break | ConnectFour() | conditional_block |
ctrl_server.py | #!/usr/bin/env python
"""Server that accepts and executes control-type commands on the bot."""
import sys
import os
from inspect import getmembers, ismethod
from simplejson.decoder import JSONDecodeError
import zmq
import signal
# This is required to make imports work
sys.path = [os.getcwd()] + sys.path
import bot.l... | reply = msgs.exit_reply()
# Need to actually send reply here as we're about to exit
self.logger.debug("Sending: {}".format(reply))
self.ctrl_sock.send_json(reply)
self.clean_up()
sys.exit(0)
else:
err_msg = "Unrecognized message... | self.logger.info("Received message to die. Bye!") | random_line_split |
ctrl_server.py | #!/usr/bin/env python
"""Server that accepts and executes control-type commands on the bot."""
import sys
import os
from inspect import getmembers, ismethod
from simplejson.decoder import JSONDecodeError
import zmq
import signal
# This is required to make imports work
sys.path = [os.getcwd()] + sys.path
import bot.l... |
callables[name] = methods
return msgs.list_reply(callables)
def call_method(self, name, method, params):
"""Call a previously registered subsystem method by name. Only
methods tagged with the @api_call decorator can be called.
:param name: Assigned name of the register... | methods.append(member[0]) | conditional_block |
ctrl_server.py | #!/usr/bin/env python
"""Server that accepts and executes control-type commands on the bot."""
import sys
import os
from inspect import getmembers, ismethod
from simplejson.decoder import JSONDecodeError
import zmq
import signal
# This is required to make imports work
sys.path = [os.getcwd()] + sys.path
import bot.l... | (self):
"""Raise a test exception which will be returned to the caller."""
raise Exception("Exception test")
@lib.api_call
def spawn_pub_server(self):
"""Spawn publisher thread."""
if self.pub_server is None:
self.pub_server = pub_server_mod.PubServer(self.systems)
... | exception | identifier_name |
ctrl_server.py | #!/usr/bin/env python
"""Server that accepts and executes control-type commands on the bot."""
import sys
import os
from inspect import getmembers, ismethod
from simplejson.decoder import JSONDecodeError
import zmq
import signal
# This is required to make imports work
sys.path = [os.getcwd()] + sys.path
import bot.l... |
def list_callables(self):
"""Build list of callable methods on each exported subsystem object.
Uses introspection to create a list of callable methods for each
registered subsystem object. Only methods which are flagged using the
@lib.api_call decorator will be included.
... | """Generic message handler. Hands-off based on type of message.
:param msg: Message, received via ZMQ from client, to handle.
:type msg: dict
:returns: An appropriate message reply dict, from lib.messages.
"""
self.logger.debug("Received: {}".format(msg))
try:
... | identifier_body |
synchronizer.rs | // Copyright (c) Facebook, Inc. and its affiliates.
use super::committee::*;
use super::error::*;
use super::messages::*;
use super::types::*;
use bincode::Error;
use crypto::Digest;
use futures::future::{Fuse, FutureExt};
use futures::select;
use futures::stream::futures_unordered::FuturesUnordered;
use futures::strea... | warn!("Exiting DagSynchronizer::start().");
break;
}
}
res = rollback_fut => {
if let Err(e) = res{
error!("rollback_headers returns error: {:?}", e);
}
else{
... | random_line_split | |
synchronizer.rs | // Copyright (c) Facebook, Inc. and its affiliates.
use super::committee::*;
use super::error::*;
use super::messages::*;
use super::types::*;
use bincode::Error;
use crypto::Digest;
use futures::future::{Fuse, FutureExt};
use futures::select;
use futures::stream::futures_unordered::FuturesUnordered;
use futures::strea... | (
mut dag_synchronizer: DagSynchronizer,
digest: Digest,
rollback_stop_round: RoundNumber,
sq: SyncNumber,
) -> Result<Option<Vec<Digest>>, DagError> {
//TODO: issue: should we try the processor first? we need concurrent access to it...
if let Ok(dbvalue) = dag_synchronizer.store.read(digest.to... | handle_header_digest | identifier_name |
synchronizer.rs | // Copyright (c) Facebook, Inc. and its affiliates.
use super::committee::*;
use super::error::*;
use super::messages::*;
use super::types::*;
use bincode::Error;
use crypto::Digest;
use futures::future::{Fuse, FutureExt};
use futures::select;
use futures::stream::futures_unordered::FuturesUnordered;
use futures::strea... |
pub async fn dag_synchronizer_process(
mut get_from_dag: Receiver<SyncMessage>,
dag_synchronizer: DagSynchronizer,
) {
let mut digests_to_sync: Vec<Digest> = Vec::new();
let mut round_to_sync: RoundNumber = 0;
let mut last_synced_round: RoundNumber = 0;
let mut rollback_stop_round: RoundNumber... | {
debug!(
"[DEP] ASK H {:?} D {}",
(header.round, header.author),
header.transactions_digest.len()
);
//Note: we now store different digests for header and certificates to avoid false positive.
for (other_primary_id, digest) in &header.parents {
let digest_in_store =
... | identifier_body |
timeseriesrdd.py | from py4j.java_gateway import java_import
from pyspark import RDD
from pyspark.serializers import FramedSerializer, SpecialLengths, write_int, read_int
from pyspark.sql import DataFrame
from utils import datetime_to_millis
from datetimeindex import DateTimeIndex, irregular
import struct
import numpy as np
import pandas... | Returns a TimeSeriesRDD rebased on top of a new index. Any timestamps that exist in the new
index but not in the existing index will be filled in with NaNs.
Parameters
----------
new_index : DateTimeIndex
"""
return TimeSeriesRDD(None, None, self._jtsrdd... | return TimeSeriesRDD(None, None, self._jtsrdd.returnRates(), self.ctx)
def with_index(self, new_index):
""" | random_line_split |
timeseriesrdd.py | from py4j.java_gateway import java_import
from pyspark import RDD
from pyspark.serializers import FramedSerializer, SpecialLengths, write_int, read_int
from pyspark.sql import DataFrame
from utils import datetime_to_millis
from datetimeindex import DateTimeIndex, irregular
import struct
import numpy as np
import pandas... | (self, method):
"""
Returns a TimeSeriesRDD with missing values imputed using the given method.
Parameters
----------
method : string
"nearest" fills in NaNs with the closest non-NaN value, using the closest previous value
in the case of a tie. "... | fill | identifier_name |
timeseriesrdd.py | from py4j.java_gateway import java_import
from pyspark import RDD
from pyspark.serializers import FramedSerializer, SpecialLengths, write_int, read_int
from pyspark.sql import DataFrame
from utils import datetime_to_millis
from datetimeindex import DateTimeIndex, irregular
import struct
import numpy as np
import pandas... |
stream.seek(0)
return stream.read()
def loads(self, obj):
stream = BytesIO(obj)
key_length = read_int(stream)
key = stream.read(key_length).decode('utf-8')
return (key, _read_vec(stream))
def __repr__(self):
return '_TimeSeriesSerializer'
class _Insta... | stream.write(struct.pack('!d', value)) | conditional_block |
timeseriesrdd.py | from py4j.java_gateway import java_import
from pyspark import RDD
from pyspark.serializers import FramedSerializer, SpecialLengths, write_int, read_int
from pyspark.sql import DataFrame
from utils import datetime_to_millis
from datetimeindex import DateTimeIndex, irregular
import struct
import numpy as np
import pandas... |
def fill(self, method):
"""
Returns a TimeSeriesRDD with missing values imputed using the given method.
Parameters
----------
method : string
"nearest" fills in NaNs with the closest non-NaN value, using the closest previous value
in the cas... | """
Returns a TimeSeriesRDD where each time series is differenced with the given order.
The new RDD will be missing the first n date-times.
Parameters
----------
n : int
The order of differencing to perform.
"""
return TimeSeriesRDD(N... | identifier_body |
CLQ_search_new.py | import numpy as np
import astropy.io.fits as fits
import scipy as sp
import matplotlib.pyplot as plt
import astroML
from matplotlib.ticker import NullFormatter
import pandas as pd
import os
import urllib2
from scipy import stats
from pydl.pydl.pydlutils.spheregroup import *
from astroML.plotting import hist
from mat... | cptxt = open('copyCLQadditionalspectra.txt','w')
for i in range(len(clqC['name'])):
#for i in range(100):
print 'Working on ',i,' source'
xx = np.where((master['plate1'] == clqC['plate1'][i]) &(master['mjd1'] == clqC['mjd1'][i]) & (master['fiber1'] == clqC['fiber1'][i]))[0][0]
xy =n... | specdir = 'CLQsearch_spectra'
linelist = np.genfromtxt('/Users/vzm83/Proposals/linelist_speccy.txt',usecols=(0,1,2),dtype=('|S10',float,'|S5'),names=True)
out = open('CLQsearch_deltamgs_sn1700gt6.txt','w') | random_line_split |
CLQ_search_new.py | import numpy as np
import astropy.io.fits as fits
import scipy as sp
import matplotlib.pyplot as plt
import astroML
from matplotlib.ticker import NullFormatter
import pandas as pd
import os
import urllib2
from scipy import stats
from pydl.pydl.pydlutils.spheregroup import *
from astroML.plotting import hist
from mat... | ():
text_font = {'fontname':'Times New Roman', 'size':'14'}
pp = PdfPages('CLQsearches_plot_spectra_sn1700gt6.pdf')
clqC=np.genfromtxt('Candidate_CLQ_search_DR16c.txt',names=['name','nepoch','ra','dec','zvi','plate1','mjd1','fiber1','plate2','mjd2','fiber2'],dtype=('|S30',int,float,float,float,int,int,int,... | plot_spectra | identifier_name |
CLQ_search_new.py | import numpy as np
import astropy.io.fits as fits
import scipy as sp
import matplotlib.pyplot as plt
import astroML
from matplotlib.ticker import NullFormatter
import pandas as pd
import os
import urllib2
from scipy import stats
from pydl.pydl.pydlutils.spheregroup import *
from astroML.plotting import hist
from mat... |
def download_spectraCLQ(print_cmd=False):
clqC=np.genfromtxt('Candidate_CLQ_search_DR16c.txt',names=['name','nepoch','ra','dec','zvi','plate1','mjd1','fiber1','plate2','mjd2','fiber2'],dtype=('|S30',int,float,float,float,int,int,int,int,int,int))
if print_cmd :
cptxt = open('CLQcopyspectrumfromBOSS_S... | redux= '/uufs/chpc.utah.edu/common/home/sdss/ebosswork/eboss/spectro/redux/v5_13_0/spectra/lite'
data=fits.open('CrossMatch_DR12Q_spAll_v5_13_0.fits')[1].data
uname = np.unique(data['SDSS_NAME'])
count = 0
gcount = 0
out=open('Candidate_CLQ_search_DR16.txt','w')
name = [] ; ra=[] ; dec=[];zvi=[]... | identifier_body |
CLQ_search_new.py | import numpy as np
import astropy.io.fits as fits
import scipy as sp
import matplotlib.pyplot as plt
import astroML
from matplotlib.ticker import NullFormatter
import pandas as pd
import os
import urllib2
from scipy import stats
from pydl.pydl.pydlutils.spheregroup import *
from astroML.plotting import hist
from mat... |
if not print_cmd:
if not ((os.path.isfile(FITS_FILENAME)) | (os.path.isfile(os.path.join(specdir,FITS_FILENAME)))):
download_spectra(plates[j],mjds[j],fibers[j],specdir)
else :
print 'Spectrum already downloaded'
if print... | FITS_FILENAME = 'spec-{0:04d}-{1:05d}-{2:04d}.fits'.format(plates[j],mjds[j],fibers[j]) | conditional_block |
lib.rs | /*!
Generate lexicographically-evenly-spaced strings between two strings
from pre-defined alphabets.
This is a rewrite of [mudderjs](https://github.com/fasiha/mudderjs); thanks
for the original work of the author and their contributors!
## Usage
Add a dependency in your Cargo.toml:
```toml
mudders = "0.0.4"
```
Now... | utputs_more_or_less_match_mudderjs() {
let table = SymbolTable::from_str("abc").unwrap();
let result = table.mudder_one("a", "b").unwrap();
assert_eq!(result, "ac");
let table = SymbolTable::alphabet();
let result = table.mudder("anhui", "azazel", n(3)).unwrap();
assert_e... | SymbolTable::from_str("ab").unwrap();
let result = table.mudder_one("a", "b").unwrap();
assert_eq!(result, "ab");
let table = SymbolTable::from_str("0123456789").unwrap();
let result = table.mudder_one("1", "2").unwrap();
assert_eq!(result, "15");
}
#[test]
fn o | identifier_body |
lib.rs | /*!
Generate lexicographically-evenly-spaced strings between two strings
from pre-defined alphabets.
This is a rewrite of [mudderjs](https://github.com/fasiha/mudderjs); thanks
for the original work of the author and their contributors!
## Usage
Add a dependency in your Cargo.toml:
```toml
mudders = "0.0.4"
```
Now... | // SymbolTable::mudder() returns a Vec containing `amount` Strings.
let result = table.mudder_one("a", "z").unwrap();
// These strings are always lexicographically placed between `start` and `end`.
let one_str = result.as_str();
assert!(one_str > "a");
assert!(one_str < "z");
// You can also define your own symbol tab... | // so you cannot pass in an invalid value.
use std::num::NonZeroUsize;
// You can use the included alphabet table
let table = SymbolTable::alphabet(); | random_line_split |
lib.rs | /*!
Generate lexicographically-evenly-spaced strings between two strings
from pre-defined alphabets.
This is a rewrite of [mudderjs](https://github.com/fasiha/mudderjs); thanks
for the original work of the author and their contributors!
## Usage
Add a dependency in your Cargo.toml:
```toml
mudders = "0.0.4"
```
Now... | Ok(if amount.get() == 1 {
pool.get(pool.len() / 2)
.map(|item| vec![item.clone()])
.ok_or_else(|| FailedToGetMiddle)?
} else {
let step = computed_amount() as f64 / pool.len() as f64;
let mut counter = 0f64;
let mut last_valu... | // We still don't have enough items, so bail
panic!(
"Internal error: Failed to calculate the correct tree depth!
This is a bug. Please report it at: https://github.com/Follpvosten/mudders/issues
and make sure to include the following information:
Symbols in table: {symbols:?}
G... | conditional_block |
lib.rs | /*!
Generate lexicographically-evenly-spaced strings between two strings
from pre-defined alphabets.
This is a rewrite of [mudderjs](https://github.com/fasiha/mudderjs); thanks
for the original work of the author and their contributors!
## Usage
Add a dependency in your Cargo.toml:
```toml
mudders = "0.0.4"
```
Now... | -> Self {
Self::new(&('a' as u8..='z' as u8).collect::<Box<[_]>>()).unwrap()
}
/// Generate `amount` strings that lexicographically sort between `start` and `end`.
/// The algorithm will try to make them as evenly-spaced as possible.
///
/// When both parameters are empty strings, `amount`... | phabet() | identifier_name |
Search.py | # coding: utf-8
# Jeremy Aguillon
# CMSC 471
# Project 1
# Due 2/15/2016
# imports queues for BFS and UCS
from queue import Queue
from queue import PriorityQueue
# imports sys for command line arguments (argv)
import sys
## Constants ##
# Command line arguments
INPUT_FILE = 1
OUTPUT_FILE = 2
START_NODE = 3
END_NOD... | alternate = distance[cur[1]] + pair[1]
# if the distance is shorter it replaces in the algorithm
if alternate < distance[pair[0]]:
distance[pair[0]] = alternate
previous[pair[0]] = cur[1]
# finds if the nodes are in the open queue and... | # list of nodes that are in open that need to be updated
openNodes = []
# Adds each of the neighbors of the node and compares their length
for pair in sorted(nodeDict[cur[1]]):
# distance of current path is saved and compared with distance | random_line_split |
Search.py | # coding: utf-8
# Jeremy Aguillon
# CMSC 471
# Project 1
# Due 2/15/2016
# imports queues for BFS and UCS
from queue import Queue
from queue import PriorityQueue
# imports sys for command line arguments (argv)
import sys
## Constants ##
# Command line arguments
INPUT_FILE = 1
OUTPUT_FILE = 2
START_NODE = 3
END_NOD... | (Filename, start, end):
# flags to validate that nodes exist in the given graph
foundStart = 0
foundEnd = 0
# validation for opening the file
try:
inFile = open(Filename, 'r')
except IOError as e:
print ("I/O error({0}): {1} \"{2}\"".format(e.errno, e.strerror, Filename),)
... | getNodes | identifier_name |
Search.py | # coding: utf-8
# Jeremy Aguillon
# CMSC 471
# Project 1
# Due 2/15/2016
# imports queues for BFS and UCS
from queue import Queue
from queue import PriorityQueue
# imports sys for command line arguments (argv)
import sys
## Constants ##
# Command line arguments
INPUT_FILE = 1
OUTPUT_FILE = 2
START_NODE = 3
END_NOD... |
# writePath() writes the final path it takes to search from start to end to a new file
# Input: outFile - the filename of the file to be written to
# finalPath - a list of the nodes of the path from start to end nodes
# Output: None
def writePath(outFile, finalPath):
outFile = open(outFile, 'w')
if ... | Open = PriorityQueue(10000)
# creates dictionaries to keep track of distance and previous node of each element
distance = {}
previous = {}
# Initializes each node to have infinity length and no previous
for node in nodeDict.keys():
# gives the initial node 0 distance to be chosen first
... | identifier_body |
Search.py | # coding: utf-8
# Jeremy Aguillon
# CMSC 471
# Project 1
# Due 2/15/2016
# imports queues for BFS and UCS
from queue import Queue
from queue import PriorityQueue
# imports sys for command line arguments (argv)
import sys
## Constants ##
# Command line arguments
INPUT_FILE = 1
OUTPUT_FILE = 2
START_NODE = 3
END_NOD... |
# repopulates Open with updated values
for node in newOpen:
Open.put(node)
# end while loop
# returns blank string if no output found
return ""
# writePath() writes the final path it takes to search from start to end to a new file
# Input: outFile - the filename of the fil... | newOpen.append(node) | conditional_block |
session.rs | use crypto::digest::Digest;
use crypto::sha1::Sha1;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use eventual;
use eventual::Future;
use eventual::Async;
use protobuf::{self, Message};
use rand::thread_rng;
use rand::Rng;
use std::io::{Read, Write, Cursor};
use std::result::Result;
use std::sync::{Mutex, RwLock, Arc, ... | pub struct Session(pub Arc<SessionInternal>);
impl Session {
pub fn new(config: Config, cache: Box<Cache + Send + Sync>) -> Session {
let device_id = {
let mut h = Sha1::new();
h.input_str(&config.device_name);
h.result_str()
};
Session(Arc::new(SessionI... | }
#[derive(Clone)] | random_line_split |
session.rs | use crypto::digest::Digest;
use crypto::sha1::Sha1;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use eventual;
use eventual::Future;
use eventual::Async;
use protobuf::{self, Message};
use rand::thread_rng;
use rand::Rng;
use std::io::{Read, Write, Cursor};
use std::result::Result;
use std::sync::{Mutex, RwLock, Arc, ... | {
config: Config,
device_id: String,
data: RwLock<SessionData>,
cache: Box<Cache + Send + Sync>,
mercury: Mutex<MercuryManager>,
metadata: Mutex<MetadataManager>,
stream: Mutex<StreamManager>,
audio_key: Mutex<AudioKeyManager>,
rx_connection: Mutex<Option<CipherConnection>>,
tx... | SessionInternal | identifier_name |
session.rs | use crypto::digest::Digest;
use crypto::sha1::Sha1;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use eventual;
use eventual::Future;
use eventual::Async;
use protobuf::{self, Message};
use rand::thread_rng;
use rand::Rng;
use std::io::{Read, Write, Cursor};
use std::result::Result;
use std::sync::{Mutex, RwLock, Arc, ... |
pub fn cache(&self) -> &Cache {
self.0.cache.as_ref()
}
pub fn config(&self) -> &Config {
&self.0.config
}
pub fn username(&self) -> String {
self.0.data.read().unwrap().canonical_username.clone()
}
pub fn country(&self) -> String {
self.0.data.read().unw... | {
self.0.mercury.lock().unwrap().subscribe(self, uri)
} | identifier_body |
option.rs | //! Enumeration of RS2 sensor options.
//!
//! Not all options apply to every sensor. In order to retrieve the correct options,
//! one must iterate over the `sensor` object for option compatibility.
//!
//! Notice that this option refers to the `sensor`, not the device. However, the device
//! used also matters; senso... |
assert!(
Rs2Option::from_i32(i).is_some(),
"Rs2Option variant for ordinal {} does not exist.",
i,
);
}
}
}
| {
continue;
} | conditional_block |
option.rs | //! Enumeration of RS2 sensor options.
//!
//! Not all options apply to every sensor. In order to retrieve the correct options,
//! one must iterate over the `sensor` object for option compatibility.
//!
//! Notice that this option refers to the `sensor`, not the device. However, the device
//! used also matters; senso... | {
/// The requested option is not supported by this sensor.
#[error("Option not supported on this sensor.")]
OptionNotSupported,
/// The requested option is read-only and cannot be set.
#[error("Option is read only.")]
OptionIsReadOnly,
/// The requested option could not be set. Reason is r... | OptionSetError | identifier_name |
option.rs | //! Enumeration of RS2 sensor options.
//!
//! Not all options apply to every sensor. In order to retrieve the correct options,
//! one must iterate over the `sensor` object for option compatibility.
//!
//! Notice that this option refers to the `sensor`, not the device. However, the device
//! used also matters; senso... | NoiseEstimation = sys::rs2_option_RS2_OPTION_NOISE_ESTIMATION as i32,
/// Enable/disable data collection for calculating IR pixel reflectivity.
EnableIrReflectivity = sys::rs2_option_RS2_OPTION_ENABLE_IR_REFLECTIVITY as i32,
/// Auto exposure limit in microseconds.
///
/// Default is 0 which mea... | /// Enable/disable the maximum usable depth sensor range given the amount of ambient light in the scene.
EnableMaxUsableRange = sys::rs2_option_RS2_OPTION_ENABLE_MAX_USABLE_RANGE as i32,
/// Enable/disable the alternate IR, When enabling alternate IR, the IR image is holding the amplitude of the depth corre... | random_line_split |
option.rs | //! Enumeration of RS2 sensor options.
//!
//! Not all options apply to every sensor. In order to retrieve the correct options,
//! one must iterate over the `sensor` object for option compatibility.
//!
//! Notice that this option refers to the `sensor`, not the device. However, the device
//! used also matters; senso... |
}
| {
let deprecated_options = vec![
sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_X as i32,
sys::rs2_option_RS2_OPTION_ZERO_ORDER_POINT_Y as i32,
sys::rs2_option_RS2_OPTION_ZERO_ORDER_ENABLED as i32,
sys::rs2_option_RS2_OPTION_AMBIENT_LIGHT as i32,
sys::rs2... | identifier_body |
mixture.rs | use itertools::{
Either,
EitherOrBoth::{Both, Left, Right},
Itertools,
};
use std::{
cell::Cell,
sync::atomic::{AtomicU64, Ordering::Relaxed},
};
use tinyvec::TinyVec;
use crate::reaction::ReactionIdentifier;
use super::{
constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI... | reactions
.iter()
.filter_map(|r| r.check_conditions(self).then(|| r.get_id()))
.collect()
})
}
/// Returns a tuple with oxidation power and fuel amount of this gas mixture.
pub fn get_burnability(&self) -> (f32, f32) {
use crate::types::FireInfo;
super::with_gas_info(|gas_info| {
self.moles
... | }
/// Gets all of the reactions this mix should do.
pub fn all_reactable(&self) -> Vec<ReactionIdentifier> {
with_reactions(|reactions| { | random_line_split |
mixture.rs | use itertools::{
Either,
EitherOrBoth::{Both, Left, Right},
Itertools,
};
use std::{
cell::Cell,
sync::atomic::{AtomicU64, Ordering::Relaxed},
};
use tinyvec::TinyVec;
use crate::reaction::ReactionIdentifier;
use super::{
constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI... |
FireInfo::Fuel(fire) => {
if self.temperature > fire.temperature() {
let amount = amt
* (1.0 - fire.temperature() / self.temperature).max(0.0);
acc.1 += amount / fire.burn_rate();
}
}
FireInfo::None => (),
}
}
acc
})
})
}
/// Retu... | {
if self.temperature > oxidation.temperature() {
let amount = amt
* (1.0 - oxidation.temperature() / self.temperature)
.max(0.0);
acc.0 += amount * oxidation.power();
}
} | conditional_block |
mixture.rs | use itertools::{
Either,
EitherOrBoth::{Both, Left, Right},
Itertools,
};
use std::{
cell::Cell,
sync::atomic::{AtomicU64, Ordering::Relaxed},
};
use tinyvec::TinyVec;
use crate::reaction::ReactionIdentifier;
use super::{
constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI... |
/// Merges one gas mixture into another.
pub fn merge(&mut self, giver: &Self) {
if self.immutable {
return;
}
let our_heat_capacity = self.heat_capacity();
let other_heat_capacity = giver.heat_capacity();
self.maybe_expand(giver.moles.len());
for (a, b) in self.moles.iter_mut().zip(giver.moles.iter()... | {
self.heat_capacity() * self.temperature
} | identifier_body |
mixture.rs | use itertools::{
Either,
EitherOrBoth::{Both, Left, Right},
Itertools,
};
use std::{
cell::Cell,
sync::atomic::{AtomicU64, Ordering::Relaxed},
};
use tinyvec::TinyVec;
use crate::reaction::ReactionIdentifier;
use super::{
constants::*, gas_visibility, total_num_gases, with_reactions, with_specific_heats, GasI... | (&mut self, heat: f32) {
let cap = self.heat_capacity();
self.set_temperature(((cap * self.temperature) + heat) / cap);
}
/// Returns true if there's a visible gas in this mix.
pub fn is_visible(&self) -> bool {
self.enumerate()
.any(|(i, gas)| gas_visibility(i as usize).map_or(false, |amt| gas >= amt))
}
... | adjust_heat | identifier_name |
object.rs | //! Represents an object in PHP. Allows for overriding the internal object used
//! by classes, allowing users to store Rust data inside a PHP object.
use std::{convert::TryInto, fmt::Debug, ops::DerefMut};
use crate::{
boxed::{ZBox, ZBoxable},
class::RegisteredClass,
convert::{FromZendObject, FromZval, F... | (zval: &'a Zval) -> Option<Self> {
zval.object()
}
}
impl<'a> FromZvalMut<'a> for &'a mut ZendObject {
const TYPE: DataType = DataType::Object(None);
fn from_zval_mut(zval: &'a mut Zval) -> Option<Self> {
zval.object_mut()
}
}
impl IntoZval for ZBox<ZendObject> {
const TYPE: DataT... | from_zval | identifier_name |
object.rs | //! Represents an object in PHP. Allows for overriding the internal object used
//! by classes, allowing users to store Rust data inside a PHP object.
use std::{convert::TryInto, fmt::Debug, ops::DerefMut};
use crate::{
boxed::{ZBox, ZBoxable},
class::RegisteredClass,
convert::{FromZendObject, FromZval, F... | .as_ref()
}
.ok_or(Error::InvalidScope)?;
T::from_zval(zv).ok_or_else(|| Error::ZvalConversion(zv.get_type()))
}
/// Attempts to set a property on the object.
///
/// # Parameters
///
/// * `name` - The name of the property.
/// * `value` - The value to ... | &mut rv,
) | random_line_split |
object.rs | //! Represents an object in PHP. Allows for overriding the internal object used
//! by classes, allowing users to store Rust data inside a PHP object.
use std::{convert::TryInto, fmt::Debug, ops::DerefMut};
use crate::{
boxed::{ZBox, ZBoxable},
class::RegisteredClass,
convert::{FromZendObject, FromZval, F... |
}
}
impl<T: RegisteredClass> From<ZBox<ZendClassObject<T>>> for ZBox<ZendObject> {
#[inline]
fn from(obj: ZBox<ZendClassObject<T>>) -> Self {
ZendObject::from_class_object(obj)
}
}
/// Different ways to query if a property exists.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(... | {
// TODO: become an error
let class_name = obj.get_class_name();
panic!(
"{}::__toString() must return a string",
class_name.expect("unable to determine class name"),
);
} | conditional_block |
object.rs | //! Represents an object in PHP. Allows for overriding the internal object used
//! by classes, allowing users to store Rust data inside a PHP object.
use std::{convert::TryInto, fmt::Debug, ops::DerefMut};
use crate::{
boxed::{ZBox, ZBoxable},
class::RegisteredClass,
convert::{FromZendObject, FromZval, F... |
}
impl FromZendObject<'_> for String {
fn from_zend_object(obj: &ZendObject) -> Result<Self> {
let mut ret = Zval::new();
unsafe {
zend_call_known_function(
(*obj.ce).__tostring,
obj as *const _ as *mut _,
obj.ce,
&mut ret... | {
zv.set_object(self);
Ok(())
} | identifier_body |
provider.go | package provider
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/hashicorp/go-azure-helpers/authentication"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/... |
resources[key] = resource
}
}
// then handle the untyped services
for _, service := range SupportedUntypedServices() {
debugLog("[DEBUG] Registering Data Sources for %q..", service.Name())
for k, v := range service.SupportedDataSources() {
if existing := dataSources[k]; existing != nil {
panic(fmt.... | {
panic(fmt.Errorf("creating Wrapper for Resource %q: %+v", key, err))
} | conditional_block |
provider.go | package provider
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/hashicorp/go-azure-helpers/authentication"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/... | p.ConfigureContextFunc = providerConfigure(p)
return p
}
func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc {
return func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
var auxTenants []string
if v, ok := d.Get("auxiliary_tenant_ids").([]interface{}); ok && l... | }
| random_line_split |
provider.go | package provider
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/hashicorp/go-azure-helpers/authentication"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/... | () *schema.Provider {
return azureProvider(true)
}
func ValidatePartnerID(i interface{}, k string) ([]string, []error) {
// ValidatePartnerID checks if partner_id is any of the following:
// * a valid UUID - will add "pid-" prefix to the ID if it is not already present
// * a valid UUID prefixed with "pid-"
// ... | TestAzureProvider | identifier_name |
provider.go | package provider
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/hashicorp/go-azure-helpers/authentication"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/... |
func ValidatePartnerID(i interface{}, k string) ([]string, []error) {
// ValidatePartnerID checks if partner_id is any of the following:
// * a valid UUID - will add "pid-" prefix to the ID if it is not already present
// * a valid UUID prefixed with "pid-"
// * a valid UUID prefixed with "pid-" and suffixed w... | {
return azureProvider(true)
} | identifier_body |
feature_extraction.py | import numpy as np
import os
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqIO
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
import uuid
from joblib import Parallel, delayed
import argparse
import matplotlib
matplotlib.use... | (motifs,top_n,label):
out = []
for i in motifs:
for j in range(top_n):
out.append("%s_%s_%s"%(label,i,j))
return out
## get feature table
adjusted_scores = np.array(adjusted_scores)
adjusted_scores = np.swapaxes(adjusted_scores,0,1)
adjusted_scores = adjusted_scores.reshape((len(high+low),top_n*len(m... | set_col_names | identifier_name |
feature_extraction.py | import numpy as np
import os
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqIO
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
import uuid
from joblib import Parallel, delayed
import argparse
import matplotlib
matplotlib.use... | return score_list.argsort()[-top_n:],score_list[score_list.argsort()[-top_n:]]
# 5. for each seq, get top N scores from (4) and their footprint score (given their positions), get adjusted score
def get_adjusted_motif_score(motif_score,footprint_score,n):
"""motif_score and footprint_score are same shape, N * L"... | ------
pos, value list
"""
| random_line_split |
feature_extraction.py | import numpy as np
import os
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqIO
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
import uuid
from joblib import Parallel, delayed
import argparse
import matplotlib
matplotlib.use... |
i = i+1
return myDict
def motif_scan(s,m):
## s, m are numpy array
## s.shape = L*4
## m.shape = 4*W
L = s.shape[0]
W = m.shape[1]
score_list = []
for i in range(L-W):
sub = np.matmul(s[i:i+W,:],m)
# if i < 3:
# print ("DNA seq",s[i:i+W,:])
# print ("motif",m)
# print ("mapping... | myString = "\n".join(map(lambda x:"\t".join(x.strip().split()),lines[i+2:i+2+motifLength])).replace(" "," ")
df = pd.read_csv(StringIO(myString), sep="\t",header=None)
df.columns=['A','C','G','T']
myDict[myList[1]+label] = df
i = i+2+motifLength
if df.shape[0] != motifLength or df.shape[1] !=... | conditional_block |
feature_extraction.py | import numpy as np
import os
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqIO
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
import uuid
from joblib import Parallel, delayed
import argparse
import matplotlib
matplotlib.use... |
## Define parameters
# high_hbf = 50
high_hbf = 0
low_hbf = 0
input = "Editable_A_scores.combined.scores.csv"
flank = 100
refgenome="/home/yli11/Data/Human/hg19/fasta/hg19.fa"
bw_file="/home/yli11/Projects/Li_gRNA/footprint/H1_H2_GM12878_Tn5_bw/Hudep2.bw"
meme_file = "selected_motifs.meme"
top_n=5 # numb... | df = pd.DataFrame(roi)
df[1] = df[1]-flank
df[2] = df[2]+flank
df.to_csv("tmp.bed",sep="\t",header=False,index=False)
os.system("bedtools getfasta -fi %s -fo tmp.fa -bed tmp.bed -s -name"%(genome_fa))
seq = read_fasta("tmp.fa")
os.system("rm tmp.fa tmp.bed")
return seq | identifier_body |
public_key.rs | use crate::key::{KeyError, PublicKey};
use crate::ssh::decode::SshComplexTypeDecode;
use crate::ssh::encode::SshComplexTypeEncode;
use std::str::FromStr;
use std::{io, string};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SshPublicKeyError {
#[error(transparent)]
IoError(#[from] io::Error),
#[er... | pub struct SshPublicKey {
pub inner_key: SshBasePublicKey,
pub comment: String,
}
impl SshPublicKey {
pub fn to_string(&self) -> Result<String, SshPublicKeyError> {
let mut buffer = Vec::with_capacity(1024);
self.encode(&mut buffer)?;
Ok(String::from_utf8(buffer)?)
}
}
impl Fro... | random_line_split | |
public_key.rs | use crate::key::{KeyError, PublicKey};
use crate::ssh::decode::SshComplexTypeDecode;
use crate::ssh::encode::SshComplexTypeEncode;
use std::str::FromStr;
use std::{io, string};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SshPublicKeyError {
#[error(transparent)]
IoError(#[from] io::Error),
#[er... | () {
// ssh-keygen -t rsa -b 2048 -C "test2@picky.com"
let ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDI9ht2g2qOPgSG5huVYjFUouyaw59/6QuQqUVGwgnITlhRbM+bkvJQfcuiqcv+vD9/86Dfugk79sSfg/aVK+V/plqAAZoujz/wALDjEphSxAUcAR+t4i2F39Pa71MSc37I9L30z31tcba1X7od7hzrVMl9iurkOyBC4xcIWa1H8h0mDyoXyWPTqoTONDU... | decode_ssh_rsa_2048_public_key | identifier_name |
public_key.rs | use crate::key::{KeyError, PublicKey};
use crate::ssh::decode::SshComplexTypeDecode;
use crate::ssh::encode::SshComplexTypeEncode;
use std::str::FromStr;
use std::{io, string};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SshPublicKeyError {
#[error(transparent)]
IoError(#[from] io::Error),
#[er... |
#[test]
fn ed25519_roundtrip() {
let public_key = SshPublicKey::from_str(test_files::SSH_PUBLIC_KEY_ED25519).unwrap();
let ssh_public_key_after = public_key.to_string().unwrap();
assert_eq!(test_files::SSH_PUBLIC_KEY_ED25519, ssh_public_key_after.as_str());
}
}
| {
let public_key = SshPublicKey::from_str(key_str).unwrap();
let ssh_public_key_after = public_key.to_string().unwrap();
assert_eq!(key_str, ssh_public_key_after.as_str());
} | identifier_body |
CallCenterHome.js | import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Page, Header, Content } from 'yqcloud-front-boot';
import { message, Button, Table, Modal, Tooltip, Icon } from 'yqcloud-ui';
import C... | () {
return{
dataSource: [],
pagination: {
current: 1,
pageSize: 25,
total: '',
pageSizeOptions: ['25', '50', '100', '200'],
},
visible: false,
submitting: false,
edit: false,
isLoading: true,
Id: '',
nickname: '',
sort: 'is... | getInitState | identifier_name |
CallCenterHome.js | import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Page, Header, Content } from 'yqcloud-front-boot';
import { message, Button, Table, Modal, Tooltip, Icon } from 'yqcloud-ui';
import C... | }
this.queryInfo(pagination, sorter.join(','), filters, params);
}
/**
* 呼叫中心标题
* @returns {*}
*/
renderSideTitle() {
if (this.state.edit) {
return CallCenterStore.languages[`${intlPrefix}.editCallCenter`];
} else {
return CallCenterStore.languages[`${intlPrefix}.createCallCe... | random_line_split | |
CallCenterHome.js | import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Page, Header, Content } from 'yqcloud-front-boot';
import { message, Button, Table, Modal, Tooltip, Icon } from 'yqcloud-ui';
import C... | }
handleAble = (record) => {
const body = {
id: record.id,
enabled: !record.enabled
}
CallCenterStore.handleEdit(body).then((data) => {
if (data.success) {
this.queryInfo();
}
})
}
render() {
const { pagination, visible, dataSource, edit, submitting } =... | } else {
return `${values}`;
}
| conditional_block |
CallCenterHome.js | import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Page, Header, Content } from 'yqcloud-front-boot';
import { message, Button, Table, Modal, Tooltip, Icon } from 'yqcloud-ui';
import C... |
componentWillMount() {
this.fetch(this.props);
}
componentDidMount() {
this.loadLanguage();
this.queryInfo();
}
fetch() {
CallCenterStore.getIsEnabled();
}
loadLanguage=() => {
const { AppState } = this.props;
CallCenterStore.queryLanguage(0, AppState.currentLanguage);
}
... | {
return{
dataSource: [],
pagination: {
current: 1,
pageSize: 25,
total: '',
pageSizeOptions: ['25', '50', '100', '200'],
},
visible: false,
submitting: false,
edit: false,
isLoading: true,
Id: '',
nickname: '',
sort: 'isEna... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.