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 |
|---|---|---|---|---|
transaction.component.ts | Expense: Array<any>;
dataDebtLoan: Array<any>;
// hiện thị phần thêm chi tiết
public adddetail = true;
// KHỞI TẠO CÁC BIẾN VỊ TRÍ
lat: number = 10.812035;
lng: number = 106.7119887
zoom: number = 14;
// DANH SÁCH TẤT CẢ CÁC ĐỊA ĐIỂM
allPlace: any[] = [];
// OBJCET ĐỊA ĐIỂM
... | = (this.Activ | identifier_name | |
MIDRAN.py | .aestheticUtils import *
from modelDefinitions.DRAN import *
from torchvision.utils import save_image
class MIDRAN:
def __init__(self, config):
# Model Configration
self.trainingImagePath = config['trainingImagePath']
#self.trainingImagePath = config['targetPath']
self.ch... | def savingWeights(self, currentStep, duplicate=None):
# Saving weights | random_line_split | |
MIDRAN.py | Beta1 = float(config['adamBeta1'])
self.adamBeta2 = float(config['adamBeta2'])
self.barLen = int(config['barLen'])
# Initiating Training Parameters(for step)
self.currentEpoch = 0
self.startSteps = 0
self.totalSteps = 0
self.adversarialMean = 0
se... | customPrint(Fore.RED + "Loading pretrained weight", textWidth=self.barLen)
previousWeight = loadCheckpoints(self.checkpointPath, self.modelName)
self.net.load_state_dict(previousWeight['stateDictEG'])
self.optimizerEG.load_state_dict(previousWeight['optimizerEG'])
self.scheduleLR = pre... | identifier_body | |
MIDRAN.py | Tools.customDataloader import *
from utilities.inferenceUtils import *
from utilities.aestheticUtils import *
from modelDefinitions.DRAN import *
from torchvision.utils import save_image
class MIDRAN:
def __init__(self, config):
# Model Configration
self.trainingImagePath = config['train... |
datasetReadder = customDatasetReader(
image_list=targetImageList,
imagePath=self.trainingImagePath,
height = self.imageH,
... | targetImageList = targetImageList[:self.dataSamples] | conditional_block |
MIDRAN.py | Tools.customDataloader import *
from utilities.inferenceUtils import *
from utilities.aestheticUtils import *
from modelDefinitions.DRAN import *
from torchvision.utils import save_image
class MIDRAN:
def __init__(self, config):
# Model Configration
self.trainingImagePath = config['train... | (self, testImagesPath = None, outputDir = None, resize = None, validation = None, noiseSet = None, steps = None):
if not validation:
self.modelLoad()
print("\nInferencing on pretrained weights.")
else:
print("Validation about to begin.")
if not noiseSet:
... | modelInference | identifier_name |
validator.go | ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L40
func (c *Client) VerifySubscription(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (InAppPurchaseData, error) {
var iap InAppPurchaseData
dataString, err := c.GetSubscriptionDataString(ctx, purchaseToken, subscriptionID, accountFlag)
... | {
// default values
if maxRows > 1000 || maxRows < 1 {
maxRows = 1000
}
switch endAt {
case 0:
endAt = time.Now().UnixNano() / 1000000
case startAt:
endAt++
}
bodyMap := map[string]string{
"startAt": fmt.Sprintf("%v", startAt),
"endAt": fmt.Sprintf("%v", endAt),
"maxRows": ... | identifier_body | |
validator.go | := x509.ParsePKIXPublicKey(publicKeyByte)
if err != nil {
return err
}
hashed := sha256.Sum256([]byte(data))
signatureByte, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashed[:], signatureByte)
}
// Subscripti... | }
return resp.InappPurchaseData, nil
}
// OrderVerifyResponse JSON response from {rootUrl}/applications/purchases/tokens/verify
type OrderVerifyResponse struct {
ResponseCode string `json:"responseCode"` // Response code, if = "0" means succeed, for others see https://developer.huawei.com/consu... | return "", err
}
if err := c.getResponseErrorByCode(resp.ResponseCode); err != nil {
return "", err | random_line_split |
validator.go | .GetSubscriptionDataString(ctx, purchaseToken, subscriptionID, accountFlag)
if err != nil {
return iap, err
}
if err := json.Unmarshal([]byte(dataString), &iap); err != nil {
return iap, err
}
return iap, nil
}
// GetSubscriptionDataString gets subscriptions response data string.
//
// Document: https://dev... | {
// log.Printf("GetCanceledOrRefundedPurchases(): Encounter error: %s", err)
return
} | conditional_block | |
validator.go | := x509.ParsePKIXPublicKey(publicKeyByte)
if err != nil {
return err
}
hashed := sha256.Sum256([]byte(data))
signatureByte, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashed[:], signatureByte)
}
// Subscripti... | (
// context of request
ctx context.Context,
// start time timestamp in milliseconds, if =0, will default to 1 month ago.
startAt int64,
// end time timestamp in milliseconds, if =0, will default to now | GetCanceledOrRefundedPurchases | identifier_name |
model.rs | /// Keeps track of the next index to assign to a new element of this model.
element_index: i32,
/// Maps *flat* witness terms to elements of this model.
///
/// **Hint**: Flat (witness) terms are terms that do not contain any complex sub-terms
/// that consist of functions applications.
rew... |
if let Some(relation) = self.relations.get(symbol) {
if let Symbol::Equality = symbol {
let to_add = tuples.iter().map(|t| vec![t[1], t[0]]).collect_vec();
tuples.extend(to_add);
};
self.database.insert(relation, tuples).map_err(Error::from)
... | _ => {}
} | random_line_split |
model.rs | /// Keeps track of the next index to assign to a new element of this model.
element_index: i32,
/// Maps *flat* witness terms to elements of this model.
///
/// **Hint**: Flat (witness) terms are terms that do not contain any complex sub-terms
/// that consist of functions applications.
rew... |
// assumes that the witness term is flat
pub(super) fn record(&mut self, witness: BasicWitnessTerm) -> E {
match witness {
BasicWitnessTerm::Elem(e) => e,
_ => self
.rewrites
.get(&witness)
.copied()
.unwrap_or_els... | {
let element = E(self.element_index);
self.element_index += 1;
self.rewrites.insert(witness, element);
element
} | identifier_body |
model.rs | /// Keeps track of the next index to assign to a new element of this model.
element_index: i32,
/// Maps *flat* witness terms to elements of this model.
///
/// **Hint**: Flat (witness) terms are terms that do not contain any complex sub-terms
/// that consist of functions applications.
rew... | (&self, element: &E) -> Vec<BasicWitnessTerm> {
self.rewrites
.iter()
.filter(|(_, e)| *e == element)
.map(|(t, _)| t)
.cloned()
.collect()
}
fn element(&self, witness: &BasicWitnessTerm) -> Option<E> {
match witness {
Basi... | witness | identifier_name |
mod.rs | meta(charset = "UTF-8") {}
script(src="/resources/svg-pan-zoom.js") {}
script(src="/resources/zoom_mir.js") {}
: Raw(refresh_script(pcx))
}
body(onload="enable_mir_mousewheel()") {
link(rel="stylesheet", href="/resources/positionin... | else {
String::new()
}
}
pub fn render_main_window(
pcx: &PrirodaContext<'_, '_>,
display_frame: Option<usize>,
message: String,
) -> Html<String> {
let is_active_stack_frame = match display_frame {
Some(n) => n == Machine::stack(&pcx.ecx).len() - 1,
None => true,
};
... | {
r#"<script>
setInterval(() => {
fetch("/step_count").then((res) => {
if(res.status == 200) {
return res.text();
} else {
throw "";
}
}).then((res) => {
... | conditional_block |
mod.rs | meta(charset = "UTF-8") {}
script(src="/resources/svg-pan-zoom.js") {}
script(src="/resources/zoom_mir.js") {}
: Raw(refresh_script(pcx))
}
body(onload="enable_mir_mousewheel()") {
link(rel="stylesheet", href="/resources/positionin... | div(id="stack") {
table(border="1") {
@ for (i, &(ref s, ref span, ref def_id)) in stack.iter().enumerate().rev() {
tr {
@ if i == display_frame.unwrap_or(stack.len() - 1) { td { : Raw("→") } } ... | }
div(id="right") {
div {
: format!("Step count: {}", pcx.step_count);
} | random_line_split |
mod.rs | (() => {
fetch("/step_count").then((res) => {
if(res.status == 200) {
return res.text();
} else {
throw "";
}
}).then((res) => {
if(res != #step_count#) {
... | e_invalid(fra | identifier_name | |
mod.rs | Html(buf)
}
pub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String {
if pcx.config.auto_refresh {
r#"<script>
setInterval(() => {
fetch("/step_count").then((res) => {
if(res.status == 200) {
return res.text();
... | {
let mut buf = String::new();
(horrorshow::html! {
html {
head {
title { : title }
meta(charset = "UTF-8") {}
script(src="/resources/svg-pan-zoom.js") {}
script(src="/resources/zoom_mir.js") {}
: Raw(refresh_scr... | identifier_body | |
window_manager.rs | Vec<Rc<Window>>,
bottom: Vec<Rc<Window>>,
normal: Vec<Rc<Window>>,
top: Vec<Rc<Window>>,
overlay: Vec<Rc<Window>>,
}
impl WindowLayers {
fn all_windows(&self) -> impl '_ + DoubleEndedIterator<Item = Rc<Window>> {
self
.background
.iter()
.chain(self.bottom.iter())
.chain(self.nor... | // it no longer has focus and the client will repaint accordingly, e.g.
// stop displaying a caret.
let surface = Surface::from_wlr_surface(old_wlr_surface);
surface.set_activated(false);
}
wlr_seat_keyboard_clear_focus(self.seat_manager.raw_seat());
}
}
}
pub(crate) ... | .keyboard_state
.focused_surface;
if !old_wlr_surface.is_null() {
// Deactivate the previously focused window. This lets the client know | random_line_split |
window_manager.rs | <Rc<Window>>,
bottom: Vec<Rc<Window>>,
normal: Vec<Rc<Window>>,
top: Vec<Rc<Window>>,
overlay: Vec<Rc<Window>>,
}
impl WindowLayers {
fn all_windows(&self) -> impl '_ + DoubleEndedIterator<Item = Rc<Window>> {
self
.background
.iter()
.chain(self.bottom.iter())
.chain(self.normal.... | else {
self.layers.borrow_mut().update(layer, |windows| {
windows.push(window.clone());
})
}
window
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::input::{cursor::CursorManager, event_filter::EventFilterManager};
use crate::output_manager::OutputManager;
use crate::window:... | {
self.layers.borrow_mut().update(layer, |windows| {
windows.insert(0, window.clone());
})
} | conditional_block |
window_manager.rs | <Rc<Window>>,
bottom: Vec<Rc<Window>>,
normal: Vec<Rc<Window>>,
top: Vec<Rc<Window>>,
overlay: Vec<Rc<Window>>,
}
impl WindowLayers {
fn all_windows(&self) -> impl '_ + DoubleEndedIterator<Item = Rc<Window>> {
self
.background
.iter()
.chain(self.bottom.iter())
.chain(self.normal.... | (&self) -> impl '_ + Iterator<Item = Rc<Window>> {
self.windows().filter(|window| *window.mapped.borrow())
}
pub fn window_at(&self, point: &Point) -> Option<Rc<Window>> {
self
.layers
.borrow()
.all_windows()
// Reverse as windows is from back to front
.rev()
.find(|win... | windows_to_render | identifier_name |
plugin.go | v, will skip", pod)
} else if !q.podStore.Poll(meta.Name(), queue.POP_EVENT) {
log.V(1).Infof("yield popped a transitioning pod, skipping: %+v", pod)
} else if pod.Status.Host != "" {
// should never happen if enqueuePods is filtering properly
log.Warningf("yield popped an already-scheduled pod, skipping: ... | {
pod := v.(*api.Pod)
newmap[k] = &Pod{Pod: pod}
} | conditional_block | |
plugin.go | binder) bind(ctx api.Context, binding *api.Binding, task *PodTask) (err error) {
// sanity check: ensure that the task hasAcceptedOffer(), it's possible that between
// Schedule() and now that the offer for this task was rescinded or invalidated.
// ((we should never see this here))
if !task.hasAcceptedOffer() {
... | offerId := task.GetOfferId()
if offer, ok := b.api.offers().Get(offerId); !ok || offer.HasExpired() {
// already rescinded or timed out or otherwise invalidated
task.Offer.Release()
task.ClearTaskInfo()
return fmt.Errorf("failed prior to launchTask due to expired offer for task %v", task.ID)
}
if err = b.p... | // By this time, there is a chance that the slave is disconnected. | random_line_split |
plugin.go | ):
q.unscheduledCond.Broadcast() // abort Wait()
<-signalled // wait for the go-routine, and the lock
log.V(4).Infoln("timed out waiting for a pod to yield")
case <-signalled:
// we have acquired the lock, and there
// may be a pod for us to pop now
}
continue
}
pod :... | {
pod := obj.(*api.Pod)
psa.FIFO.Add(id, &Pod{Pod: pod})
} | identifier_body | |
plugin.go | Wait()
<-signalled // wait for the go-routine, and the lock
log.V(4).Infoln("timed out waiting for a pod to yield")
case <-signalled:
// we have acquired the lock, and there
// may be a pod for us to pop now
}
continue
}
pod := kpod.(*Pod).Pod
if meta, err := meta.Acce... | Update | identifier_name | |
lib.rs | DCODED_NETS: &[HardcodedNet] = &[ALTONA, MEDALLA, SPADINA, PYRMONT, MAINNET, TOLEDO];
pub const DEFAULT_HARDCODED_TESTNET: &str = "medalla";
/// Specifies an Eth2 testnet.
///
/// See the crate-level documentation for more details.
#[derive(Clone, PartialEq, Debug)]
pub struct Eth2TestnetConfig {
pub deposit_contr... | {
// Ensure we can parse the YAML config to a chain spec.
config
.yaml_config
.as_ref()
.unwrap()
.apply_to_chain_spec::<MainnetEthSpec>(&E::default_spec())
.unwrap();
} | conditional_block | |
lib.rs | macro_rules! define_net {
($mod: ident, $include_file: tt) => {{
use eth2_config::$mod::ETH2_NET_DIR;
HardcodedNet {
name: ETH2_NET_DIR.name,
genesis_is_known: ETH2_NET_DIR.genesis_is_known,
yaml_config: $include_file!("../", "config.yaml"),
deploy_bl... | .as_ref()
.ok_or_else(|| "Genesis state is unknown".to_string())?;
BeaconState::from_ssz_bytes(genesis_state_bytes)
.map_err(|e| format!("Genesis state SSZ bytes are invalid: {:?}", e))
}
/// Write the files to the directory.
///
/// Overwrites files if spec... | /// Attempts to deserialize `self.beacon_state`, returning an error if it's missing or invalid.
pub fn beacon_state<E: EthSpec>(&self) -> Result<BeaconState<E>, String> {
let genesis_state_bytes = self
.genesis_state_bytes | random_line_split |
lib.rs | macro_rules! define_net {
($mod: ident, $include_file: tt) => {{
use eth2_config::$mod::ETH2_NET_DIR;
HardcodedNet {
name: ETH2_NET_DIR.name,
genesis_is_known: ETH2_NET_DIR.genesis_is_known,
yaml_config: $include_file!("../", "config.yaml"),
deploy_bl... | (&self, base_dir: PathBuf, overwrite: bool) -> Result<(), String> {
if base_dir.exists() && !overwrite {
return Err("Testnet directory already exists".to_string());
}
self.force_write_to_file(base_dir)
}
/// Write the files to the directory, even if the directory already ex... | write_to_file | identifier_name |
lib.rs | _rules! define_net {
($mod: ident, $include_file: tt) => {{
use eth2_config::$mod::ETH2_NET_DIR;
HardcodedNet {
name: ETH2_NET_DIR.name,
genesis_is_known: ETH2_NET_DIR.genesis_is_known,
yaml_config: $include_file!("../", "config.yaml"),
deploy_block: ... |
/// Attempts to deserialize `self.beacon_state`, returning an error if it's missing or invalid.
pub fn beacon_state<E: EthSpec>(&self) -> Result<BeaconState<E>, String> {
let genesis_state_bytes = self
.genesis_state_bytes
.as_ref()
.ok_or_else(|| "Genesis state is ... | {
self.genesis_state_bytes.is_some()
} | identifier_body |
input_selection_wb_test.go | t.Fatal("InputSelection failed:", err)
}
// Check we got the expected number of eligible inputs.
if len(eligibles) != expNoEligibleInputs {
t.Fatalf("Wrong number of eligible inputs returned. Got: %d, want: %d.",
len(eligibles), expNoEligibleInputs)
}
// Check that the returned eligibles are reverse sorte... |
// Check that all credits are unique
checkUniqueness(t, eligibles)
}
func TestNextAddrWithVaryingHighestIndices(t *testing.T) {
tearDown, db, pool := TstCreatePool(t)
defer tearDown()
dbtx, err := db.BeginReadWriteTx()
if err != nil {
t.Fatal(err)
}
defer dbtx.Commit()
ns, addrmgrNs := TstRWNamespaces(db... | {
t.Fatal("Eligible inputs are not sorted.")
} | conditional_block |
input_selection_wb_test.go | t.Fatal("InputSelection failed:", err)
}
// Check we got the expected number of eligible inputs.
if len(eligibles) != expNoEligibleInputs {
t.Fatalf("Wrong number of eligible inputs returned. Got: %d, want: %d.",
len(eligibles), expNoEligibleInputs)
}
// Check that the returned eligibles are reverse sorte... | }
defer dbtx.Commit()
ns, addrmgrNs := TstRWNamespaces(dbtx)
series := []TstSeriesDef{
{ReqSigs: 2, PubKeys: TstPubKeys[1:4], SeriesID: 1},
}
TstCreateSeries(t, dbtx, pool, series)
stopSeriesID := uint32(2)
// Populate the used addr DB for branch 0 and indices ranging from 0 to 2.
TstEnsureUsedAddr(t, dbtx... |
dbtx, err := db.BeginReadWriteTx()
if err != nil {
t.Fatal(err) | random_line_split |
input_selection_wb_test.go | locked(t, pool.Manager(), addrmgrNs, func() {
addr, err = nextAddr(pool, ns, addrmgrNs, addr.seriesID, addr.branch, addr.index, stopSeriesID)
})
if err != nil {
t.Fatalf("Failed to get next address: %v", err)
}
checkWithdrawalAddressMatches(t, addr, 2, Branch(i), 0)
}
// Finally check that nextAddr() r... | {
if addr.SeriesID() != seriesID {
t.Fatalf("Wrong seriesID; got %d, want %d", addr.SeriesID(), seriesID)
}
if addr.Branch() != branch {
t.Fatalf("Wrong branch; got %d, want %d", addr.Branch(), branch)
}
if addr.Index() != index {
t.Fatalf("Wrong index; got %d, want %d", addr.Index(), index)
}
} | identifier_body | |
input_selection_wb_test.go | stRunWithManagerUnlocked(t, pool.Manager(), addrmgrNs, func() {
addr, err = nextAddr(pool, ns, addrmgrNs, addr.seriesID, addr.branch, addr.index, stopSeriesID)
})
if err != nil {
t.Fatalf("Failed to get next address: %v", err)
}
checkWithdrawalAddressMatches(t, addr, 1, Branch(i), lastIdx-1)
}
// The l... | checkUniqueness | identifier_name | |
showcase_custom_layout.js | 15,
minPageWidth: 270
}
var LayoutShowcaseState = {
columns: ColumnsNumber.Three,
layoutVisuals: null,
layoutReport: null,
layoutPageName: null
}
// Embed the report and retrieve all report visuals
function embedCustomLayoutReport() {
// Load custom layout report properties into session
... |
// Render all visuals with current configuration
function renderVisuals() {
// render only if report and visuals initialized
if (!LayoutShowcaseState.layoutReport || !LayoutShowcaseState.layoutVisuals)
return;
// Get models. models contains enums that can be used
const models = window['power... | {
// Remove all visuals without titles (i.e cards)
LayoutShowcaseState.layoutVisuals = reportVisuals.filter(function (visual) {
return visual.title !== undefined;
});
// Clear visuals list div
$('#visualsList').empty();
// Build checkbox html list and insert the html code to visualsLi... | identifier_body |
showcase_custom_layout.js | = {
columns: ColumnsNumber.Three,
layoutVisuals: null,
layoutReport: null,
layoutPageName: null
}
// Embed the report and retrieve all report visuals
function embedCustomLayoutReport() {
// Load custom layout report properties into session
LoadLayoutShowcaseReportIntoSession().then(function (... | function setColumnButtonActive(num) {
const active_btn_class = "active-columns-btn";
$('#btnOneCol').removeClass(active_btn_class);
$('#btnTwoCols').removeClass(active_btn_class);
$('#btnThreeCols').removeClass(active_btn_class); | random_line_split | |
showcase_custom_layout.js | 15,
minPageWidth: 270
}
var LayoutShowcaseState = {
columns: ColumnsNumber.Three,
layoutVisuals: null,
layoutReport: null,
layoutPageName: null
}
// Embed the report and retrieve all report visuals
function embedCustomLayoutReport() {
// Load custom layout report properties into session
... |
// Set visuals height according to width - 9:16 ratio
const height = width * (9 / 16);
// Visuals starting point
let x = LayoutShowcaseConsts.margin, y = LayoutShowcaseConsts.margin;
// Filter the visuals list to display only the checked visuals
let checkedVisuals = LayoutShowcaseState.layou... | {
pageWidth = width + 2 * LayoutShowcaseConsts.margin;
// Check if page width is smaller than minimum width and update accordingly
if (pageWidth < LayoutShowcaseConsts.minPageWidth) {
pageWidth = LayoutShowcaseConsts.minPageWidth;
// Visuals width is set to fit minimum ... | conditional_block |
showcase_custom_layout.js | 15,
minPageWidth: 270
}
var LayoutShowcaseState = {
columns: ColumnsNumber.Three,
layoutVisuals: null,
layoutReport: null,
layoutPageName: null
}
// Embed the report and retrieve all report visuals
function embedCustomLayoutReport() {
// Load custom layout report properties into session
... | (num) {
const active_btn_class = "active-columns-btn";
$('#btnOneCol').removeClass(active_btn_class);
| setColumnButtonActive | identifier_name |
driver_ceph.go | out, err := shared.RunCommand("rbd", "--version")
if err != nil {
return err
}
out = strings.TrimSpace(out)
fields := strings.Split(out, " ")
if strings.HasPrefix(out, "ceph version ") && len(fields) > 2 {
cephVersion = fields[2]
} else {
cephVersion = out
}
}
cephLoaded = true
return nil... |
// Validate.
_, err = units.ParseByteSizeString(d.config["ceph.osd.pg_num"])
if err != nil {
return err
}
// Quick check.
if d.config["source"] != "" && d.config["ceph.osd.pool_name"] != "" && d.config["source"] != d.config["ceph.osd.pool_name"] {
return fmt.Errorf(`The "source" and "ceph.osd.pool_name" pr... | {
return err
} | conditional_block |
driver_ceph.go | {
out, err := shared.RunCommand("rbd", "--version")
if err != nil {
return err
}
out = strings.TrimSpace(out)
fields := strings.Split(out, " ")
if strings.HasPrefix(out, "ceph version ") && len(fields) > 2 {
cephVersion = fields[2]
} else {
cephVersion = out
}
}
cephLoaded = true
return ... | () Info {
return Info{
Name: "ceph",
Version: cephVersion,
OptimizedImages: true,
PreservesInodes: false,
Remote: d.isRemote(),
VolumeTypes: []VolumeType{VolumeTypeCustom, VolumeTypeImage, VolumeTypeContainer, VolumeTypeVM},
BlockBacking: true,
RunningCo... | Info | identifier_name |
driver_ceph.go | }
// load is used to run one-time action per-driver rather than per-pool.
func (d *ceph) load() error {
// Register the patches.
d.patches = map[string]func() error{
"storage_lvm_skipactivation": nil,
"storage_missing_snapshot_records": nil,
"storage_delete_old_snapsho... | random_line_split | ||
driver_ceph.go | {
out, err := shared.RunCommand("rbd", "--version")
if err != nil {
return err
}
out = strings.TrimSpace(out)
fields := strings.Split(out, " ")
if strings.HasPrefix(out, "ceph version ") && len(fields) > 2 {
cephVersion = fields[2]
} else {
cephVersion = out
}
}
cephLoaded = true
return ... | return nil
}
// On delete, wipe everything in the directory.
err := wipeDirectory(GetPoolMountPath(d.name))
if err != nil {
return err
}
return nil
}
// Validate checks that all provide keys are supported and that no conflicting or missing configuration is present.
func (d *ceph) Validate(config map[strin... | {
// Test if the pool exists.
poolExists := d.osdPoolExists()
if !poolExists {
d.logger.Warn("Pool does not exist", logger.Ctx{"pool": d.config["ceph.osd.pool_name"], "cluster": d.config["ceph.cluster_name"]})
}
// Check whether we own the pool and only remove in this case.
if shared.IsTrue(d.config["volatile.... | identifier_body |
getinfo.go | for _, item := range searchQuery.LawNumber {
if len(params) > 0 {
params += "&"
}
switch item {
case "44-fz":
params += "fz44=on"
case "223-fz":
params += "fz223=on"
case "pp_rf_615":
params += "ppRf615=on"
case "94-fz":
params += "fz94=on"
}
}
for _, item := range searchQuery.Proced... | (searchQuery SearchQuery) (SearchResult, error) {
var result SearchResult
var err error
searchUrl := "http://zakupki.gov.ru/epz/order/quicksearch/search.html?" + m.SearchQueryToParams(searchQuery)
page, err := http.Get(searchUrl)
if err != nil {
return SearchResult{}, err
}
defer page.Body.Close()
if page... | Search | identifier_name |
getinfo.go | for _, item := range searchQuery.ProcedureStatus {
if len(params) > 0 {
params += "&"
}
switch item {
case "applicationSubmission":
params += "af=on"
case "commissionWork":
params += "ca=on"
case "procedureCompleted":
params += "pc=on"
case "procedureAborted":
params += "pa=on"
}
}
i... | {
params := ""
for _, item := range searchQuery.LawNumber {
if len(params) > 0 {
params += "&"
}
switch item {
case "44-fz":
params += "fz44=on"
case "223-fz":
params += "fz223=on"
case "pp_rf_615":
params += "ppRf615=on"
case "94-fz":
params += "fz94=on"
}
}
| identifier_body | |
getinfo.go | for _, item := range searchQuery.LawNumber {
if len(params) > 0 {
params += "&"
}
switch item {
case "44-fz":
params += "fz44=on"
case "223-fz":
params += "fz223=on"
case "pp_rf_615":
params += "ppRf615=on"
case "94-fz":
params += "fz94=on"
}
}
for _, item := range searchQuery.Proced... | else {
totalString := strings.TrimSpace(totalNode.Text())
totalNumber, err = strconv.ParseInt(strings.ReplaceAll(totalString, " ", ""), 10, 64) // there is a no-break space
if err != nil {
return SearchResult{}, fmt.Errorf("Error on getting approximate total records number: %s\n", err.Error())
}
... | {
totalString := strings.Split(totalComment.Data, ": ")[1]
totalNumber, err = strconv.ParseInt(strings.ReplaceAll(totalString, "\u00a0", ""), 10, 64) // there is a no-break space
if err != nil {
return SearchResult{}, fmt.Errorf("Error on getting exact total records number: %s\n", err.Error())
}
} | conditional_block |
getinfo.go | "strconv"
"net/http"
"net/url"
"github.com/PuerkitoBio/goquery"
)
type GetInfo struct {}
type SearchResult struct {
Items []SearchItem
Total int64
Page int64
TotalPage int64
}
type SearchItem struct {
Name string
Link string
Ids []string
Type string
Status ... | "fmt"
"log"
"time"
"strings" | random_line_split | |
daemon.go | .MkdirAll(daemonStateDirectory, 0700)
if err != nil {
log.Fatalf("Could not create state directory: %s", daemonStateDirectory)
}
var store storage.Storage
{
switch config.Storage.Type {
case "native":
store, err = storage.NewNativeStorage(daemonStateDirectory)
case "memory":
store, err = st... |
current := []decider.LogDecider{}
for _, deciderConfig := range deciderConfigs {
switch deciderConfig.Engine {
case "javascript":
decider, err := decider.NewJSDecider(deciderConfig.JS.Function)
if err != nil {
return err
}
current = append(current, decider)
case "p... | conditional_block | |
daemon.go | remote := remote
go func() {
pc, err := clientPool.Dial(remote)
if err != nil {
log.WithFields(log.Fields{
"remote": remote,
}).Error("Couldn't dial remote")
return
}
pc.Activate()
}()
}
rootBucket := &storage.Bucket{}
caValueBucket := rootBucket.Cd(constants.CaValueB... |
homeDir, _ := os.UserHomeDir()
defaultStateDir := path.Join(homeDir, ".local/share/trustix")
daemonCmd.Flags().StringVar(&daemonStateDirectory, "state", defaultStateDir, "State directory")
// Default poll every 30 minutes
daemonCmd.Flags().Float64Var(&daemonPollInterval, "interval", 60*30, "Log poll interval in... | identifier_body | |
daemon.go | err := subConf.PublicKey.LogID(pd, logMode)
if err != nil {
log.Fatal(err)
}
signer, err := subConf.PublicKey.Signer()
if err != nil {
log.Fatal(err)
}
log := &api.Log{
LogID: &logID,
Meta: subConf.GetMeta(),
Signer: signer,
Protocol: &pd.ID,
Mode: ... | }
return nil
}, | random_line_split | |
daemon.go | .LogID(pd, logMode)
if err != nil {
log.Fatal(err)
}
signer, err := subConf.PublicKey.Signer()
if err != nil {
log.Fatal(err)
}
log := &api.Log{
LogID: &logID,
Meta: subConf.GetMeta(),
Signer: signer,
Protocol: &pd.ID,
Mode: logMode.Enum(),
}... | nitDaemon( | identifier_name | |
fetch_fnz_mf.py | Results'] # from a list of dictionary
else:
return []
def insert_mutual_funds(isin_map):
logger.info('Inserting into mutual fund database')
conn = get_fund_db_conn()
cursor = conn.cursor()
fund_name_sql = "REPLACE INTO mstar_fund_name(mstar_id, name, name_cn) values(%s, %s, %s)... | logger.info('Inserting into fund_branding')
conn = get_fund_db_conn()
cursor = conn.cursor()
fund_branding_sql = "INSERT INTO fund_branding values(%s, '', '') ON DUPLICATE KEY UPDATE name = %s"
fund_branding_stmt = []
for branding in brandings:
fund_branding_stmt.append((branding, ... | identifier_body | |
fetch_fnz_mf.py | , ' \
' f.CategoryCode, f.BroadCategoryGroupID ' \
'from hkfundbasicinfo f ' \
' LEFT JOIN hkfundchineseinvestmentstrategy st on f.mstarId = st.mstarId, ' \
' hkfundchinesenamemapping fcm, hkfundtraditionalchinese ftc ' \
'wh... | two_y = '' if two_y is None else "{0:.5f}".format(two_y)
three_y = '' if three_y is None else "{0:.5f}".format(three_y)
five_y = '' if five_y is None else "{0:.5f}".format(five_y)
fund_name_stmt.append((mStarId, name, name_cn))
mutual_fund_stmt.append((name, product_id, isi... | ytd = '' if ytd is None else "{0:.5f}".format(ytd)
three_m = '' if three_m is None else "{0:.5f}".format(three_m)
one_y = '' if one_y is None else "{0:.5f}".format(one_y)
| random_line_split |
fetch_fnz_mf.py | , ' \
' f.CategoryCode, f.BroadCategoryGroupID ' \
'from hkfundbasicinfo f ' \
' LEFT JOIN hkfundchineseinvestmentstrategy st on f.mstarId = st.mstarId, ' \
' hkfundchinesenamemapping fcm, hkfundtraditionalchinese ftc ' \
'wh... | (isin_map):
logger.info('Inserting into mutual fund database')
conn = get_fund_db_conn()
cursor = conn.cursor()
fund_name_sql = "REPLACE INTO mstar_fund_name(mstar_id, name, name_cn) values(%s, %s, %s)"
mf_sql = "REPLACE INTO mutual_fund (name, product_id, isin, fnz_code, currency, inception_... | insert_mutual_funds | identifier_name |
fetch_fnz_mf.py | , ' \
' f.CategoryCode, f.BroadCategoryGroupID ' \
'from hkfundbasicinfo f ' \
' LEFT JOIN hkfundchineseinvestmentstrategy st on f.mstarId = st.mstarId, ' \
' hkfundchinesenamemapping fcm, hkfundtraditionalchinese ftc ' \
'wh... |
else:
return []
def insert_mutual_funds(isin_map):
logger.info('Inserting into mutual fund database')
conn = get_fund_db_conn()
cursor = conn.cursor()
fund_name_sql = "REPLACE INTO mstar_fund_name(mstar_id, name, name_cn) values(%s, %s, %s)"
mf_sql = "REPLACE INTO mutual_fund... | return r['PageOfResults'] # from a list of dictionary
| conditional_block |
bot.py | query_string = "+".join(list(query))
html_content = urlopen("https://www.youtube.com/results?search_query=" + query_string)
return re.search(r"\"\/watch\?v=(\S{11})\"", html_content.read().decode())[1]
## General Commands
@bot.command(name="ping", help="Check the bot latency")
async def ping(ctx: commands.Con... | await message.edit(content="Latency = {}ms".format(round(bot.latency * 1000)))
@bot.command(name="say", help="Make the bot say something")
async def say(ctx: commands.Context, *words: str):
await ctx.send(" ".join(list(words)))
@bot.command(name="quote", help="Get a random quote")
async def quote(ctx: command... | message = await ctx.send("Pinging...")
time.sleep(0.5) | random_line_split |
bot.py | query_string = "+".join(list(query))
html_content = urlopen("https://www.youtube.com/results?search_query=" + query_string)
return re.search(r"\"\/watch\?v=(\S{11})\"", html_content.read().decode())[1]
## General Commands
@bot.command(name="ping", help="Check the bot latency")
async def ping(ctx: commands.Con... |
@commands.command(name="gif", help="Get a random GIF or search one by query")
async def gif(self, ctx: commands.Context, *query):
url_prefix = "https://api.giphy.com/v1/gifs"
if query == ():
url = "{}/random?api_key={}&tag=&rating=r".format(url_prefix, os.environ["giphy_api_key"])
... | response = requests.get("https://meme-api.herokuapp.com/gimme")
json_data = json.loads(response.text)
await ctx.send("{}".format(json_data["url"])) | identifier_body |
bot.py | _string = "+".join(list(query))
html_content = urlopen("https://www.youtube.com/results?search_query=" + query_string)
return re.search(r"\"\/watch\?v=(\S{11})\"", html_content.read().decode())[1]
## General Commands
@bot.command(name="ping", help="Check the bot latency")
async def ping(ctx: commands.Context):... |
@commands.command(name='hello', help='Say hello to the bot')
async def hello(self, ctx: commands.Context, *, member: discord.Member = None):
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(choice(greet_options) + ' {0.... | await channel.send('Welcome {0.mention}.'.format(member)) | conditional_block |
bot.py | _string = "+".join(list(query))
html_content = urlopen("https://www.youtube.com/results?search_query=" + query_string)
return re.search(r"\"\/watch\?v=(\S{11})\"", html_content.read().decode())[1]
## General Commands
@bot.command(name="ping", help="Check the bot latency")
async def ping(ctx: commands.Context):... | (ctx: commands.Context, *words: str):
await ctx.send(" ".join(list(words)))
@bot.command(name="quote", help="Get a random quote")
async def quote(ctx: commands.Context):
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
await ctx.send("\"{}\"\t~ {}".format... | say | identifier_name |
mc-info.js | [321] = "K<sup>+</sup>"; PdgCodes[-321] = "K<sup>-</sup>";
PdgCodes[311] = "K<sup>0</sup>"; PdgCodes[-311] = overbar(PdgCodes[311]);
PdgCodes[310] = "K<sup>0</sup><sub>short</sub>"; PdgCodes[-310] = overbar(PdgCodes[310]);
PdgCodes[130] = "K<sup>0</sup><sub>long</sub>"; PdgCodes[-130] = ove... | (code)
{
///
/// Transform a PDG code into something printable.
///
var p = PdgCodes[code];
if(p) return p;
// googled from geant4 code, seems consistent with the picture.
// Nuclear codes are given as 10-digit numbers +-10LZZZAAAI.
//For a nucleus consisting of np protons and nn neutrons
// A = np ... | GetParticle | identifier_name |
mc-info.js | [321] = "K<sup>+</sup>"; PdgCodes[-321] = "K<sup>-</sup>";
PdgCodes[311] = "K<sup>0</sup>"; PdgCodes[-311] = overbar(PdgCodes[311]);
PdgCodes[310] = "K<sup>0</sup><sub>short</sub>"; PdgCodes[-310] = overbar(PdgCodes[310]);
PdgCodes[130] = "K<sup>0</sup><sub>long</sub>"; PdgCodes[-130] = ove... | if(I> | {
///
/// Transform a PDG code into something printable.
///
var p = PdgCodes[code];
if(p) return p;
// googled from geant4 code, seems consistent with the picture.
// Nuclear codes are given as 10-digit numbers +-10LZZZAAAI.
//For a nucleus consisting of np protons and nn neutrons
// A = np + nn +n... | identifier_body |
mc-info.js | // Any use of this code must include attribution to Nathaniel Tagg at Otterbein University, but otherwise
// you're free to modify and use it as you like.
//
function overbar(a) { return "<span style='text-decoration: overline'>"+a+"</span>"; }
PdgCodes = [];
PdgCodes[ 1] = "d";
PdgCodes[ 2] = "u";
PdgCodes[ 3] = "s... | // Code for the Arachne Event Display
// Author: Nathaniel Tagg ntagg@otterbein.edu
//
// Licence: this code is free for non-commertial use. Note other licences may apply to 3rd-party code. | random_line_split | |
action.rs | /// Converts value with the interval \[`-1.0`; `1.0`\]
#[must_use]
pub fn ratio(self) -> Option<ValueType> {
self.into()
}
/// Returns a sign (`1` or `-1`) of internal value if value exists and not zero.
///
/// Otherwise returns `0`.
#[must_use]
pub fn analog(self) -> i8 {
self.into()
}
/// Returns a s... | (self) -> Option<i8> {
self.into()
}
/// Return an internal representation of the value if signal exists or None if it doesn't.
#[must_use]
pub const fn value(self) -> Option<SignalType> {
match self {
Self::None => None,
Self::Buy(v) | Self::Sell(v) => Some(v),
}
}
/// Checks if there is no signal
... | sign | identifier_name |
action.rs | /// Converts value with the interval \[`-1.0`; `1.0`\]
#[must_use]
pub fn ratio(self) -> Option<ValueType> {
self.into()
}
/// Returns a sign (`1` or `-1`) of internal value if value exists and not zero.
///
/// Otherwise returns `0`.
#[must_use]
pub fn analog(self) -> i8 {
self.into()
}
/// Returns a s... | Some(v) => v.into(),
}
}
}
impl From<Action> for Option<i8> {
fn from(value: Action) -> Self {
match value {
Action::None => None,
_ => Some(value.into()),
}
}
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
fn from_normalized_f64_to_bounded(value: f64) -> Sig... | impl From<Option<i8>> for Action {
fn from(value: Option<i8>) -> Self {
match value {
None => Self::None, | random_line_split |
action.rs | /// Converts value with the interval \[`-1.0`; `1.0`\]
#[must_use]
pub fn ratio(self) -> Option<ValueType> {
self.into()
}
/// Returns a sign (`1` or `-1`) of internal value if value exists and not zero.
///
/// Otherwise returns `0`.
#[must_use]
pub fn analog(self) -> i8 {
self.into()
}
/// Returns a s... |
}
impl From<Action> for Option<i8> {
fn from(value: Action) -> Self {
match value {
Action::None => None,
_ => Some(value.into()),
}
}
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
fn from_normalized_f64_to_bounded(value: f64) -> SignalType {
debug_assert!((0.0.... | {
match value {
None => Self::None,
Some(v) => v.into(),
}
} | identifier_body |
util.go | ollarise(int(in))
},
"cents_to_dollars_int": func(in int) float64 {
return float64(in) / 100
},
"cents_to_dollars_int64": func(in int64) float64 {
return float64(in) / 100
},
"cents_to_dollars": func(in float32) float32 {
return in / 100
},
"csv": func(in []string) string {
return strings.Jo... | }
return mapping[abbrev]
},
"loggedIn": isLoggedIn,
"userEmail": func(ctx context.Context) string {
return ctx.Value("user").(models.User).Email
},
"user": func(ctx context.Context) models.User {
return ctx.Value("user").(models.User)
},
"orgsFromContext": func(ctx context.Context) models.Org... | "T": "Truncated", | random_line_split |
util.go | map[string]string{
"I": "Created",
"U": "Updated",
"D": "Deleted",
"T": "Truncated",
}
return mapping[abbrev]
},
"loggedIn": isLoggedIn,
"userEmail": func(ctx context.Context) string {
return ctx.Value("user").(models.User).Email
},
"user": func(ctx context.Context) models.User {
... | {
orgs := orgsFromContext(r.Context())
if len(orgs.Data) < 1 {
http.Redirect(w, r, "/create-organisation", http.StatusFound)
return
} else {
query := r.URL.Query()
query.Set("organisationid", orgs.Data[0].ID)
r.URL.RawQuery = query.Encode()
}
http.Redirect(w, r, r.URL.String(), http.StatusFound)
} | identifier_body | |
util.go | return util.NextDay(time.Now(), time.Monday).Format("2006-01-02")
},
"conjoinAnd": func(in []string) string {
return english_conjoin.ConjoinAnd(in)
},
"logoLink": func(ctx context.Context) string {
if !isLoggedIn(ctx) {
return "/"
}
unconv := ctx.Value("url")
if unconv == nil {
return ... | redirToLogin | identifier_name | |
util.go | },
"isOrgSettingsPage": func(ctx context.Context) bool {
currentURL := ctx.Value("url")
if v, ok := currentURL.(*url.URL); ok {
parts := strings.Split(v.Path, "/")
if len(parts) > 1 {
if parts[1] == "organisations" {
return true
}
}
}
return false
},
"selectorSafe": func(i... | {
user.DeleteFlash(ctx, flash)
} | conditional_block | |
docker-build-server.go | // print bob the cat
cat_bytes, err := ioutil.ReadFile("resources/cat.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
cat_str := string(cat_bytes)
banner.Init(os.Stdout, isEnabled, isColorEnabled, bytes.NewBufferString(cat_str))
http.HandleFunc("/", DockerConfluentBu... | {
currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) {
return fmt.Errorf("no permission to read from '%s'", filePath)
}
currentFile.Close()
} | conditional_block | |
docker-build-server.go | "
)
type GithubUrl struct {
GithubDomain string
GithubRepo string
}
func main() {
isEnabled := true
isColorEnabled := true
fmt.Println("Started Confluent Docker Build Server ...")
// print bob ascii
bob_bytes, err := ioutil.ReadFile("resources/bob.txt") // just pass the file name
if... | bob_str := string(bob_bytes)
banner.Init(os.Stdout, isEnabled, isColorEnabled, bytes.NewBufferString(bob_str))
fmt.Println("")
fmt.Println("Confluent Docker Build Server started ... accepting requests")
// print bob the cat
cat_bytes, err := ioutil.ReadFile("resources/cat.txt") // jus... | fmt.Print(err)
} | random_line_split |
docker-build-server.go | "
)
type GithubUrl struct {
GithubDomain string
GithubRepo string
}
func main() {
isEnabled := true
isColorEnabled := true
fmt.Println("Started Confluent Docker Build Server ...")
// print bob ascii
bob_bytes, err := ioutil.ReadFile("resources/bob.txt") // just pass the file name
if... |
statsd, err := statsd.New("127.0.0.1:8125")
if err != nil {
log.Fatal(err)
}
clone_n_dockerbuild(url_param, statsd)
}
func clone_n_dockerbuild(git_url string, statsd *statsd.Client) (types.ImageBuildResponse) {
domain_name := "bob.run"
git_parts := strings.SplitN(gi... | {
url_param := r.URL.Path[1:]
if !strings.Contains(url_param, "github.com") {
fmt.Println("Invalid Github Repo!")
return
}
fmt.Println("Lightning fast docker build for ", url_param)
// v2/github.com/mohnishbasha/hello-world/manifests/latest
if strings.Contains(url_par... | identifier_body |
docker-build-server.go | "
)
type GithubUrl struct {
GithubDomain string
GithubRepo string
}
func main() {
isEnabled := true
isColorEnabled := true
fmt.Println("Started Confluent Docker Build Server ...")
// print bob ascii
bob_bytes, err := ioutil.ReadFile("resources/bob.txt") // just pass the file name
if... | (srcPath string, excludes []string) error {
return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error {
// skip this directory/file if it's not in the path, it won't get added to the context
if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {
retur... | validateDockerContextDirectory | identifier_name |
input_without_IP_group1min.py | %s",
"15%s",
"16%s",
"17%s",
"18%s",
"19%s",
"20%s",
"21%s",
"22%s",
"23%s",
"24%s",
"25%s",
"26%s",
"27%s",
"28%s",
"29%s",
"30%s",
"31%s",
"32%s",
"33%s",
"34%s",
"35%s",
"36%s",
"37%s",
"38%s",
"39%s",
"40%s",
... | if math.fabs(cal_time(link[-1]['time'])-cal_time(list_link2[i]['time'])) > 1800:
list_link2[i]["IP"] = list_link2[i]["IP"]+"_"+str(i)
link.append(list_link2[i])
else :
link.append(list_link2[i])
else :
... | list_new_IP = []
list_link2 = sorted(list_data, key=lambda x:(x['IP'],x['time'],x['domain']))
link = [list_link2[0]]
for i in range(len(list_link2)) :
if '_' in link[-1]['IP'] :
IP = link[-1]['IP'].split("_")[0]
print(IP)
if IP == list_link2[i]['IP']:
... | identifier_body |
input_without_IP_group1min.py | %s",
"15%s",
"16%s",
"17%s",
"18%s",
"19%s",
"20%s",
"21%s",
"22%s",
"23%s",
"24%s",
"25%s",
"26%s",
"27%s",
"28%s",
"29%s",
"30%s",
"31%s",
"32%s",
"33%s",
"34%s",
"35%s",
"36%s",
"37%s",
"38%s",
"39%s",
"40%s",
... | for line in file:
line_split = line.split(" ")
row_data = {}
row_data['Request'] = line_split[15]
time = file_name%(folder%(minute%(sub)))
time_after = time... | #print(PATH_WEB_LOG_FILE%folder%file_name%folder%minute%sub)
with open (PATH_WEB_LOG_FILE%(folder%(file_name%(folder%(minute%(sub))))),'r',encoding='utf-8', errors='ignore') as file: | random_line_split |
input_without_IP_group1min.py | %s",
"15%s",
"16%s",
"17%s",
"18%s",
"19%s",
"20%s",
"21%s",
"22%s",
"23%s",
"24%s",
"25%s",
"26%s",
"27%s",
"28%s",
"29%s",
"30%s",
"31%s",
"32%s",
"33%s",
"34%s",
"35%s",
"36%s",
"37%s",
"38%s",
"39%s",
"40%s",
... | (list_data):
list_IP = []
list_sequence = {}
list_link2 = sorted(list_data, key=lambda x:(x['IP'],x['time'],x['domain']))
list_link = sorted(list_data, key=lambda x:(x['IP'],x['domain'],x['time']))
print(list_link)
link = [list_link[0]]
for i in range(1,len(list_link)):
if link[-1]['... | sequence_gather | identifier_name |
input_without_IP_group1min.py | %s",
"15%s",
"16%s",
"17%s",
"18%s",
"19%s",
"20%s",
"21%s",
"22%s",
"23%s",
"24%s",
"25%s",
"26%s",
"27%s",
"28%s",
"29%s",
"30%s",
"31%s",
"32%s",
"33%s",
"34%s",
"35%s",
"36%s",
"37%s",
"38%s",
"39%s",
"40%s",
... |
#print(list_data)
group_domain(list_data)
def get_domainname(domainname):
if 'http://' not in domainname and 'https://' not in domainname and 'ftp://' not in domainname:
domainname = 'http://' + domainname
subdomain,domain,suf = tldextract.extract(domainname)
if domain in 'edgesuite' :
... | with open (PATH_WEB_LOG_FILE%(folder%(file_name%(folder%(minute%(sub))))),'r',encoding='utf-8', errors='ignore') as file:
for line in file:
line_split = line.split(" ")
row_data = {}
row_data['Request'] = line... | conditional_block |
ObsLightGitManager.py | packages.
'''
def __init__(self, projectChroot):
ObsLightObject.__init__(self)
self.__chroot = projectChroot
self.__mySubprocessCrt = SubprocessCrt()
self.initialTag = "initial-prep"
def __subprocess(self, command=None, stdout=False, noOutPut=False):
return self.__... | (self, path, package):
pkgCurGitDir = package.getCurrentGitDirectory()
res = self.__listSubprocess([self.prepareGitCommand(path, "checkout %s" % self.initialTag , pkgCurGitDir)])
return res
def initGitignore(self, path, package):
absPath = self.__chroot.getDirectory() + path
... | resetToPrep | identifier_name |
ObsLightGitManager.py | packages.
'''
def __init__(self, projectChroot):
ObsLightObject.__init__(self)
self.__chroot = projectChroot
self.__mySubprocessCrt = SubprocessCrt()
self.initialTag = "initial-prep"
def __subprocess(self, command=None, stdout=False, noOutPut=False):
return self.__... |
def prepareGitCommand(self, workTree, subcommand, gitDir):
"""
Construct a Git command-line, setting its working tree to `workTree`,
and git directory to `gitDir`, and then appends `subcommand`.
Output example:
git --git-dir=<gitDir> --work-tree=<workTree> <subcommand>
... | return self.__mySubprocessCrt.execPipeSubprocess(command, command2) | identifier_body |
ObsLightGitManager.py | packages.
'''
def __init__(self, projectChroot):
ObsLightObject.__init__(self)
self.__chroot = projectChroot
self.__mySubprocessCrt = SubprocessCrt()
self.initialTag = "initial-prep"
def __subprocess(self, command=None, stdout=False, noOutPut=False):
return self.__... |
def resetToPrep(self, path, package):
pkgCurGitDir = package.getCurrentGitDirectory()
res = self.__listSubprocess([self.prepareGitCommand(path, "checkout %s" % self.initialTag , pkgCurGitDir)])
return res
def initGitignore(self, path, package):
absPath = self.__chroot.getDire... | msg = "Initialization of the git repository for %s failed. "
msg += "See the log for more information."
raise ObsLightErr.ObsLightChRootError(msg % package.getName()) | conditional_block |
ObsLightGitManager.py | packages.
'''
def __init__(self, projectChroot):
ObsLightObject.__init__(self)
self.__chroot = projectChroot
self.__mySubprocessCrt = SubprocessCrt()
self.initialTag = "initial-prep"
def __subprocess(self, command=None, stdout=False, noOutPut=False):
return self.__... | if not isNonEmptyString(res):
self.logger.debug(" -> Setting it to '%s'" % (value))
cmd2 = self.prepareGitCommand(workTree,
'config %s "%s"' % (param, value),
gitDir)
r... | for param, value in confParams.iteritems():
cmd = self.prepareGitCommand(workTree, "config " + param, gitDir)
res = self.__subprocess(cmd, stdout=True, noOutPut=True)
self.logger.debug("Git parameter '%s': '%s'" % (param, res)) | random_line_split |
mongo.go | : This interface is defined mainly for mock testing
type MongoCollection interface {
InsertOne(ctx context.Context, document interface{},
opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
FindOne(ctx context.Context, filter interface{},
opts ...*options.FindOneOptions) *mongo.SingleResult
FindOn... | filter := bson.M{
"$set": p,
}
return filter, nil
}
func (m *MongoStore) createKeyField(key interface{}) (string, error) {
var n map[string]string
st, err := json.Marshal(key)
if err != nil {
return "", pkgerrors.Errorf("Error Marshalling key: %s", err.Error())
}
err = json.Unmarshal([]byte(st), &n)
if e... | p := make(bson.M, len(n))
for k, v := range n {
p[k] = v
} | random_line_split |
mongo.go | This interface is defined mainly for mock testing
type MongoCollection interface {
InsertOne(ctx context.Context, document interface{},
opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
FindOne(ctx context.Context, filter interface{},
opts ...*options.FindOneOptions) *mongo.SingleResult
FindOne... |
// Unmarshal implements an unmarshaler for bson data that
// is produced from the mongo database
func (m *MongoStore) Unmarshal(inp []byte, out interface{}) error {
err := bson.Unmarshal(inp, out)
if err != nil {
return pkgerrors.Wrap(err, "Unmarshaling bson")
}
return nil
}
func (m *MongoStore) findFilter(key... | {
for _, v := range args {
val, ok := v.(string)
if ok {
if val == "" {
return false
}
} else {
if v == nil {
return false
}
}
}
return true
} | identifier_body |
mongo.go | This interface is defined mainly for mock testing
type MongoCollection interface {
InsertOne(ctx context.Context, document interface{},
opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
FindOne(ctx context.Context, filter interface{},
opts ...*options.FindOneOptions) *mongo.SingleResult
FindOne... | (key Key) (primitive.M, error) {
var bsonMap bson.M
st, err := json.Marshal(key)
if err != nil {
return primitive.M{}, pkgerrors.Errorf("Error Marshalling key: %s", err.Error())
}
err = json.Unmarshal([]byte(st), &bsonMap)
if err != nil {
return primitive.M{}, pkgerrors.Errorf("Error Unmarshalling key to Bso... | findFilter | identifier_name |
mongo.go | This interface is defined mainly for mock testing
type MongoCollection interface {
InsertOne(ctx context.Context, document interface{},
opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)
FindOne(ctx context.Context, filter interface{},
opts ...*options.FindOneOptions) *mongo.SingleResult
FindOne... |
s = s + "}"
return s, nil
}
// Insert is used to insert/add element to a document
func (m *MongoStore) Insert(coll string, key Key, query interface{}, tag string, data interface{}) error {
if data == nil || !m.validateParams(coll, key, tag) {
return pkgerrors.New("No Data to store")
}
c := getCollection(coll,... | {
s = s + k + ","
} | conditional_block |
conftest.py |
return get_vo()
else:
# Client-only test, only use config with no DB config
from rucio.tests.common import get_long_vo
return get_long_vo()
@pytest.fixture(scope='session')
def second_vo():
from rucio.common.config import config_get_bool
from rucio.core.vo import vo_exists... |
@pytest.fixture(scope='module')
def scope_client():
from rucio.client.scopeclient import ScopeClient
return ScopeClient()
@pytest.fixture(scope='module')
def dirac_client():
from rucio.client.diracclient import DiracClient
return DiracClient()
@pytest.fixture
def rest_client():
from rucio.te... |
return RSEClient() | random_line_split |
conftest.py | return get_vo()
else:
# Client-only test, only use config with no DB config
from rucio.tests.common import get_long_vo
return get_long_vo()
@pytest.fixture(scope='session')
def second_vo():
from rucio.common.config import config_get_bool
from rucio.core.vo import vo_exists,... | (vo):
from rucio.common.types import InternalScope
return InternalScope('test', vo=vo)
@pytest.fixture(scope='module')
def root_account(vo):
from rucio.common.types import InternalAccount
return InternalAccount('root', vo=vo)
@pytest.fixture(scope='module')
def jdoe_account(vo):
from rucio.com... | test_scope | identifier_name |
conftest.py |
@pytest.fixture(scope='function')
def function_scope_prefix(request, class_scope_prefix):
return class_scope_prefix + _del_test_prefix(request.node.originalname) + '-'
@pytest.fixture(scope='session')
def vo():
if environ.get('SUITE', 'remote_dbs') != 'client':
# Server test, we can use short VO vi... | if not request.cls:
return module_scope_prefix
return module_scope_prefix + _del_test_prefix(request.cls.__name__) + '-' | identifier_body | |
conftest.py |
else:
# Client-only test, only use config with no DB config
from rucio.tests.common import get_long_vo
return get_long_vo()
@pytest.fixture(scope='session')
def second_vo():
from rucio.common.config import config_get_bool
from rucio.core.vo import vo_exists, add_vo
multi_vo = ... | from rucio.tests.common_server import get_vo
return get_vo() | conditional_block | |
cmonkeyobj.py | contigs = np.unique( features.contig )
seqs = {}
for contig in contigs:
genome_file = './cache/' + self.species + '_' + contig
seq = ut.readLines( genome_file )[0].strip().upper()
seqs[contig] = seq
return seqs
def get_networks( self, include_oper... | def get_genome_seqs( self ):
features = self.get_features() | random_line_split | |
cmonkeyobj.py | buf = cStringIO.StringIO( gen_table )
gen_table = pd.read_table( buf, sep='\t', header=None )
buf.close()
taxon_id = int(gen_table.ix[ gen_table[0] == 'genome:'+kegg_code ][1].values[0].split(', ')[2].split('; ')[0])
self.taxon_id = taxon_id
return taxon_id
def load_... |
pos = nx.spring_layout(gr, k=0.9, iterations=2000)
## requires installation of graphviz-dev and pygraphviz:
##from networkx import graphviz_layout
##pos = nx.graphviz_layout( gr, prog='neato'
pos2 = { i:k for i,k in pos.items() if i in gr2.nodes() }
nx.draw_networkx_edg... | ops = out_nets[ 'operons' ]
ops = ops.ix[ ops.bOp == True ]
ops = ops[ ['SysName1','SysName2','pOp'] ]
ops.pOp = ops.pOp * 1000.
buf = cStringIO.StringIO() ## round-about way to do it but wtf?
ops.to_csv( buf, sep='\t', header=False, index=False )
... | conditional_block |
cmonkeyobj.py | buf = cStringIO.StringIO( gen_table )
gen_table = pd.read_table( buf, sep='\t', header=None )
buf.close()
taxon_id = int(gen_table.ix[ gen_table[0] == 'genome:'+kegg_code ][1].values[0].split(', ')[2].split('; ')[0])
self.taxon_id = taxon_id
return taxon_id
def load_... |
def get_cluster_info( self, k ):
t1 = self.tables['cluster_stats']
t1 = t1[ t1.cluster == k ]
#t1 = t1.drop( ['iteration', 'cluster'], 1 )
t2 = self.tables['motif_infos']
t2 = t2[ t2.cluster == k ]
#t2 = t2.drop( ['iteration', 'cluster'], 1 )
## Extract it... | rats = self.get_ratios( k, rows, cols, included )
rats = rats.transpose()
if kind == 'box': ## sort by mean of columns
means = rats.mean(1)
tmp = pd.concat( [rats, means], 1 )
cols = tmp.columns.values; cols[-1] = 'MEANS'; tmp.columns = cols
tmp = tmp.sor... | identifier_body |
cmonkeyobj.py | buf = cStringIO.StringIO( gen_table )
gen_table = pd.read_table( buf, sep='\t', header=None )
buf.close()
taxon_id = int(gen_table.ix[ gen_table[0] == 'genome:'+kegg_code ][1].values[0].split(', ')[2].split('; ')[0])
self.taxon_id = taxon_id
return taxon_id
def load_... | ( self, k ):
t1 = self.tables['column_members']
t1 = t1[ t1.iteration == self.iteration ]
t1 = t1[ t1.cluster == k ]
t2 = self.tables['column_names']
t2 = pd.merge( t1, t2, on='order_num' )
return t2.name.values
def get_ratios( self, k=None, rows=None, cols=None, inc... | get_cols | identifier_name |
parse.py | config_dir + str(item) + '/Quagga.conf'
config_file = open(config_filename, 'w')
os.chmod(config_filename, 0o775)
# Populate data structures
community_list_dict[item] = get_community_list(data, item)
as_path_list_dict[item] = get_as_path_list(data, item)
... |
else:
ses = Session(item, ngh, remoteAs, "", ngh_policy[ngh]['exportPolicy'])
if not session_list_dict.get(item):
session_list_dict[item] = []
# session_list_dict[item] = {}
session_list_dict[item].append(ses)
# session_lis... | policy_dict[ngh_policy[ngh]['importPolicy']] = []
ses = Session(item, ngh, remoteAs, ngh_policy[ngh]['importPolicy'], \
ngh_policy[ngh]['exportPolicy']) | conditional_block |
parse.py |
if directory:
create_directory(directory)
config_dir = directory+'/configs/'
create_directory(config_dir)
config_file = None # init config_file; if directory not set, write_config_wrapper no-op
topology_file = "topology.json" if directory else None
for item in data['nodes'... | router_dict = {} | random_line_split | |
parse.py | = config_dir + str(item) + '/Quagga.conf'
config_file = open(config_filename, 'w')
os.chmod(config_filename, 0o775)
# Populate data structures
community_list_dict[item] = get_community_list(data, item)
as_path_list_dict[item] = get_as_path_list(data, item)
... |
def get_as_path_list(data, item):
# ip as-path access-list
as_path_list_dict = {}
if data['nodes'][item].get('asPathAccessLists'):
for as_path_list in data['nodes'][item]['asPathAccessLists']:
as_path_list_name = str(data['nodes'][item]['asPathAccessLists'][as_path_list]['name'])
... | community_list_dict = {}
if data['nodes'][item].get('communityLists'):
for community in data['nodes'][item]['communityLists']:
communityName = str(data['nodes'][item]['communityLists'][community]['name'])
for line in data['nodes'][item]['communityLists'][community]['lines']:
... | identifier_body |
parse.py | config_dir + str(item) + '/Quagga.conf'
config_file = open(config_filename, 'w')
os.chmod(config_filename, 0o775)
# Populate data structures
community_list_dict[item] = get_community_list(data, item)
as_path_list_dict[item] = get_as_path_list(data, item)
... | (data, item, session_list_dict, prefix_to_intf_dict):
policy_dict = {} # maps policies seen in vrfs to list of conjuncts of routingPolicies
ReturnBGP = collections.namedtuple('ReturnBGP', ['localAs', 'router_id', 'bgpProcess', \
'as_to_peer_group_dict', 'ngh_to_as_dict', 'ngh_list', 'prefix_to_intf_... | get_bgp_info | identifier_name |
cli.rs | delta",
about = "A syntax-highlighter for git and diff output",
after_help = "\
Colors
------
All delta color options work the same way. There are two ways to specify a color:
1. RGB hex code
An example of passing an RGB hex code is:
--file-color=\"#0e7c0e\"
2. ANSI color name
There are 8 ANSI col... | {
Box,
Plain,
Underline,
}
// TODO: clean up enum parsing and error handling
#[derive(Debug)]
pub enum Error {
SectionStyleParseError,
}
impl FromStr for SectionStyle {
type Err = Error;
fn from_str(s: &str) -> Result<SectionStyle, Error> {
match s.to_lowercase().as_str() {
... | SectionStyle | identifier_name |
cli.rs | "delta",
about = "A syntax-highlighter for git and diff output",
after_help = "\
Colors
------
All delta color options work the same way. There are two ways to specify a color:
1. RGB hex code
An example of passing an RGB hex code is:
--file-color=\"#0e7c0e\"
2. ANSI color name
There are 8 ANSI c... | /// be combined with --light and --dark to view the background colors for those modes. It can
/// also be used to experiment with different RGB hex codes by combining this option with
/// --minus-color, --minus-emph-color, --plus-color, --plus-emph-color.
#[structopt(long = "show-background-colors")]
... | /// Show the command-line arguments (RGB hex codes) for the background colors that are in
/// effect. The hex codes are displayed with their associated background color. This option can | random_line_split |
HypeClipPath.js | Id+'")';
applyElm.style.clipPath = 'url("#'+uniqueId+'")';
/* reverse lookup */
sourceElm.dataset.clipPathSelector = targetElm.dataset.clipPath;
forceRedraw(applyElm);
break;
}
/* as safari doesn't clip outside the bounds on groups let's remind people in chrome */
appl... | sceneUnload | identifier_name | |
HypeClipPath.js |
}
}
/* defs generator function */
function generateDefs(){
/* create and return defs node */
var defsElm = document.createElementNS(kSvgNS, 'defs');
return defsElm;
}
/* extend Hype */
function extendHype(hypeDocument, element, event) {
/* init document specific lookup for mutation observer */
var... | {
clipPathElm.setAttribute(name, obj.clipPathAttributes[name]);
} | conditional_block | |
HypeClipPath.js | .clipPath);
/* if found apply it */
if (sourceElm) {
hypeDocument.generateClipPathForElement(sourceElm, targetElm);
} else {
//remove
removeClipPath(targetElm);
}
}
}
} else {
//remove
removeClipPath(targetElm);
}
}
/* hypeDocument function calcul... | /* apply update to targets referenced by this source */
var selector = mutation.target.dataset.clipPathSelector;
var targetElms = sceneElm.querySelectorAll ('[data-clip-path="'+selector+'"]');
for (var i=0; i < targetElms.length; i++) {
hypeDocument.applyClipPathToElement(targetElms[i]); /* TO... | var sceneElm = _isHypeIDE? document : hypeDocument.getCurrentSceneElement();
/* clip path attribute was mingled with */
switch (mutation.attributeName) {
case 'style':
if (processingStyleDemandsUpdate(hypeDocument, mutation)){ | random_line_split |
HypeClipPath.js | 100;
originOffsetY = sourceHeight * parseFloat(transformOrigin[1]) / 100;
}
/* queue transforms using unshift as they are counter intuitive applied in reverse in SVG */
var transform = [];
if (sourceScaleX!=1 || sourceScaleY!=1) {
transform.unshift('scale('+sourceScaleX+' '+sourceScaleY+')');
t... | {
/* make sure we have a scene specific storage */
var hypeDocId = hypeDocument.documentId();
/* fetch fresh scene element */
var sceneElm = hypeDocument.getCurrentSceneElement();
if (!_lookup[hypeDocId][sceneElm.id]){
_lookup[hypeDocId][sceneElm.id] = {};
_lookup[hypeDocId][sceneElm.id]['Observer'] = {... | identifier_body | |
process_node.go | }, sdk.Parameter{
Name: "cds.triggered_by.fullname",
Type: sdk.StringParameter,
Value: manual.User.Fullname,
}, sdk.Parameter{
Name: "cds.triggered_by.username",
Type: sdk.StringParameter,
Value: manual.User.Username,
}, sdk.Parameter{
Name: "cds.manual",
Type: sdk.StringParameter,
... | {
return nil, false, sdk.WrapError(err, "unable to update workflow node run build parameters")
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.