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 |
|---|---|---|---|---|
scaledobject_controller.go | package controllers
import (
"context"
"fmt"
"sync"
"github.com/go-logr/logr"
autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/... |
// ensureScaledObjectLabel ensures that scaledObjectName=<scaledObject.Name> label exist in the ScaledObject
// This is how the MetricsAdapter will know which ScaledObject a metric is for when the HPA queries it.
func (r *ScaledObjectReconciler) ensureScaledObjectLabel(logger logr.Logger, scaledObject *kedav1alpha1.S... | {
// Check scale target Name is specified
if scaledObject.Spec.ScaleTargetRef.Name == "" {
err := fmt.Errorf("ScaledObject.spec.scaleTargetRef.name is missing")
return "ScaledObject doesn't have correct scaleTargetRef specification", err
}
// Check the label needed for Metrics servers is present on ScaledObjec... | identifier_body |
scaledobject_controller.go | package controllers
import (
"context"
"fmt"
"sync"
"github.com/go-logr/logr"
autoscalingv2beta2 "k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/... | (logger logr.Logger, scaledObject *kedav1alpha1.ScaledObject) (bool, error) {
key, err := cache.MetaNamespaceKeyFunc(scaledObject)
if err != nil {
logger.Error(err, "Error getting key for scaledObject")
return true, err
}
value, loaded := r.scaledObjectsGenerations.Load(key)
if loaded {
generation := value.... | scaledObjectGenerationChanged | identifier_name |
create_secret.go | /*
Copyright 2015 The Kubernetes 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 writing, ... |
// CreateSecretGeneric is the implementation of the create secret generic command
func CreateSecretGeneric(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch ge... | {
cmd := &cobra.Command{
Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]",
Short: i18n.T("Create a secret from a local file, directory or literal value"),
Long: secretLong,
Example: secretExample,
Run: func(cmd *cobra.Command, args []string) {
... | identifier_body |
create_secret.go | /*
Copyright 2015 The Kubernetes 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 writing, ... |
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.SecretForTLSV1GeneratorName:
generator = &kubectl.SecretForTLSGeneratorV1{
Name: name,
Key: cmdutil.GetFlagString(cmd, "key"),
Cert: cmdutil.GetFlagString(cmd, "cert"),... | {
if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
}
} | conditional_block |
create_secret.go | /*
Copyright 2015 The Kubernetes 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 writing, ... | Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]",
Short: i18n.T("Create a secret from a local file, directory or literal value"),
Long: secretLong,
Example: secretExample,
Run: func(cmd *cobra.Command, args []string) {
err := CreateSecretGener... | )
// NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values
func NewCmdCreateSecretGeneric(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{ | random_line_split |
create_secret.go | /*
Copyright 2015 The Kubernetes 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 writing, ... | (f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.SecretV1GeneratorName:... | CreateSecretGeneric | identifier_name |
utils.js | "use strict";
// TODO/FIXME: Load the bundled functions in this file from Alhadis/Utils
const {resolve, dirname, sep, isAbsolute, normalize} = require("path");
const {defineAssertions, defineAssertion, flattenList, formatList} = require("chinotto");
const {deindent} =
module.exports = {
/**
* Non-Atom related he... | flags){
src = (src || "").toString();
if(!src) return null;
const matchEnd = src.match(/\/([gimuy]*)$/);
// Input is a "complete" regular expression
if(matchEnd && /^\//.test(src))
return new RegExp(
src.replace(/^\/|\/([gimuy]*)$/gi, ""),
flags != null ? flags : matchEnd[1]
);
return... | romString(src, | identifier_name |
utils.js | "use strict";
// TODO/FIXME: Load the bundled functions in this file from Alhadis/Utils
const {resolve, dirname, sep, isAbsolute, normalize} = require("path");
const {defineAssertions, defineAssertion, flattenList, formatList} = require("chinotto");
const {deindent} =
module.exports = {
/**
* Non-Atom related he... | /**
* Return the width of the scrollbars being displayed by this user's OS/device.
*
* @return {Number}
*/
getScrollbarWidth(){
const el = document.createElement("div");
const {style} = el;
const size = 120;
style.width =
style.height = size+"px";
style.overflow = "auto";
el.inne... | nst POSIX = paths[0].indexOf("/") !== -1;
let matched = [];
// Spare ourselves the trouble if there's only one path
if(1 === paths.length){
matched = (paths[0].replace(/[\\/]+$/, "")).split(/[\\/]/g);
matched.pop();
}
// Otherwise, comb each array
else{
const rows = paths.map(d => d.split(/... | identifier_body |
utils.js | "use strict";
// TODO/FIXME: Load the bundled functions in this file from Alhadis/Utils
const {resolve, dirname, sep, isAbsolute, normalize} = require("path");
const {defineAssertions, defineAssertion, flattenList, formatList} = require("chinotto");
const {deindent} =
module.exports = {
/**
* Non-Atom related he... | .replace(/^(?:[ \t]*\n)+|(?:\n[ \t]*)+$/g, "");
for(const line of chunk.split(/\n/)){
// Ignore whitespace-only lines
if(!/\S/.test(line)) continue;
const indentString = line.match(/^[ \t]*(?=\S|$)/)[0];
const indentLength = indentString.replace(/\t/g, " ".repeat(8)).length;
if(indentLength < 1... | // Normalise newlines and strip leading or trailing blank lines
const chunk = String.raw.call(null, input, ...args)
.replace(/\r(\n?)/g, "$1") | random_line_split |
HFIF_RunTime.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 16:26:07 2019
@author: WGP
"""
import xlrd, threading,datetime,os,pymssql,time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from queue import Queue, Empty
from threading import Thread
import WindTDFAPI as w
from keras import models,backend
import numpy as n... | def myLoss(y_true, y_pred):
#return backend.mean(backend.square((y_pred - y_true)*y_true), axis=-1)
return backend.mean(backend.abs((y_pred - y_true)*y_true), axis=-1)
def myMetric(y_true, y_pred):
return backend.mean(y_pred*y_true, axis=-1)*10
def getCfgFareFactor(ffPath):
cfgFile=os.path.joi... | random_line_split | |
HFIF_RunTime.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 16:26:07 2019
@author: WGP
"""
import xlrd, threading,datetime,os,pymssql,time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from queue import Queue, Empty
from threading import Thread
import WindTDFAPI as w
from keras import models,backend
import numpy as n... | stPm))
if isPush and ((intNTime>93100 and intNTime<113000) or (intNTime>130100 and intNTime<150000)):
sql.UpdateAllFF()
finally:
lock.release()
def ReceiveQuote(quoteEvent):
global dictQuote,lock
dt =quoteEvent.data
lock.acquire()
try:
code=byt... | end(ff.pm)
print(intNTime,*tuple(li | conditional_block |
HFIF_RunTime.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 16:26:07 2019
@author: WGP
"""
import xlrd, threading,datetime,os,pymssql,time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from queue import Queue, Empty
from threading import Thread
import WindTDFAPI as w
from keras import models,backend
import numpy as n... |
class MyEvent:
def __init__(self, Eventtype,Data):
self.type_ = Eventtype # 事件类型
self.data = Data # 字典用于保存具体的事件数据
class MSSQL:
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
... | def __init__(self):
self.__eventQueue = Queue()
self.__active = False
self.__thread = Thread(target = self.__Run)
self.__handlers = {}
def __Run(self):
while self.__active == True:
try:
event = self.__eventQueue.get(block = True, timeout ... | identifier_body |
HFIF_RunTime.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 16:26:07 2019
@author: WGP
"""
import xlrd, threading,datetime,os,pymssql,time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from queue import Queue, Empty
from threading import Thread
import WindTDFAPI as w
from keras import models,backend
import numpy as n... | self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="UTF-8")
self.conn.autocommit(True)
self.cur = self.conn.cursor()
if not self.cur:
return False
else:
return True
except:
... | identifier_name | |
utils.py | import os
from os import path
from config import TIMEZONE, SPREADSHEETID
import config
from datetime import datetime, timedelta
import time
from pytz import timezone
import json
import calendar
import models
pj = path.join
CLIENTS_CACHE_VALID = 'CLIENTS_CACHE_VALID'
def p(pt):
return pj(path.dirname(__file__), p... | user = models.user.objects.filter(id=id).first()
cache = {} if not user else json.loads(user.cache)
return cache.get(name, default)
def userCacheSet(id, name, value):
user = models.user.objects.filter(id=id).first()
if not user:
models.user.create(id=id, cache=json.dumps({}))
user = mode... | def getBookingDateFromEvent(event, fmt = '%Y-%m-%d %H:%M'):
start = datetime.strptime(event['start']['dateTime'][:19], "%Y-%m-%dT%H:%M:%S")
bookingDatetime = start.strftime(fmt)
return bookingDatetime
def userCacheGet(id, name, default=None): | random_line_split |
utils.py | import os
from os import path
from config import TIMEZONE, SPREADSHEETID
import config
from datetime import datetime, timedelta
import time
from pytz import timezone
import json
import calendar
import models
pj = path.join
CLIENTS_CACHE_VALID = 'CLIENTS_CACHE_VALID'
def p(pt):
return pj(path.dirname(__file__), p... |
# get: name, default(nullable)
# set: nameValues(dict), minutes(nullable)
def cache(*args):
if isinstance(args[0], dict):
# set
nameValues = args[0]
minutes = listGet(args, 1)
for k, v in nameValues.items():
item = models.cache.objects.filter(name=k).first()
... | return dc.get(name, default) | conditional_block |
utils.py | import os
from os import path
from config import TIMEZONE, SPREADSHEETID
import config
from datetime import datetime, timedelta
import time
from pytz import timezone
import json
import calendar
import models
pj = path.join
CLIENTS_CACHE_VALID = 'CLIENTS_CACHE_VALID'
def p(pt):
return pj(path.dirname(__file__), p... | (ts):
return datetime.fromtimestamp(ts)
gcService = None
def getGoogleCalendarService():
global gcService
if not gcService:
import httplib2
from apiclient import discovery
from get_google_calendar_credentials import get_google_calendar_credentials
credentials = get_google_cal... | toDatetime | identifier_name |
utils.py | import os
from os import path
from config import TIMEZONE, SPREADSHEETID
import config
from datetime import datetime, timedelta
import time
from pytz import timezone
import json
import calendar
import models
pj = path.join
CLIENTS_CACHE_VALID = 'CLIENTS_CACHE_VALID'
def p(pt):
return pj(path.dirname(__file__), p... |
def toTimestamp(dt):
return int(time.mktime(dt.timetuple()))
def toDatetime(ts):
return datetime.fromtimestamp(ts)
gcService = None
def getGoogleCalendarService():
global gcService
if not gcService:
import httplib2
from apiclient import discovery
from get_google_calendar_creden... | month = dt.month - 1 + months
year = dt.year + month // 12
month = month % 12 + 1
day = min(dt.day,calendar.monthrange(year,month)[1])
return dt.replace(year=year, month = month,day=day) | identifier_body |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | let received = unwrap!(block_on(recv_f));
assert_eq!(received, message);
assert!(now_float() - start < 0.1); // Double-check that we're not waiting for DHT chunks.
block_on(destruction_check(alice));
block_on(destruction_check(bob));
}
/// Check the primitives used to communicate with the HTTP fal... | .direct_chunks
.load(Ordering::Relaxed)
> 0));
let start = now_float(); | random_line_split |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | /// Using a minimal one second HTTP fallback which should happen before the DHT kicks in.
#[cfg(feature = "native")]
pub fn peers_http_fallback_recv() {
let ctx = MmCtxBuilder::new().into_mm_arc();
let addr = SocketAddr::new(unwrap!("127.0.0.1".parse()), 30204);
let server = unwrap!(super::http_fallback::ne... | use std::ptr::null;
common::executor::spawn(async move {
peers_dht().await;
unsafe { call_back(cb_id, null(), 0) }
})
}
| identifier_body |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | // NB: Still need the DHT enabled in order for the pings to work.
let alice = block_on(peer(json! ({"dht": "on"}), 2121));
let bob = block_on(peer(json! ({"dht": "on"}), 2122));
let bob_id = unwrap!(bob.public_id());
// Bob isn't a friend yet.
let alice_pctx = unwrap!(super::PeersContext::from_... | return;
}
| conditional_block |
peers_tests.rs | #[cfg(not(feature = "native"))] use common::call_back;
use common::executor::Timer;
use common::for_tests::wait_for_log_re;
use common::mm_ctx::{MmArc, MmCtxBuilder};
use common::privkey::key_pair_from_seed;
#[cfg(feature = "native")] use common::wio::{drive, CORE};
use common::{block_on, now_float, small_rng};
use crd... | (mm: MmArc) {
mm.stop();
if let Err(err) = wait_for_log_re(&mm, 1., "delete_dugout finished!").await {
// NB: We want to know if/when the `peers` destruction doesn't happen, but we don't want to panic about it.
pintln!((err))
}
}
async fn peers_exchange(conf: Json) {
let fallback_on = c... | destruction_check | identifier_name |
fbb_churn_eval_ensemb_alberto.py | # coding: utf-8
import sys
from common.src.main.python.utils.hdfs_generic import *
import argparse
import os
import sys
import time
from pyspark.sql.functions import (udf,
col,
decode,
when,
... | ##################
### EVALUATION ###
##################
# Calibration
calibmodel = get_calibration_function2(spark, model, valdf, 'label', 10)
getScore = udf(lambda prob: float(prob[1]), DoubleType())
# Train
tr_preds_df = model.transform(trdf).withColumn("model_score", getScore(col(... | for fimp in feat_importance:
print "[Info Main FbbChurn] Imp feat " + str(fimp[0]) + ": " + str(fimp[1])
| random_line_split |
fbb_churn_eval_ensemb_alberto.py | # coding: utf-8
import sys
from common.src.main.python.utils.hdfs_generic import *
import argparse
import os
import sys
import time
from pyspark.sql.functions import (udf,
col,
decode,
when,
... |
def initialize(app_name, min_n_executors = 1, max_n_executors = 15, n_cores = 4, executor_memory = "16g", driver_memory="8g"):
import time
start_time = time.time()
print("_initialize spark")
#import pykhaos.utils.pyspark_configuration as pyspark_config
sc, spark, sql_context = get_spark_session(a... | MAX_N_EXECUTORS = max_n_executors
MIN_N_EXECUTORS = min_n_executors
N_CORES_EXECUTOR = n_cores
EXECUTOR_IDLE_MAX_TIME = 120
EXECUTOR_MEMORY = executor_memory
DRIVER_MEMORY = driver_memory
N_CORES_DRIVER = 1
MEMORY_OVERHEAD = N_CORES_EXECUTOR * 2048
QUEUE = "root.BDPtenants.es.medium"
... | identifier_body |
fbb_churn_eval_ensemb_alberto.py | # coding: utf-8
import sys
from common.src.main.python.utils.hdfs_generic import *
import argparse
import os
import sys
import time
from pyspark.sql.functions import (udf,
col,
decode,
when,
... |
####################
### 2. TEST DATA ###
####################
#path = "/data/udf/vf_es/churn/fbb_tmp/ttdf_ini_" + tr_ttdates
#if (pathExist(path)):
#print "[Info Main FbbChurn] " + time.ctime() + " File " + str(path) + " already exists. Reading it."
#ttdf_ini = spark.read.parque... | print "[Info Main FbbChurn] Non-informative feat: " + f | conditional_block |
fbb_churn_eval_ensemb_alberto.py | # coding: utf-8
import sys
from common.src.main.python.utils.hdfs_generic import *
import argparse
import os
import sys
import time
from pyspark.sql.functions import (udf,
col,
decode,
when,
... | (min_n_executors = 1, max_n_executors = 15, n_cores = 8, executor_memory = "16g", driver_memory="8g",
app_name = "Python app", driver_overhead="1g", executor_overhead='3g'):
MAX_N_EXECUTORS = max_n_executors
MIN_N_EXECUTORS = min_n_executors
N_CORES_EXECUTOR = n_cores
EXECUTOR_IDLE_M... | setting_bdp | identifier_name |
feature_extraction.py | import numpy as np
import pandas as pd
from scipy.signal import welch
from scipy.fftpack import fft
import scipy.stats
from collections import Counter
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn.neighbors import KNeig... | (repeats=10):
# Load data
N = 128
fs = 50 # Hz
t_n = 2.56 # total duration seconds
T = t_n / N # sample_rate T
denominator = 10
# Load data
X_train, X_test, y_train, y_test = load_dataset(verbose=0)
# Feature extraction
X_train, Y_train = extract_features(X_train, y_train, T... | run_experiment | identifier_name |
feature_extraction.py | import numpy as np
import pandas as pd
from scipy.signal import welch
from scipy.fftpack import fft
import scipy.stats
from collections import Counter
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn.neighbors import KNeig... |
# remove the small peaks and sort back the indices by their occurrence
ind = np.sort(ind[~idel])
if show:
if indnan.size:
x[indnan] = np.nan
if valley:
x = -x
_plot(x, mph, mpd, threshold, edge, valley, ax, ind)
return ind
def get_values(y_val... | idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \
& (x[ind[i]] > x[ind] if kpsh else True)
idel[i] = 0 # Keep current peak | conditional_block |
feature_extraction.py | import numpy as np
import pandas as pd
from scipy.signal import welch
from scipy.fftpack import fft
import scipy.stats
from collections import Counter
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn.neighbors import KNeig... | if ind.size and ind[-1] == x.size - 1:
ind = ind[:-1]
# remove peaks < minimum peak height
if ind.size and mph is not None:
ind = ind[x[ind] >= mph]
# remove peaks - neighbors < threshold
if ind.size and threshold > 0:
dx = np.min(np.vstack([x[ind] - x[ind - 1], x[ind] - x[in... | if ind.size and ind[0] == 0:
ind = ind[1:] | random_line_split |
feature_extraction.py | import numpy as np
import pandas as pd
from scipy.signal import welch
from scipy.fftpack import fft
import scipy.stats
from collections import Counter
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.pipeline import make_pipeline
from sklearn.svm import SVC
from sklearn.neighbors import KNeig... |
def get_values(y_values, T, N, f_s):
y_values = y_values
x_values = [(1 / f_s) * kk for kk in range(0, len(y_values))]
return x_values, y_values
def get_fft_values(y_values, T, N, f_s):
f_values = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
fft_values_ = fft(y_values)
fft_values = 2.0 / N * n... | """Detect peaks in data based on their amplitude and other features.
Parameters
----------
x : 1D array_like
data.
mph : {None, number}, optional (default = None)
detect peaks that are greater than minimum peak height.
mpd : positive integer, optional (default = 1)
detect pe... | identifier_body |
main.js | // All colors are from https://www.google.com/design/spec/style/color.html#color-color-palette
var classToColorMap = {
'CS 61A': '#4DD0E1',
'CS 61B': '#F06292',
'CS 61C': '#BA68C8',
'CS 70': '#81C784',
'CS 170': '#E57373',
'CS 188': '#7986CB'
};
var defaultClassColor = '#616161';
var clas... | outMap[name].forEach(function(student) {
newHTML += '<li>' + student + '</li>';
});
newHTML += '</ul>';
}
$('#info').innerHTML = newHTML;
$('#info').style.display = 'block';
};
var filterByCourse = function(course) {
if ($('#filter').value !== course) {
$('#filter').value = cou... | });
newHTML += '</ul>';
}
if (outMap[name] && outMap[name].length) {
newHTML += '<p>Students:<ul>';
| random_line_split |
main.js | // All colors are from https://www.google.com/design/spec/style/color.html#color-color-palette
var classToColorMap = {
'CS 61A': '#4DD0E1',
'CS 61B': '#F06292',
'CS 61C': '#BA68C8',
'CS 70': '#81C784',
'CS 170': '#E57373',
'CS 188': '#7986CB'
};
var defaultClassColor = '#616161';
var clas... | else {
activeFilter = '';
s.graph.edges().forEach(function(edge) {
var idParts = edge.id.split(':');
edge.color = classToColor(idParts[2]);
edge.size = 1;
});
s.refresh();
$('#layout-wrapper').style.display = 'inline';
$('#search-wrapper').style.display = 'inline';
... | {
activeFilter = course;
s.graph.edges().forEach(function(edge) {
var idParts = edge.id.split(':');
if (idParts[2] !== course) {
edge.color = 'transparent';
edge.size = 1;
} else {
edge.color = classToColor(idParts[2]);
edge.size = 1;
}
});
... | conditional_block |
Trade.go | package trade
// Trade
type Trade struct {
// 交易编号 (父订单的交易编号)
Tid string `json:"tid,omitempty" xml:"tid,omitempty"`
// 商品购买数量。取值范围:大于零的整数,对于一个trade对应多个order的时候(一笔主订单,对应多笔子订单),num=0,num是一个跟商品关联的属性,一笔订单对应多比子订单的时候,主订单上的num无意义。
Num int64 `json:"num,omitempty" xml:"num,omitempty"`
... |
BrandLightShopSource string `json:"brand_light_shop_source,omitempty" xml:"brand_light_shop_source,omitempty"`
// 透出的额外信息
ExtendInfo string `json:"extend_info,omitempty" xml:"extend_info,omitempty"`
// 收货地址有变更,返回"1"
Lm string `json:"lm,omitempty" xml:"lm,om... | // 同城购订单source | random_line_split |
asistencia.component.ts | import { Component, OnInit, ViewChild, ViewContainerRef, Input, ChangeDetectorRef } from '@angular/core';
import { PopoverModule } from 'ngx-popover';
import { DaterangepickerConfig, DaterangePickerComponent } from 'ng2-daterangepicker';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute } from... | ( time ){
let td = moment(time)
if( td < moment(`${moment().format('YYYY-MM-DD')} 05:00:00`)){
return td.add(1, 'days')
}else{
return td
}
}
showDom(rac, date, block){
if(this.checkSet(rac, date, block)){
this.shownDom[`${rac}_${date}_${block}`] = undefined
}else{
th... | timeDateXform | identifier_name |
asistencia.component.ts | import { Component, OnInit, ViewChild, ViewContainerRef, Input, ChangeDetectorRef } from '@angular/core';
import { PopoverModule } from 'ngx-popover';
import { DaterangepickerConfig, DaterangePickerComponent } from 'ng2-daterangepicker';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute } from... | else{
this.loading = true
}
}else{
this.loading = true
}
this._api.restfulPut( params, 'Asistencia/pya' )
.subscribe( res =>{
if( asesor && !flag){
// console.log( res )
this.singleUpdate( res )
... | {
this.asistData[asesor]['data'][inicio]['loading'] = true
} | conditional_block |
asistencia.component.ts | import { Component, OnInit, ViewChild, ViewContainerRef, Input, ChangeDetectorRef } from '@angular/core';
import { PopoverModule } from 'ngx-popover';
import { DaterangepickerConfig, DaterangePickerComponent } from 'ng2-daterangepicker';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute } from... |
checkSet(rac, date, block){
if(this.isset(this.shownDom,`${rac}_${date}_${block}`)){
return true
}else{
return false
}
}
isset (a, name ) {
let is = true
if ( a[name] == undefined || a[name] == '' || a[name] == null ) {
is = false
}
return is;
}
prog... | {
if(this.checkSet(rac, date, block)){
this.shownDom[`${rac}_${date}_${block}`] = undefined
}else{
this.shownDom[`${rac}_${date}_${block}`] = true
}
} | identifier_body |
asistencia.component.ts | import { Component, OnInit, ViewChild, ViewContainerRef, Input, ChangeDetectorRef } from '@angular/core';
import { PopoverModule } from 'ngx-popover';
import { DaterangepickerConfig, DaterangePickerComponent } from 'ng2-daterangepicker';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute } from... | let cunTime = time.clone().tz('America/Bogota')
return cunTime.format(format)
}
orderNames( data, ord=1 ){
// console.log(data)
let sortArray:any = []
let tmpSlot:any = []
let flag:boolean
let pushFlag:boolean
let x:number
let lastInput:any
let compare:any = []
... | formatDate(datetime, format){
let time = moment.tz(datetime, 'this._zh.defaultZone') | random_line_split |
simple-handler.go | /*
Package simplehttp provides an http.Handler that makes it easy to serve Vugu applications.
Useful for development and production.
The idea is that the common behaviors needed to serve a Vugu site are readily available
in one place. If you require more functionality than simplehttp provides, nearly everything
it d... |
h.wasmExecJsTs = time.Now() // hack but whatever for now
})
if len(h.wasmExecJsContent) == 0 {
http.Error(w, "failed to read wasm_exec.js from local Go environment", 500)
return
}
w.Header().Set("Content-Type", "text/javascript")
http.ServeContent(w, r, "/wasm_exec.js", h.wasmExecJsTs, bytes.NewReader(h.w... | {
http.Error(w, "failed to run `go env GOROOT`: "+err.Error(), 500)
return
} | conditional_block |
simple-handler.go | /*
Package simplehttp provides an http.Handler that makes it easy to serve Vugu applications.
Useful for development and production.
The idea is that the common behaviors needed to serve a Vugu site are readily available
in one place. If you require more functionality than simplehttp provides, nearly everything
it d... | if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("X-Gzipped-Size", fmt.Sprint(len(lastBuildContentGZ)))
http.ServeContent(w, r, h.MainWasmPath, lastBuildTime, bytes.NewReader(lastBuildContentGZ))
return
}
// no gzip, we decompress inter... | // w.Header().Set("Last-Modified", lastBuildTime.Format(http.TimeFormat)) // handled by http.ServeContent
// if client supports gzip response (the usual case), we just set the gzip header and send back | random_line_split |
simple-handler.go | /*
Package simplehttp provides an http.Handler that makes it easy to serve Vugu applications.
Useful for development and production.
The idea is that the common behaviors needed to serve a Vugu site are readily available
in one place. If you require more functionality than simplehttp provides, nearly everything
it d... | {
dirf, err := os.Open(dir)
if err != nil {
return ts, err
}
defer dirf.Close()
fis, err := dirf.Readdir(-1)
if err != nil {
return ts, err
}
for _, fi := range fis {
if fi.Name() == "." || fi.Name() == ".." {
continue
}
// for directories we recurse
if fi.IsDir() {
dirTs, err := dirTimes... | identifier_body | |
simple-handler.go | /*
Package simplehttp provides an http.Handler that makes it easy to serve Vugu applications.
Useful for development and production.
The idea is that the common behaviors needed to serve a Vugu site are readily available
in one place. If you require more functionality than simplehttp provides, nearly everything
it d... | (dir string) (ts time.Time, reterr error) {
dirf, err := os.Open(dir)
if err != nil {
return ts, err
}
defer dirf.Close()
fis, err := dirf.Readdir(-1)
if err != nil {
return ts, err
}
for _, fi := range fis {
if fi.Name() == "." || fi.Name() == ".." {
continue
}
// for directories we recurse
... | dirTimestamp | identifier_name |
parse_dwarf.py | # -*- Mode: Python -*-
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ri... | :
def __init__ (self, tree, by_pos):
self.tree = tree
tag, where, self.attrs, self.children = tree
assert (tag == 'compile_unit')
self.by_pos = by_pos
def __repr__ (self):
return '<compile_unit %r at 0x%x>' % (self.attrs['name'], id(self))
def dump (self, file):
... | compile_unit | identifier_name |
parse_dwarf.py | # -*- Mode: Python -*-
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ri... |
def test (path):
import parse_elf
import sys
global info
info_iter = read (path, parse_elf.go (path))
if not info_iter:
sys.stderr.write ('no debugging information present\n')
else:
for unit in info_iter:
print '-' * 75
unit.dump (sys.stdout)
if __name_... | """read (<path>, <elf_info>) => <iterator>
generate a list of <compile_unit> objects for file <path>"""
ehdr, phdrs, shdrs, syms, core_info = elf_info
info = abbrev = strings = None
for shdr in shdrs:
if shdr['name'] == '.debug_info':
info = shdr['offset'], shdr['size']
if sh... | identifier_body |
parse_dwarf.py | # -*- Mode: Python -*-
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ri... |
if TAGS.has_key (tag):
item = (TAGS[tag], where, attrs, children)
else:
item = (tag, where, attrs, children)
by_pos[where] = item
tree.append (item)
if depth == 0:
# only one element at the top level, special-ca... | children = None | conditional_block |
parse_dwarf.py | # -*- Mode: Python -*-
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the ri... | DW_ATE_boolean = 0x02
DW_ATE_complex_float = 0x03
DW_ATE_float = 0x04
DW_ATE_signed = 0x05
DW_ATE_signed_char = 0x06
DW_ATE_unsigned = 0x07
DW_ATE_unsigned_char = 0x08
DW_ATE_imaginary_float = 0x09
DW_ATE_packed_decimal = 0x0a
DW_ATE_numeric_string = 0x0b
DW_ATE_edited ... | random_line_split | |
report.go | /*
Copyright 2017 The Kubernetes 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 writing, ... | return result
}
func newResources() *Resources {
return &Resources{
PrimaryResources: v1.ResourceList{
v1.ResourceName(v1.ResourceCPU): *resource.NewMilliQuantity(0, resource.DecimalSI),
v1.ResourceName(v1.ResourceMemory): *resource.NewQuantity(0, resource.BinarySI),
v1.ResourceName... | } | random_line_split |
report.go | /*
Copyright 2017 The Kubernetes 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 writing, ... |
func printResources(resources *Resources) {
fmt.Printf("\t\t- CPU: %v\n", resources.PrimaryResources.Cpu().String())
fmt.Printf("\t\t- Memory: %v\n", resources.PrimaryResources.Memory().String())
if resources.PrimaryResources.StorageEphemeral() != nil {
fmt.Printf("\t\t- Ephemeral Storage: %v\n", resources.Prim... | {
cap := float64(requested) / float64(allocatable) * 100
fmt.Printf("\t- %s requested: %v%s/%v%s %.2f%% allocated\n",
label, requested, unit, allocatable, unit, cap)
commit := float64(limit) / float64(allocatable) * 100
fmt.Printf("\t- %s limited: %v%s/%v%s %.2f%% allocated\n",
label, limit, unit, allocatable, ... | identifier_body |
report.go | /*
Copyright 2017 The Kubernetes 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 writing, ... |
return resultSlc
}
func getPodsRequirements(pods []*v1.Pod) []*Requirements {
result := make([]*Requirements, 0)
for _, pod := range pods {
podRequirements := &Requirements{
PodName: pod.Name,
Resources: getResourceRequest(pod),
Limits: getResourceLimit(pod),
NodeSelectors: pod.Spec.... | {
resultSlc = append(resultSlc, v)
} | conditional_block |
report.go | /*
Copyright 2017 The Kubernetes 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 writing, ... | (pod *v1.Pod) *Resources {
result := newResources()
for _, container := range pod.Spec.Containers {
appendResources(result, container.Resources.Requests)
}
return result
}
func getResourceLimit(pod *v1.Pod) *Resources {
result := newResources()
for _, container := range pod.Spec.Containers {
appendResources(... | getResourceRequest | identifier_name |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit="256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use sp_std::prelude::*;
use sp_core::{
c... |
}
impl Convert<Balance, u64> for CurrencyToVoteHandler {
fn convert(x: Balance) -> u64 {
(x / Self::factor()) as u64
}
}
impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance {
x * Self::factor()
}
}
parameter_types! {
pub const SessionsPerEra: sp_staking::SessionIndex = 3;... | {
(Balances::total_issuance() / u64::max_value() as Balance).max(1)
} | identifier_body |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit="256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use sp_std::prelude::*;
use sp_core::{
c... | (x: Balance) -> u64 {
(x / Self::factor()) as u64
}
}
impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance {
x * Self::factor()
}
}
parameter_types! {
pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours
pub const BondingDuration: pallet_staking::EraIndex = 4; ... | convert | identifier_name |
lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit="256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use sp_std::prelude::*;
use sp_core::{
c... | type WeightInfo = ();
}
parameter_types! {
pub const TransactionByteFee: Balance = 1;
}
/// pallet_transaction_payment origin
impl pallet_transaction_payment::Trait for Runtime {
type Currency = Balances;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = IdentityFee<Balance>;
type OnTransactionPa... | type AccountStore = System; //
type Event = Event; | random_line_split |
paxos.go | package paxos
//
// Paxos library, to be included in an application.
// Multiple applications will run, each including
// a Paxos peer.
//
// Manages a sequence of agreed-on values.
// The set of peers is fixed.
// Copes with network failures (partition, msg loss, &c).
// Does not store anything persistently, so canno... | (seq int, v interface{}) {
for idx, peer := range px.peers {
args := &DecdidedArgs{}
reply := &DecidedReply{}
args.Seq = seq
args.V = v
if idx == px.me {
px.Decided(args, reply)
} else {
call(peer, "Paxos.Decided", args, reply)
}
}
}
/* Learner
* handler for decide notification
*/
func (px *P... | send_decided | identifier_name |
paxos.go | package paxos
//
// Paxos library, to be included in an application.
// Multiple applications will run, each including
// a Paxos peer.
//
// Manages a sequence of agreed-on values.
// The set of peers is fixed.
// Copes with network failures (partition, msg loss, &c).
// Does not store anything persistently, so canno... |
/* Proposer
* send decided value to all
*/
func (px *Paxos) send_decided(seq int, v interface{}) {
for idx, peer := range px.peers {
args := &DecdidedArgs{}
reply := &DecidedReply{}
args.Seq = seq
args.V = v
if idx == px.me {
px.Decided(args, reply)
} else {
call(peer, "Paxos.Decided", args, re... | {
if args.Proposal.PNum >= px.APp[args.Seq] {
px.APp[args.Seq] = args.Proposal.PNum
px.APa[args.Seq] = args.Proposal
reply.Err = OK
} else {
reply.Err = Reject
}
return nil
} | identifier_body |
paxos.go | package paxos
//
// Paxos library, to be included in an application.
// Multiple applications will run, each including
// a Paxos peer.
//
// Manages a sequence of agreed-on values.
// The set of peers is fixed.
// Copes with network failures (partition, msg loss, &c).
// Does not store anything persistently, so canno... |
return false
}
defer c.Close()
// fmt.Printf("Call srv:%s name:%s\n", srv, name)
err = c.Call(name, args, reply)
// fmt.Printf("After Call %s, err:%v, rpl:%v\n", srv, err, reply)
if err == nil {
return true
}
return false
}
/* clog(bool, func_name, format) */
func (px *Paxos) clog(dbg bool, funcname, fo... | {
fmt.Printf("paxos Dial() failed: %v\n", err1)
} | conditional_block |
paxos.go | package paxos
//
// Paxos library, to be included in an application.
// Multiple applications will run, each including
// a Paxos peer.
//
// Manages a sequence of agreed-on values.
// The set of peers is fixed.
// Copes with network failures (partition, msg loss, &c).
// Does not store anything persistently, so canno... |
px.clog(DBG_PROPOSER, "Start", "decided")
break
}
}()
}
//
// the application on this machine is done with
// all instances <= seq.
//
// see the comments for Min() for more explanation.
//
func (px *Paxos) Done(seq int) {
// Your code here.
px.clog(DBG_DONE, "Done", "Done: %d", seq)
if seq <= px.local_... | px.clog(DBG_PROPOSER, "Start", "accept OK")
px.send_decided(seq, new_p.Value) | random_line_split |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... |
let ptr: *mut E = self
.ctx
.bump
.get_or_default()
.alloc_layout(Layout::for_value(self.queued.as_slice()))
.cast::<E>()
.as_ptr();
self.queued
.drain(..)
.enumerate()
.for_each(|(index, event... | {
return; // Nothing to do
} | conditional_block |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... | (&mut self, event: E) {
self.queued.push(event);
}
pub fn trigger_batched(&mut self, events: impl IntoIterator<Item = E>) {
self.queued.extend(events);
}
}
impl<'a, E> SystemDataOutput<'a> for &'a mut Trigger<E>
where
E: Send + Sync + 'static,
{
type SystemData = Trigger<E>;
}
imp... | trigger | identifier_name |
event.rs | use crate::mappings::Mappings;
use crate::scheduler::TaskMessage;
use crate::system::{SystemCtx, SystemDataOutput, SYSTEM_ID_MAPPINGS};
use crate::{resource_id_for_component, MacroData, ResourceId, Resources, SystemData, SystemId};
use hashbrown::HashSet;
use lazy_static::lazy_static;
use legion::storage::ComponentType... | /// Returns the unique ID of this event handler, as allocated by `system_id_for::<T>()`.
fn id(&self) -> SystemId;
/// Returns the name of this event handler.
fn name(&self) -> &'static str;
/// Returns the ID of the event which is handled by this handler.
fn event_id(&self) -> EventId;
/... | pub unsafe trait RawEventHandler: Send + Sync + 'static { | random_line_split |
tutorial.js | var Tutorial = function() {
this.prev = this.index;
this.next = this._p1;
}
Tutorial.prototype = {
index: function() {
this.next = this._p1;
return P('Use `tutorial <chapter> <section>` or `next` `prev` commands to navigate.') + BR() +
P('Available sections are:') +
... | return P("Chapter 2c - Using Gremlin build-in functions and data structures (maps, lists).") + BR() +
P(" Gremlin provides build-in functions and data structures which will be very useful while working with graphs.") + BR() +
P("To execute a function you should call it using special... | random_line_split | |
main_classes.py | import random
import colorama
from termcolor import colored
from reusables.string_manipulation import int_to_words
from app.common_functions import comma_separated, add_dicts_together, remove_little_words, odds
from app.load_data import items, buildings, wild_mobs, names, adjectives
colorama.init()
def find_uniqu... | if random.randint(0, results[rarity]) == 1:
quantity += 1
countdown -= 1
return quantity
def drop_building(dictionary, p, limit=None):
limit = limit or len(adjectives)
drops_i = []
for k, v in dictionary.items():
quantity = dropper(v['rarity'])
quantity = q... | 'super common': 2}
quantity = 0
countdown = random.randint(0, 10)
while countdown > 0: | random_line_split |
main_classes.py | import random
import colorama
from termcolor import colored
from reusables.string_manipulation import int_to_words
from app.common_functions import comma_separated, add_dicts_together, remove_little_words, odds
from app.load_data import items, buildings, wild_mobs, names, adjectives
colorama.init()
def find_uniqu... |
else:
return None
@staticmethod
def skills():
""" Pick the skills for a mob, these determine what a player can get from completing a quest """
all_skills = ["strength", "patience", "cleanliness", "leadership", "communication",
"science", "math", "engin... | self.inventory.remove(nice_weapons[0])
return nice_weapons[0] | conditional_block |
main_classes.py | import random
import colorama
from termcolor import colored
from reusables.string_manipulation import int_to_words
from app.common_functions import comma_separated, add_dicts_together, remove_little_words, odds
from app.load_data import items, buildings, wild_mobs, names, adjectives
colorama.init()
def find_uniqu... | (self, name, p, plural, category=None, rarity=None, ware_list=None, mobs=None, jobs=None):
self.name = name
self.p = p
self.quantity = 1
self.plural = plural
self.category = category or None
self.rarity = rarity or None
self.ware_list = ware_list
self.ware... | __init__ | identifier_name |
main_classes.py | import random
import colorama
from termcolor import colored
from reusables.string_manipulation import int_to_words
from app.common_functions import comma_separated, add_dicts_together, remove_little_words, odds
from app.load_data import items, buildings, wild_mobs, names, adjectives
colorama.init()
def find_uniqu... |
def view_hit_list(self):
if self.hit_list:
print(f"If you ever run across these shady characters, be sure to take their names off your list: {comma_separated(self.hit_list)}")
else:
print("Looks like you don't know of anyone who needs to be dead.")
def increase_skill(s... | print(f"You have killed {self.body_count} mobs.")
print(f"You have ran away from {self.run_away_count} battles.")
print(f"You have eaten {self.food_count} items.")
print(f"You have performed {self.assassination_count} assassinations.")
print(f"You have talked to mobs {self.greeting_count... | identifier_body |
tanzania-improved.py | # coding: utf-8
# In[1]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # d... | # In[34]:
df_pred1.head()
# In[35]:
#df_pred2.head()
df_pred1.round({"no_financial_services":4, "other_only":4, "mm_only":4, "mm_plus":4})
# In[36]:
df_pred1.to_csv('pred_set.csv', index=False) #save to csv file#
# FROM HERE THE CODE IS SPECIFIC TO XGBOOST MULTICLASS CLASSIFICATION
# In[37]:
#now since w... |
df_pred.head()
| random_line_split |
tanzania-improved.py |
# coding: utf-8
# In[1]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # ... |
# In[18]:
from pprint import pprint
# Look at parameters used by our current forest
print('Parameters currently in use:\n')
pprint(rf.get_params())
# In[19]:
from sklearn.model_selection import RandomizedSearchCV
# Number of trees in random forest
n_estimators = [int(x) for x in np.linspace(start = 200, stop =... | print("Train Index: ", train_index, "\n")
print("Test Index: ", test_index)
X_train, X_test, y_train, y_test = X2[train_index], X2[test_index], y[train_index], y[test_index]
rf.fit(X_train, y_train)
scores.append(rf.score(X_test, y_test)) | conditional_block |
main.js | moment().format();
let CabSimple = 800;
let CabDoble = 1300;
let CabSuite = 2000;
const iva = (x) => x * 0.21;
let sumaPorDia = (a, b) => a + b;
let simpleIVA = sumaPorDia(CabSimple, iva(CabSimple));
let dobleIVA = sumaPorDia(CabDoble, iva(CabDoble));
let suiteIVA = sumaPorDia(CabSuite, iva(CabSuite));
let estadia... | servicios.push(
new Servicio(
2,
'Tirolesa',
800,
'Recreacion',
'Deslizamiento por cable entre las copas de los arboles.',
false,
0
)
);
servicios.push(
new Servicio(
3,
'Trekking',
800,
'Recreacion',
'Caminata guiada por el bosque.',
false,
0
)
);
servici... | 'Tour a caballo guiado por el bosque.',
false,
0
)
); | random_line_split |
main.js | moment().format();
let CabSimple = 800;
let CabDoble = 1300;
let CabSuite = 2000;
const iva = (x) => x * 0.21;
let sumaPorDia = (a, b) => a + b;
let simpleIVA = sumaPorDia(CabSimple, iva(CabSimple));
let dobleIVA = sumaPorDia(CabDoble, iva(CabDoble));
let suiteIVA = sumaPorDia(CabSuite, iva(CabSuite));
let estadia... |
function Cabaña(id, nombre, precio, selected) {
this.id = id;
this.nombre = nombre;
this.precio = precio;
this.selected = selected;
}
const cabins = [];
cabins.push(new Cabaña(1, 'Cabaña simple', simpleIVA, false));
cabins.push(new Cabaña(2, 'Cabaña doble', dobleIVA, false));
cabins.push(new Cabaña(3, 'Caba... | cabanasimple.style.display = 'none';
cabanadoble.style.display = 'none';
cabanasuite.style.display = 'initial';
aparecerDoble.style.display = 'none';
aparecerSimple.style.display = 'none';
}
}; | conditional_block |
main.js | moment().format();
let CabSimple = 800;
let CabDoble = 1300;
let CabSuite = 2000;
const iva = (x) => x * 0.21;
let sumaPorDia = (a, b) => a + b;
let simpleIVA = sumaPorDia(CabSimple, iva(CabSimple));
let dobleIVA = sumaPorDia(CabDoble, iva(CabDoble));
let suiteIVA = sumaPorDia(CabSuite, iva(CabSuite));
let estadia... | url: 'https://randomuser.me/api/?results=4&nat=us,fr,br',
dataType: 'json',
success: function (data) {
contenidoJSON = data.results;
for (let i in contenidoJSON) {
HTMLCard += ` <div class="card m-4 rounded-3">
<img class="card-img-top img-testimonial" src=... | $.ajax({
| identifier_name |
main.js | moment().format();
let CabSimple = 800;
let CabDoble = 1300;
let CabSuite = 2000;
const iva = (x) => x * 0.21;
let sumaPorDia = (a, b) => a + b;
let simpleIVA = sumaPorDia(CabSimple, iva(CabSimple));
let dobleIVA = sumaPorDia(CabDoble, iva(CabDoble));
let suiteIVA = sumaPorDia(CabSuite, iva(CabSuite));
let estadia... |
}
const servicios = [];
servicios.push(
new Servicio(
1,
'Cabalgata',
600,
'Recreacion',
'Tour a caballo guiado por el bosque.',
false,
0
)
);
servicios.push(
new Servicio(
2,
'Tirolesa',
800,
'Recreacion',
'Deslizamiento por cable entre las copas de los arboles.'... | {
this.id = id;
this.nombre = nombre;
this.costo = costo;
this.tipo = tipo;
this.descripcion = descripcion;
this.selected = selected;
this.cantidadPersonas = cantidadPersonas;
} | identifier_body |
nginx_controller.go | // Copyright 2020 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controllers
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/ap... | (ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("nginx", req.NamespacedName)
var instance nginxv1alpha1.Nginx
err := r.Client.Get(ctx, req.NamespacedName, &instance)
if err != nil {
if errors.IsNotFound(err) {
log.Info("Nginx resource not found, skipping reconcile")
r... | Reconcile | identifier_name |
nginx_controller.go | // Copyright 2020 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controllers
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/ap... |
var ingresses []nginxv1alpha1.IngressStatus
for _, i := range ingressList.Items {
ingresses = append(ingresses, nginxv1alpha1.IngressStatus{Name: i.Name})
}
sort.Slice(ingresses, func(i, j int) bool {
return ingresses[i].Name < ingresses[j].Name
})
return ingresses, nil
}
func (r *NginxReconciler) should... | {
return nil, err
} | conditional_block |
nginx_controller.go | // Copyright 2020 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controllers
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/ap... |
func (r *NginxReconciler) reconcileDeployment(ctx context.Context, nginx *nginxv1alpha1.Nginx) error {
newDeploy, err := k8s.NewDeployment(nginx)
if err != nil {
return fmt.Errorf("failed to build Deployment from Nginx: %w", err)
}
var currentDeploy appsv1.Deployment
err = r.Client.Get(ctx, types.NamespacedNa... | {
if err := r.reconcileDeployment(ctx, nginx); err != nil {
return err
}
if err := r.reconcileService(ctx, nginx); err != nil {
return err
}
if err := r.reconcileIngress(ctx, nginx); err != nil {
return err
}
return nil
} | identifier_body |
nginx_controller.go | // Copyright 2020 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controllers
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/ap... | "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/contr... | networkingv1 "k8s.io/api/networking/v1" | random_line_split |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
//
// 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... | (ctx *Context, source map[string]interface{}) (Resource, error) {
v, ok := source["__self__"]
if !ok {
return nil, nil
}
ci := v.(*constructInput)
if ci.value.ContainsUnknowns() {
return nil, errors.New("__self__ is unknown")
}
value, secret, err := unmarshalPropertyValue(ctx, ci.value)
if err != nil {
... | callArgsSelf | identifier_name |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
//
// 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... |
// Deserialize the inputs and apply appropriate dependencies.
inputDependencies := req.GetInputDependencies()
deserializedInputs, err := plugin.UnmarshalProperties(
req.GetInputs(),
plugin.MarshalOptions{KeepSecrets: true, KeepResources: true, KeepUnknowns: req.GetDryRun()},
)
if err != nil {
return nil, e... | {
return nil, errors.Wrap(err, "constructing run context")
} | conditional_block |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
//
// 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... | if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return errors.New("args must be a pointer to a struct")
}
argsV, typ = argsV.Elem(), typ.Elem()
for k, v := range inputs {
ci := v.(*constructInput)
for i := 0; i < typ.NumField(); i++ {
fieldV := argsV.Field(i)
if !fieldV.CanSet() {... | }
argsV := reflect.ValueOf(args)
typ := argsV.Type() | random_line_split |
provider.go | // Copyright 2016-2021, Pulumi Corporation.
//
// 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... |
type callFunc func(ctx *Context, tok string, args map[string]interface{}) (Input, error)
// call adapts the gRPC CallRequest/CallResponse to/from the Pulumi Go SDK programming model.
func call(ctx context.Context, req *pulumirpc.CallRequest, engineConn *grpc.ClientConn,
callF callFunc) (*pulumirpc.CallResponse, err... | {
if resource == nil {
return nil, nil, errors.New("resource must not be nil")
}
resourceV := reflect.ValueOf(resource)
typ := resourceV.Type()
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return nil, nil, errors.New("resource must be a pointer to a struct")
}
resourceV, typ = resou... | identifier_body |
build_server.go | package buildserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
pathpkg "path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/die-net/lrucache"
"github.com/gregjones/httpcache"
op... | {
var result error
for _, closer := range h.closers {
err := closer.Close()
if err != nil {
result = multierror.Append(result, err)
}
}
return result
} | identifier_body | |
build_server.go | package buildserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
pathpkg "path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/die-net/lrucache"
"github.com/gregjones/httpcache"
op... | if err := json.Unmarshal(*req.Params, &p); err != nil {
return nil, err
}
dirsHint, haveDirsHint := p.Hints["dirs"]
if haveDirsHint {
dirs := dirsHint.([]interface{})
for i, dir := range dirs {
dirs[i] = rewriteURIFromClient(lsp.DocumentURI(dir.(string)))
}
// Arbitrarily chosen li... | random_line_split | |
build_server.go | package buildserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
pathpkg "path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/die-net/lrucache"
"github.com/gregjones/httpcache"
op... | (ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
// Prevent any uncaught panics from taking the entire server down.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("unexpected panic: %v", r)
// Same as net/http
const size = 64 << 10
buf :... | Handle | identifier_name |
build_server.go | package buildserver
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
pathpkg "path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"time"
multierror "github.com/hashicorp/go-multierror"
"github.com/die-net/lrucache"
"github.com/gregjones/httpcache"
op... |
return nil, err
}
h.InitTracer(conn)
span, ctx, err := h.SpanForRequest(ctx, "build", req, opentracing.Tags{"mode": "go"})
if err != nil {
return nil, err
}
defer func() {
if err != nil {
ext.Error.Set(span, true)
span.LogFields(otlog.Error(err))
}
span.Finish()
}()
if Debug && h.init != nil ... | {
err = nil
} | conditional_block |
cdn_log.go | package cdn
import (
"bufio"
"context"
"crypto/rsa"
"fmt"
"net"
"strconv"
"strings"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/ovh/cds/engine/api/cache"
"github.com/ovh/cds/engine/api/services"
"github.com/ovh/cds/engine/api/worker"
"github.com/ovh/cds/engine/api/workflow"
"github.com/o... |
func (s *Service) dequeueJobMessages(ctx context.Context, jobLogsQueueKey string, jobID string) error {
log.Info(ctx, "Dequeue %s", jobLogsQueueKey)
var t0 = time.Now()
var t1 = time.Now()
var nbMessages int
defer func() {
delta := t1.Sub(t0)
log.Info(ctx, "processLogs[%s] - %d messages received in %v", jobL... | {
for {
select {
case <-ctx.Done():
return
default:
// List all queues
keyListQueue := cache.Key(keyJobLogQueue, "*")
listKeys, err := s.Cache.Keys(keyListQueue)
if err != nil {
log.Error(ctx, "unable to list jobs queues %s", keyListQueue)
continue
}
// For each key, check if heartb... | identifier_body |
cdn_log.go | package cdn
import (
"bufio"
"context"
"crypto/rsa"
"fmt"
"net"
"strconv"
"strings"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/ovh/cds/engine/api/cache"
"github.com/ovh/cds/engine/api/services"
"github.com/ovh/cds/engine/api/worker"
"github.com/ovh/cds/engine/api/workflow"
"github.com/o... |
sdk.GoRoutine(ctx, "cdn-dequeue-job-message", func(ctx context.Context) {
if err := s.dequeueJobMessages(ctx, jobQueueKey, jobID); err != nil {
log.Error(ctx, "unable to dequeue redis incoming job queue: %v", err)
}
})
}
time.Sleep(250 * time.Millisecond)
}
}
}
func (s *Service) dequ... | {
continue
} | conditional_block |
cdn_log.go | package cdn
import (
"bufio"
"context"
"crypto/rsa"
"fmt"
"net"
"strconv"
"strings"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/ovh/cds/engine/api/cache"
"github.com/ovh/cds/engine/api/services"
"github.com/ovh/cds/engine/api/worker"
"github.com/ovh/cds/engine/api/workflow"
"github.com/o... | if exist {
return "", nil
}
//hearbeat
heartbeatKey := cache.Key(keyJobHearbeat, jobID)
if err := s.Cache.SetWithTTL(heartbeatKey, true, 30); err != nil {
return "", err
}
return jobQueueKey, nil
} | // if key exist, that mean that someone is already dequeuing | random_line_split |
cdn_log.go | package cdn
import (
"bufio"
"context"
"crypto/rsa"
"fmt"
"net"
"strconv"
"strings"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/ovh/cds/engine/api/cache"
"github.com/ovh/cds/engine/api/services"
"github.com/ovh/cds/engine/api/worker"
"github.com/ovh/cds/engine/api/workflow"
"github.com/o... | (ctx context.Context, hatcheryID int64, hatcheryName string) (*rsa.PublicKey, error) {
h, err := services.LoadByNameAndType(ctx, s.Db, hatcheryName, services.TypeHatchery)
if err != nil {
return nil, err
}
if h.ID != hatcheryID {
return nil, sdk.WithStack(sdk.ErrWrongRequest)
}
// Verify signature
pk, err ... | getHatchery | identifier_name |
test_runner.go | /*
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
*... |
seq := getRandSeq()
ue := makeUE(imsi, key, opc, seq)
sub := makeSubscriber(imsi, key, opc, seq+1)
err = uesim.AddUE(ue)
if err != nil {
return nil, errors.Wrap(err, "Error adding UE to UESimServer")
}
err = addSubscriberToHSS(sub)
if err != nil {
return nil, errors.Wrap(err, "Error adding Subs... | {
return nil, err
} | conditional_block |
test_runner.go | /*
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
*... | (numIMSIs int, preExistingIMSIS map[string]interface{}) []string {
set := make(map[string]bool)
IMSIs := make([]string, 0, numIMSIs)
for i := 0; i < numIMSIs; i++ {
imsi := ""
for {
imsi = getRandomIMSI()
// Check if IMSI is in the preexisting list of IMSI or in the current generated list
presentPreExis... | generateRandomIMSIS | identifier_name |
test_runner.go | /*
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
*... |
func (tr *TestRunner) WaitForEnforcementStatsForRule(imsi string, ruleIDs ...string) func() bool {
// Wait until the ruleIDs show up for the IMSI
return func() bool {
fmt.Printf("Waiting until %s, %v shows up in enforcement stats...\n", imsi, ruleIDs)
records, err := tr.GetPolicyUsage()
if err != nil {
retu... | func (tr *TestRunner) WaitForPoliciesToSync() {
// TODO load this value from sessiond.yml (rule_update_interval_sec)
ruleUpdatePeriod := 1 * time.Second
time.Sleep(4 * ruleUpdatePeriod)
} | random_line_split |
test_runner.go | /*
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
*... |
func (tr *TestRunner) WaitForNoEnforcementStatsForRule(imsi string, ruleIDs ...string) func() bool {
// Wait until the ruleIDs disappear for the IMSI
return func() bool {
fmt.Printf("Waiting until %s, %v disappear from enforcement stats...\n", imsi, ruleIDs)
records, err := tr.GetPolicyUsage()
if err != nil {... | {
// Wait until the ruleIDs show up for the IMSI
return func() bool {
fmt.Printf("Waiting until %s, %v shows up in enforcement stats...\n", imsi, ruleIDs)
records, err := tr.GetPolicyUsage()
if err != nil {
return false
}
if records[prependIMSIPrefix(imsi)] == nil {
return false
}
for _, ruleID :=... | identifier_body |
dt.py | from __future__ import division
import matplotlib as mpl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
mpl.rc('figure', figsize=[12,8]) #set the default figure size
import itertools, random, math
import time
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/ar... |
class Split(object):
def __init__(self, data, class_column, split_column, point=None):
self.data = data
self.class_column = class_column
self.split_column = split_column
self.info_gain = None
self.point = point
self.partition_list... | data = self.data
if self.node_type != 'leaf':
s = (f"{self.name} Internal node with {data[data.columns[0]].count()} rows; split"
f" {self.split.split_column} at {self.split.point:.2f} for children with"
f" {[p[p.columns[0]].count() for p in self.split.partitions()]}... | identifier_body |
dt.py | from __future__ import division
import matplotlib as mpl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
mpl.rc('figure', figsize=[12,8]) #set the default figure size
import itertools, random, math
import time
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/ar... |
res.append(node.label)
return res
def plurality_value(self, data):
#return data[self.class_column].value_counts().idxmax()
return np.argmax(np.bincount(data[self.class_column].astype(int).values))
def print(self):
self.recursive_print(self.root)... | node = node.children[1] | conditional_block |
dt.py | from __future__ import division
import matplotlib as mpl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
mpl.rc('figure', figsize=[12,8]) #set the default figure size
import itertools, random, math
import time
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/ar... | for depth in range(MAX_DEPTH + 1)[2::2]:
# initialize the tree
dt = DecisionTree(depth)
training_error_ratio_sum = 0
test_error_ratio_sum = 0
for sets in [[0,1,2],[1,2,0],[0,2,1]]:
# get the training data and test data
training_data =... | # initilize the correct ratio of training data and test data
training_error_ratio = []
test_error_ratio = [] | random_line_split |
dt.py | from __future__ import division
import matplotlib as mpl
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
mpl.rc('figure', figsize=[12,8]) #set the default figure size
import itertools, random, math
import time
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/ar... | (self, neg, pos):
data = self.data[self.class_column].values.astype(int)
H0 = self.compute_entropy(data)
p_neg = len(neg) / len(data)
p_pos = len(pos) / len(data)
H_n = p_neg * self.compute_entropy(neg)
H_p = p_pos * self.compute_entropy(pos)
Ha = H_p + H... | compute_info_gain | identifier_name |
main.go | // Copyright 2014, Successfulmatch Inc. All rights reserved.
// Author TonyXu<tonycbcd@gmail.com>,
// Build on dev-0.0.1
// MIT Licensed
// The Go mysql proxy main model file.
package models
import (
"fmt"
"errors"
"strconv"
"sync"
"log"
"git.masontest.com/branches/gomysqlproxy/app/models/sc... | m.InitMain()
m.InitMysqlDB()
m.InitMysqlTable()
m.InitConnPooling()
if isUpdated {
// save mysql proxy.
err := redis.UpdateDB("main", redis.EncodeData(m), "MysqlProxy")
CheckError(err)
}
// panic(fmt.Sprintf("OK: %#v", m))
}
// get the table status.
func (m *Mys... | dLogHostStatus()
return proxy
}
// To init the necessary data.
func (m *MysqlProxy) Init() {
| identifier_body |
main.go | // Copyright 2014, Successfulmatch Inc. All rights reserved.
// Author TonyXu<tonycbcd@gmail.com>,
// Build on dev-0.0.1
// MIT Licensed
// The Go mysql proxy main model file.
package models
import (
"fmt"
"errors"
"strconv"
"sync"
"log"
"git.masontest.com/branches/gomysqlproxy/app/models/sc... | schema.MysqlShardTable{}
for _, id := range ids {
tbs, err := redis.ReadDB("MysqlShardTable", id)
if err != nil { return nil, err }
if len(tbs) != 1 { return nil, errors.New("no found the shard table for id: " + id) }
tb := tbs[0][id].(map[string]interface {})
sha... | tables := []* | identifier_name |
main.go | // Copyright 2014, Successfulmatch Inc. All rights reserved.
// Author TonyXu<tonycbcd@gmail.com>,
// Build on dev-0.0.1
// MIT Licensed
// The Go mysql proxy main model file.
package models
import (
"fmt"
"errors"
"strconv"
"sync"
"log"
"git.masontest.com/branches/gomysqlproxy/app/models/sc... | = shardDBs
}
// listen the sharddb change status.
locker := &sync.Mutex{}
go func() {
for {
newShardDB := <-schema.NewShardDBCh
locker.Lock()
defer locker.Unlock()
m.ShardDBIds = append(m.ShardDBIds, newShardDB.Id)
m.Sha... | if len(dbs) != 1 { panic("no found relation shard db for id:" + sid) }
sdb := dbs[0][sid].(map[string]interface {})
groupId := sdb["HostGroupId"].(string)
curGroup, err := host.GetHostGroupById(groupId)
CheckError(err)
shardDB := &sch... | conditional_block |
main.go | // Copyright 2014, Successfulmatch Inc. All rights reserved.
// Author TonyXu<tonycbcd@gmail.com>,
// Build on dev-0.0.1
// MIT Licensed
// The Go mysql proxy main model file.
package models
import (
"fmt"
"errors"
"strconv"
"sync"
"log"
"git.masontest.com/branches/gomysqlproxy/app/models/sc... | }
// to exel the sql
func (m *MysqlProxy) Exec(args []string, user *client.Client) (interface{}, error) {
execPlan, err := planbuilder.GetExecPlan(args, user)
if err != nil { return nil, err }
result, err := execPlan.Do()
if err != nil { return nil, err }
switch result.(type) {
case *sc... | schema.Tables = tables
m.TableIds = tableIds
return m.UpdateToRedisDB() | random_line_split |
test_framework.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2014-2019 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections imp... |
if all_ok:
return
time.sleep(0.1)
raise AssertionError("wait_for_quorum_phase timed out")
def wait_for_quorum_commitment(self, timeout = 15):
t = time.time()
while time.time() - t < timeout:
all_ok = True
for node in self.node... | if s[check_received_messages] < check_received_messages_count:
all_ok = False
break | conditional_block |
test_framework.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2014-2019 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections imp... | (self, node_from, node_to, amount, min_inputs, max_inputs):
assert (min_inputs <= max_inputs)
# fill inputs
inputs = []
balances = node_from.listunspent()
in_amount = 0.0
last_amount = 0.0
for tx in balances:
if len(inputs) < min_inputs:
... | create_raw_tx | identifier_name |
test_framework.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2014-2019 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections imp... |
assert num_nodes <= MAX_NODES
create_cache = False
for i in range(MAX_NODES):
if not os.path.isdir(os.path.join(cachedir, 'node' + str(i))):
create_cache = True
break
if create_cache:
self.log.debug("Creating data directories from... | Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
Afterward, create num_nodes copies from the cache.""" | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.