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 |
|---|---|---|---|---|
mod.rs | ,
Group = 3,
Part = 4,
Note = 5,
Layer = 6,
LayerItem = 7,
}
/// Represents the **Input** and **Output** **Element**s.
///
/// These are used when specifying which **Element** we're setting the properties of.
#[derive(Copy, Clone, Debug)]
pub enum Element {
Output = 0,
Input = 1,
}
/// A r... | {
// The audio buffer list to which input data is rendered.
buffer_list: *mut sys::AudioBufferList,
callback: *mut render_callback::InputProcFnWrapper,
}
macro_rules! try_os_status {
($expr:expr) => {
Error::from_os_status($expr)?
};
}
impl AudioUnit {
/// Construct a new AudioUnit wi... | InputCallback | identifier_name |
mod.rs | /enum.MusicDeviceType)
/// - [**GeneratorType**](./types/enum.GeneratorType)
/// - [**FormatConverterType**](./types/enum.FormatConverterType)
/// - [**EffectType**](./types/enum.EffectType)
/// - [**MixerType**](./types/enum.MixerType)
///
/// To construct the **AudioUnit** with some component ... | self.stream_format(Scope::Output)
}
| identifier_body | |
updater.go | := &Factory{}
return f, nil
}
// Configure implements [driver.Configurable].
func (f *Factory) | (_ context.Context, cf driver.ConfigUnmarshaler, c *http.Client) error {
f.c = c
var cfg FactoryConfig
if err := cf(&cfg); err != nil {
return fmt.Errorf("debian: factory configuration error: %w", err)
}
if cfg.ArchiveURL != "" || cfg.OVALURL != "" {
return fmt.Errorf("debian: neither archive_url nor oval_url... | Configure | identifier_name |
updater.go |
// Configure implements [driver.Configurable].
func (f *Factory) Configure(_ context.Context, cf driver.ConfigUnmarshaler, c *http.Client) error {
f.c = c
var cfg FactoryConfig
if err := cf(&cfg); err != nil {
return fmt.Errorf("debian: factory configuration error: %w", err)
}
if cfg.ArchiveURL != "" || cfg.O... | {
f := &Factory{}
return f, nil
} | identifier_body | |
updater.go | f := &Factory{}
return f, nil
}
// Configure implements [driver.Configurable].
func (f *Factory) Configure(_ context.Context, cf driver.ConfigUnmarshaler, c *http.Client) error {
f.c = c
var cfg FactoryConfig
if err := cf(&cfg); err != nil {
return fmt.Errorf("debian: factory configuration error: %w", err)
}
... | if cfg.DistsURL != "" || cfg.OVALURL != "" {
zlog.Error(ctx).Msg("configured with deprecated URLs")
return fmt.Errorf("debian: neither url nor dists_url should be used anymore; use json_url and dists_urls instead")
}
if cfg.JSONURL != "" {
u.jsonURL = cfg.JSONURL
zlog.Info | random_line_split | |
updater.go | MirrorURL should be used.
ArchiveURL string `json:"archive_url" yaml:"archive_url"`
MirrorURL string `json:"mirror_url" yaml:"mirror_url"`
// OVALURL is a URL to a collection of OVAL XML documents.
//
// Deprecated: Use JSONURL instead.
OVALURL string `json:"oval_url" yaml:"oval_url"`
// JSONURL is a URL to a ... | {
zlog.Info(ctx).Msg("fetching latest JSON database")
break
} | conditional_block | |
GA.js | crossoverMutationNum;
/** 任务处理时间结果集([迭代次数][染色体编号]) */
var resultData = [];
/**
* 初始化遗传算法
* @param _taskNum 任务数量
* @param _nodeNum 节点数量
* @param _iteratorNum 迭代次数
* @param _chromosomeNum 染色体数量
* @param _cp 染色体复制的比例
*/
(function initGA(_taskNum, _nodeNum, _iteratorNum, _chromosomeNum, _cp) {
// 参数校验
if ... |
}
/**
* 交叉生成{crossoverMutationNum}条染色体
* @param chromosomeMatrix 上一代染色体矩阵
*/
function cross(chromosomeMatrix) {
var newChromosomeMatrix = [];
for (var chromosomeIndex=0; chromosomeIndex<crossoverMutationNum; chromosomeIndex++) {
// 采用轮盘赌选择父母染色体
var chromosomeBaba = chromosomeMatrix[RWS(se... | romosomeMatrix);
} | identifier_name |
GA.js | MutationNum;
/** 任务处理时间结果集([迭代次数][染色体编号]) */
var resultData = [];
/**
* 初始化遗传算法
* @param _taskNum 任务数量
* @param _nodeNum 节点数量
* @param _iteratorNum 迭代次数
* @param _chromosomeNum 染色体数量
* @param _cp 染色体复制的比例
*/
(function initGA(_taskNum, _nodeNum, _iteratorNum, _chromosomeNum, _cp) {
// 参数校验
if (!checkPar... | /**
* 计算所有染色体的任务处理时间
* @param chromosomeMatrix
*/
function calTime_oneIt(chromosomeMatrix) {
resultData.push(calTaskLengthOfEachChromosome(chromosomeMatrix));
}
/**
* 计算每条染色体的任务长度
* @param chromosomeMatrix
*/
function calTaskLengthOfEachChromosome(chromosomeMatrix) {
var chromosomeTaskLengths = [];
... |
return newChromosomeMatrix;
}
| random_line_split |
GA.js | MutationNum;
/** 任务处理时间结果集([迭代次数][染色体编号]) */
var resultData = [];
/**
* 初始化遗传算法
* @param _taskNum 任务数量
* @param _nodeNum 节点数量
* @param _iteratorNum 迭代次数
* @param _chromosomeNum 染色体数量
* @param _cp 染色体复制的比例
*/
(function initGA(_taskNum, _nodeNum, _iteratorNum, _chromosomeNum, _cp) {
// 参数校验
if (!checkPar... | */
function copy(chromosomeMatrix, newChromosomeMatrix) {
// 寻找适应度最高的N条染色体的下标(N=染色体数量*复制比例)
var chromosomeIndexArr = maxN(adaptability, chromosomeNum*cp);
// 复制
for (var i=0; i<chromosomeIndexArr.len
gth; i++) {
var chromosome = chromosomeMatrix[chromosomeIndexArr[i]];
newChromosomeMat... | var temp = matrix[j-1];
matrix[j-1] = matrix[j];
matrix[j] = temp;
}
}
}
// 取最大的n个元素
var maxIndexArray = [];
for (var i=matrix.length-1; i>matrix.length-n-1; i--) {
maxIndexArray.push(matrix[i][0]);
}
return maxIndexArra... | identifier_body |
GA.js | MutationNum;
/** 任务处理时间结果集([迭代次数][染色体编号]) */
var resultData = [];
/**
* 初始化遗传算法
* @param _taskNum 任务数量
* @param _nodeNum 节点数量
* @param _iteratorNum 迭代次数
* @param _chromosomeNum 染色体数量
* @param _cp 染色体复制的比例
*/
(function initGA(_taskNum, _nodeNum, _iteratorNum, _chromosomeNum, _cp) {
// 参数校验
if (!checkPar... | x<crossoverMutationNum; chromosomeIndex++) {
// 采用轮盘赌选择父母染色体
var chromosomeBaba = chromosomeMatrix[RWS(selectionProbability)].slice(0);
var chromosomeMama = chromosomeMatrix[RWS(selectionProbability)].slice(0);
// 交叉
var crossIndex = random(0, taskNum-1);
chromosomeBaba.... | [];
for (var chromosomeIndex=0; chromosomeInde | conditional_block |
diagnostics.rs | on `str` (which is what you would like to do, to
// support calls with warning("aa") instead of warning(&"aa").
impl<'a, 'b> Printable<'a, 'b> for &'b str {
fn as_maybe_spanned(&'b self) -> MaybeSpanned<'a, &'b dyn Display> {
MaybeSpanned::WithoutSpan(self)
}
}
impl<'a, 'b, T: Display + 'b> Printable<... | let (start_term_pos, end_term_pos) =
line_fmt.actual_columns(&faulty_part_of_line).unwrap();
let term_width = end_term_pos - start_term_pos;
num_fmt.spaces(output.writer())?;
{
let mut output = ColorOutput::new(ou... | // - unwrap(.): both positions are guranteed to exist in the line since we just
// got them from the faulty line, which is a subset of the whole error line | random_line_split |
diagnostics.rs | const HIGHLIGHT_COLOR: Option<Color> = Some(Color::Cyan);
// TODO reimplement line truncation
/// Instead of writing errors, warnings and lints generated in the different
/// compiler stages directly to stdout, they are collected in this object.
///
/// This has several advantages:
/// - the output level can be adapt... | new | identifier_name | |
diagnostics.rs | .write(&mut **writer).ok();
}
#[allow(dead_code)]
pub fn warning<'a, 'b, T: Printable<'a, 'b> + ?Sized>(&self, kind: &'b T) {
self.emit(MessageLevel::Warning, kind.as_maybe_spanned())
}
#[allow(dead_code)]
pub fn error<'a, 'b, T: Printable<'a, 'b> + ?Sized>(&self, kind: &'b T) {
... | {
// TODO: get rid of this nonsense
// NOTE: it would actually be nice to condition the Position on the Line
// instead of AsciiFile. Thinking of this, we could actually just do
// `AsciiFile::new((span.as_str().as_bytes()))`. Meaning AsciiFile is
// not a file, but a View
... | identifier_body | |
LAB2_OpRes.py | _to_check = []
for e in G.edges():
# Associate the flow to the edge
u = e[0]
v = e[1]
f = G.edge[u][v]['flow']
edges_to_check.append({
'edge': e,
'flow': f
})
edges_to_check.sort(key = lambda x: x['flow'])
return edges_to_check
# ALGORITHM
# Computation starting time
initial_time = t... |
def empty_place(G, n):
'''
Verify that the position "n" of the "G" is empty
'''
return G.node[n]['name'] == None
def place_node(G, pos, name):
'''
Place the node "name" into the position "pos" of the topology "G"
'''
G.node[pos]['name'] = name
def node_position(G, n):
'''
| '''
Retrieve a copy for the given traffic matrix (avoid pointer references)
'''
res = []
for row in T:
res.append([])
for c in row:
res[-1].append(c)
return res | identifier_body |
LAB2_OpRes.py | flow'])
return edges_to_check
# ALGORITHM
# Computation starting time
initial_time = time.time()
# Print on the screen the traffic matrix content
tm.print_TM(traffic_matrix)
# If one of the deltas is equal to 1, I know for sure that the resulting topology has to be a ring
if delta_in == 1 or delta_out == 1:
... | # Result | random_line_split | |
LAB2_OpRes.py | _check = []
for e in G.edges():
# Associate the flow to the edge
u = e[0]
v = e[1]
f = G.edge[u][v]['flow']
edges_to_check.append({
'edge': e,
'flow': f
})
edges_to_check.sort(key = lambda x: x['flow'])
return edges_to_check
# ALGORITHM
# Computation starting time
initial_time = time... | (T):
'''
Retrieve a copy for the given traffic matrix (avoid pointer references)
'''
res = []
for row in T:
res.append([])
for c in row:
res[-1].append(c)
return res
def empty_place(G, n):
'''
Verify that the position "n" of the "G" is empty
'''
return G.node[n]['name'] == None
def pla... | copy_TM | identifier_name |
LAB2_OpRes.py | _to_check = []
for e in G.edges():
# Associate the flow to the edge
u = e[0]
v = e[1]
f = G.edge[u][v]['flow']
edges_to_check.append({
'edge': e,
'flow': f
})
edges_to_check.sort(key = lambda x: x['flow'])
return edges_to_check
# ALGORITHM
# Computation starting time
initial_time = t... |
# Result
return (s_res, d_res)
def copy_TM(T):
'''
Retrieve a copy for the given traffic matrix (avoid pointer references)
'''
res = []
for row in T:
res.append([])
for c in row:
res[-1].append(c)
return res
def empty_place(G, n):
'''
Verify that the position "n" of the "G" is empty
... | if T[s][d] > maxV:
# Update max values
maxV = T[s][d]
s_res = s
d_res = d | conditional_block |
tags.rs | 0x0141;
pub const BadFaxLines: u16 = 0x0146;
pub const CleanFaxData: u16 = 0x0147;
pub const ConsecutiveBadFaxLines: u16 = 0x0148;
pub const SubIFDs: u16 = 0x014A;
pub const InkSet: u16 = 0x014C;
pub const InkNames: u16 = 0x014D;
pub const NumberOfInks: u16 = 0x014E;
pub const DotRange: u16 = 0x0150;
pub const TargetPr... | pub const SubsecTimeOriginal: u16 = 0x9291; //Type.Ascii
pub const FocalPlaneXResolution: u16 = 0xa20e; //Type.Rational
pub const FocalPlaneYResolution: u16 = 0xa20f; //Type.Rational | random_line_split | |
node_test.go | },
{
name: "response missing trust domain bundle",
bootstrapBundle: caCert,
overrideSVIDUpdate: &node.X509SVIDUpdate{
Svids: map[string]*node.X509SVID{
"spiffe://domain.test/not/used": {CertChain: agentCert.Raw},
},
},
err: "failed to parse attestation response: missing trust do... | createServerCertificate | identifier_name | |
node_test.go | storeKey: testKey,
failAttestCall: true,
},
{
name: "malformed cached svid ignored",
bootstrapBundle: caCert,
cachedSVID: []byte("INVALID"),
storeKey: testKey,
failAttestCall: true,
err: "attestation has been purposefully failed",
},
{
name: ... | {
trustBundle = append(trustBundle, bootstrapCert)
} | conditional_block | |
node_test.go | response: expected 1 svid; got 2",
},
{
name: "response svid has invalid cert chain",
bootstrapBundle: caCert,
overrideSVIDUpdate: &node.X509SVIDUpdate{
Svids: map[string]*node.X509SVID{
"spiffe://domain.test/not/used": {CertChain: []byte("INVALID")},
},
},
err: "failed to pa... | {
var serverNA servernodeattestor.NodeAttestor
serverNADone := spiretest.LoadPlugin(t, catalog.MakePlugin("test",
servernodeattestor.PluginServer(fakeservernodeattestor.New("test", config)),
), &serverNA)
return serverNA, serverNADone
} | identifier_body | |
node_test.go |
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{
{
Certificate: [][]byte{serverCert.Raw},
PrivateKey: testKey,
},
},
}
testCases := []struct {
name string
challengeResponses []string
bootstrapBundle *x509.Certificate
insecureBootstrap... | serverCert := createServerCertificate(t, caCert)
agentCert := createAgentCertificate(t, caCert, "/test/foo")
expiredCert := createExpiredCertificate(t, caCert) | random_line_split | |
controllerserver.go | "context"
"fmt"
"strings"
"github.com/csi-driver/goofys-csi-driver/pkg/util"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang... | (ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
if len(req.GetVolumeId()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request")
}
if req.GetVolumeCapabilities() == nil {
return nil, status.Error(codes.InvalidArg... | ValidateVolumeCapabilities | identifier_name |
controllerserver.go | "
"fmt"
"strings"
"github.com/csi-driver/goofys-csi-driver/pkg/util"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grp... |
blobClient := client.GetBlobService()
container := blobClient.GetContainerReference(containerName)
_, err = container.CreateIfNotExists(&azstorage.CreateContainerOptions{Access: azstorage.ContainerAccessTypePrivate})
if err != nil {
return nil, fmt.Errorf("failed to create container(%s) on account(%s) type(%s) r... | {
return nil, err
} | conditional_block |
controllerserver.go | "context"
"fmt"
"strings"
"github.com/csi-driver/goofys-csi-driver/pkg/util"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang... |
volSizeBytes := int64(req.GetCapacityRange().GetRequiredBytes())
requestGiB := int(util.RoundUpGiB(volSizeBytes))
parameters := req.GetParameters()
var storageAccountType, resourceGroup, location, accountName, containerName string
// Apply ProvisionerParameters (case-insensitive). We leave validation of
// the... | }
if len(volumeCapabilities) == 0 {
return nil, status.Error(codes.InvalidArgument, "CreateVolume Volume capabilities must be provided")
} | random_line_split |
controllerserver.go | "
"fmt"
"strings"
"github.com/csi-driver/goofys-csi-driver/pkg/util"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grp... |
// ListVolumes return all available volumes
func (d *Driver) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// ControllerPublishVolume make a volume available on some required node
// N/A for goofys
func (d *Drive... | {
return nil, status.Error(codes.Unimplemented, "")
} | identifier_body |
root_mod_trait.rs | "example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally ... | fn root_module_statics() -> &'static RootModuleStatics<Self>;
/// Gets the root module,returning None if the module is not yet loaded.
#[inline]
fn get_module() -> Option<Self> {
Self::root_module_statics().root_mod.get()
}
/// Gets the RawLibrary of the module,
/// returning None ... | random_line_split | |
root_mod_trait.rs | example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally th... |
/// Gets the LibHeader of a library.
///
/// # Errors
///
/// This will return these errors:
///
/// - `LibraryError::GetSymbolError`:
/// If the root module was not exported.
///
/// - `LibraryError::InvalidAbiHeader`:
/// If the abi_stable used by the library is not compatible.
///
/// # Safety
///
/// The LibHeade... | {
let path = match where_ {
LibraryPath::Directory(directory) => M::get_library_path(directory),
LibraryPath::FullPath(full_path) => full_path.to_owned(),
};
RawLibrary::load_at(&path)
} | identifier_body |
root_mod_trait.rs | example_root_module";
/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!();
/// }
///
/// # fn main(){}
/// ```
pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static {
/// The name of the dynamic library,which is the same on all platforms.
/// This is generally th... | (
raw_library: &RawLibrary,
) -> Result<AbiHeaderRef, LibraryError> {
let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL;
let header: AbiHeaderRef = unsafe { *raw_library.get::<AbiHeaderRef>(mangled.as_bytes())? };
Ok(header)
}
/// Gets the LibHeader of the library at the path.
///
/// This leaks the unde... | abi_header_from_raw_library | identifier_name |
item_classifier.py | # Licence: MIT
#-------------------------------------------------------------------------------
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from random import randrange
IMG_HEIGHT ... | self.class_names = np.array([item.name for item in Path(self.img_dir).glob('*') if item.is_dir()])
def exists(self):
"""Checks saved model presence"""
return Path(self.model_dir).exists()
def load(self):
"""Load a model from directory"""
print("==> Loading model from", ... | """This class wraps around TF model
A stone images dataset made by cc/cc_gen.py is required for model training and prediction
"""
def __init__(self, model_dir, img_dir, img_size = (IMG_WIDTH, IMG_HEIGHT), log_dir = None):
"""Constructor.
Parameters:
model_dir Directory where a ... | identifier_body |
item_classifier.py | # Licence: MIT
#-------------------------------------------------------------------------------
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from random import randrange
IMG_HEIGHT ... |
callbacks = []
if self.log_dir is not None:
callbacks.extend([
tf.keras.callbacks.TensorBoard(self.log_dir,
profile_batch=0,
write_graph=True)])
if self.image_data_gen is ... | self.init_datasets() | conditional_block |
item_classifier.py | # Licence: MIT
#-------------------------------------------------------------------------------
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from random import randrange
IMG_HEIGHT ... |
def train(self, epochs = NUM_EPOCHS, display_history = False):
"""Train the model"""
print("==> Training model from", self.model_dir)
if self.model is None:
self.build()
if self.train_dataset is None:
self.init_datasets()
callbacks = []
if se... | subset='validation')
if display_samples:
self.display_sample_images() | random_line_split |
item_classifier.py | # Licence: MIT
#-------------------------------------------------------------------------------
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from random import randrange
IMG_HEIGHT ... | (self, display_samples = False):
"""Initialize datasets for training"""
print("==> Loading images from ", self.img_dir)
self.image_data_gen = ImageDataGenerator(
rescale=1./255,
#rotation_range=30,
#shear_range=30,
#width_shift_range=.15,
... | init_datasets | identifier_name |
engine_dcos.go | .Properties) string {
masterIPList, err := generateConsecutiveIPsList(p.MasterProfile.Count, p.MasterProfile.FirstConsecutiveStaticIP)
if err != nil {
return ""
}
for i, v := range masterIPList {
masterIPList[i] = " - " + v
}
str := getSingleLineDCOSCustomData(
p.OrchestratorProfile.OrchestratorType,
... | (cs *api.ContainerService) string {
masterAttributeContents := getDCOSMasterCustomNodeLabels()
masterPreprovisionExtension := ""
if cs.Properties.MasterProfile.PreprovisionExtension != nil {
masterPreprovisionExtension += "\n"
masterPreprovisionExtension += makeMasterExtensionScriptCommands(cs)
}
var bootstrap... | getDCOSMasterCustomData | identifier_name |
engine_dcos.go | .Properties) string {
masterIPList, err := generateConsecutiveIPsList(p.MasterProfile.Count, p.MasterProfile.FirstConsecutiveStaticIP)
if err != nil {
return ""
}
for i, v := range masterIPList {
masterIPList[i] = " - " + v
}
str := getSingleLineDCOSCustomData(
p.OrchestratorProfile.OrchestratorType,
... | "PREPROVISION_EXTENSION": masterPreprovisionExtension,
"ROLENAME": "master"})
return fmt.Sprintf("\"customData\": \"[base64(concat('#cloud-config\\n\\n', '%s'))]\",", str)
}
func getDCOSAgentProvisionScript(profile *api.AgentPoolProfile, orchProfile *api.OrchestratorProfile, bootstrapIP string) ... | {
masterAttributeContents := getDCOSMasterCustomNodeLabels()
masterPreprovisionExtension := ""
if cs.Properties.MasterProfile.PreprovisionExtension != nil {
masterPreprovisionExtension += "\n"
masterPreprovisionExtension += makeMasterExtensionScriptCommands(cs)
}
var bootstrapIP string
if cs.Properties.Orches... | identifier_body |
engine_dcos.go |
provisionScript := string(bp)
if strings.Contains(provisionScript, "'") {
panic(fmt.Sprintf("BUG: %s may not contain character '", script))
}
return strings.Replace(strings.Replace(provisionScript, "\r\n", "\n", -1), "\n", "\n\n ", -1)
}
func getDCOSBootstrapCustomData(p *api.Properties) string {
masterIP... | {
panic(fmt.Sprintf("BUG: %s", err.Error()))
} | conditional_block | |
engine_dcos.go | .Properties) string {
masterIPList, err := generateConsecutiveIPsList(p.MasterProfile.Count, p.MasterProfile.FirstConsecutiveStaticIP)
if err != nil {
return ""
}
for i, v := range masterIPList {
masterIPList[i] = " - " + v
}
str := getSingleLineDCOSCustomData(
p.OrchestratorProfile.OrchestratorType,
... | yamlStr = string(jsonBytes)
// convert to one line
yamlStr = strings.Replace(yamlStr, "\\", "\\\\", -1)
yamlStr = strings.Replace(yamlStr, "\r\n", "\\n", -1)
yamlStr = strings.Replace(yamlStr, "\n", "\\n", -1)
yamlStr = strings.Replace(yamlStr, "\"", "\\\"", -1)
// variable replacement
rVariable, e1 := regexp... | panic(fmt.Sprintf("BUG: %s", err4.Error()))
} | random_line_split |
sim_controller.py | )
self.data.set_rx_time_delay(tof)
id = i+1
self.data.set_rx_team_id(id)
if self.DEBUG:
print 'tx_loc: ', tx_loc
print 'rx_loc: ', rx_loc
print 'time: ', repr(tof)
print 'id: ', id
def rx_beacon_packe... | # # f = open('location_history','w+')
# for i in self.all_locations:
# print repr(i[0][0][0]), repr(i[0][0][1]))
# # f.write(repr(i)+'\n')
# print '\n\n\n\n\n\n\n'
# print len(i)
# # f.close()
# kml_write = sdr_kml_writer.kml_writer()
... | random_line_split | |
sim_controller.py |
def init_sim(self,n):
"""
initialize simulation for n receivers.
"""
self.beacon = beacon(ENABLE_BEACON_DELAY)
self.data = data_utils(n)
random.seed()
if n < 3:
print 'Number of receivers %i is less than three.' %n
print 'Simulatio... | """__init__"""
self.geo_utils = geo_utils()
self.DEBUG = True
self.rx_number = 4
self.packet_number = 0
self.iterator = 1
self.packet_error_rate = 0.1
self.all_locations = [] | identifier_body | |
sim_controller.py | )
self.data.set_rx_time_delay(tof)
id = i+1
self.data.set_rx_team_id(id)
if self.DEBUG:
print 'tx_loc: ', tx_loc
print 'rx_loc: ', rx_loc
print 'time: ', repr(tof)
print 'id: ', id
def | (self):
"""
receive a single beacon packet. this will then be copied n times.
this tries to ensure clock synchronization across receivers.
"""
self.beacon.make_packet()
rx_packet = self.beacon.tx_packet()
rx_time = np.float128('%.20f'%(time.time()))
... | rx_beacon_packet | identifier_name |
sim_controller.py | )
self.data.set_rx_time_delay(tof)
id = i+1
self.data.set_rx_team_id(id)
if self.DEBUG:
print 'tx_loc: ', tx_loc
print 'rx_loc: ', rx_loc
print 'time: ', repr(tof)
print 'id: ', id
def rx_beacon_packe... |
self.data.set_timestamp_base(rx_time)
self.data.set_beacon_packet(rx_packet)
def receiver_chain(self,h):
"""
simulate receiver chain for n repeaters
"""
self.host = h
n = self.data.get_rx_number()
beacon_packet = self.data.get_beacon_packet()
... | print 'rx_time: ', repr(rx_time) | conditional_block |
typescript.ts | config.json file.
*
* @default "tsconfig.dev.json"
*/
readonly tsconfigDevFile?: string;
/**
* Do not generate a `tsconfig.json` file (used by jsii projects since
* tsconfig.json is generated by the jsii compiler).
*
* @default false
*/
readonly disableTsconfig?: boolean;
/**
* Do no... | {
new TypedocDocgen(this);
} | conditional_block | |
typescript.ts | });
this.testdir = options.testdir ?? "test";
this.gitignore.include(`/${this.testdir}/`);
this.npmignore?.exclude(`/${this.testdir}/`);
// if the test directory is under `src/`, then we will run our tests against
// the javascript files and not let jest compile it for us.
const compiledTests... | SampleCode | identifier_name | |
typescript.ts | in the background",
exec: "tsc --build -w",
});
this.testdir = options.testdir ?? "test";
this.gitignore.include(`/${this.testdir}/`);
this.npmignore?.exclude(`/${this.testdir}/`);
// if the test directory is under `src/`, then we will run our tests against
// the javascript files and n... | {
this.addDevDeps(
`@types/jest${jest.jestVersion}`,
`ts-jest${jest.jestVersion}`
);
jest.addTestMatch(`<rootDir>/${this.srcdir}/**/__tests__/**/*.ts?(x)`);
jest.addTestMatch(
`<rootDir>/(${this.testdir}|${this.srcdir})/**/*(*.)@(spec|test).ts?(x)`
);
// add relevant deps
... | identifier_body | |
typescript.ts | ?: string;
/**
* Custom TSConfig
* @default - default options
*/
readonly tsconfig?: TypescriptConfigOptions;
/**
* Custom tsconfig options for the development tsconfig.json file (used for testing).
* @default - use the production tsconfig options
*/
readonly tsconfigDev?: TypescriptConfigOp... | this.tsconfigDev = new TypescriptConfig(
this,
mergeTsconfigOptions(
{
fileName: tsconfigDevFile,
include: [
PROJEN_RC,
`${this.srcdir}/**/*.ts`,
`${this.testdir}/**/*.ts`,
],
exclude: ["node_module... | } else {
const tsconfigDevFile = options.tsconfigDevFile ?? "tsconfig.dev.json"; | random_line_split |
builder.py | Dog(QThread):
"""
watching ./gl directory, on modified, call given bark_callback
running on separated thread
"""
bark = pyqtSignal()
def __init__(self, bark_callback):
super(WatchDog, self).__init__()
self.ehandler = FSEventHandler(self.on_watch)
self.bark.connect(bark_... | self.to_capture_buffer_in = True | conditional_block | |
builder.py | 1920, 1080
record_width, record_height = 1920, 1088
def log(*arg):
"""
wraps built-in print for additional extendability
"""
context = str(*arg)
print("[Texture Builder] {}".format(context))
class FSEventHandler(FileSystemEventHandler):
"""
simple file system event handler for watchdog ... | (cls, gl, program):
"""
generate simplest screen filling quad
"""
vbo = [
-1.0, -1.0,
+1.0, -1.0,
-1.0, +1.0,
+1.0, +1.0,
]
vbo = np.array(vbo).astype(np.float32)
vbo = [(gl.buffer(vbo), "2f", "in_pos")]
ib... | screen_vao | identifier_name |
builder.py | .bark.emit()
def run(self):
"""
start oberserver in another separated thread, and WatchDog thread only monitors it
"""
observer = Observer()
observer.schedule(self.ehandler, "./gl", True)
observer.start()
observer.join()
class GLUtil(object):
"""
s... | def main():
app = QtWidgets.QApplication([])
renderer = Renderer()
renderer.show() | random_line_split | |
builder.py | 1920, 1080
record_width, record_height = 1920, 1088
def log(*arg):
"""
wraps built-in print for additional extendability
"""
context = str(*arg)
print("[Texture Builder] {}".format(context))
class FSEventHandler(FileSystemEventHandler):
"""
simple file system event handler for watchdog ... |
def get_filepath(self, template):
i = 0
file_name = template.format(i)
while os.path.exists(file_name):
i += 1
file_name = template.format(i)
return file_name
def build_prog(self, gl):
"""
.
"""
prog = gl.program(
... | super(Renderer, self).__init__()
self.setMinimumSize(width, height)
self.setMaximumSize(width, height)
self.setWindowFlag(Qt.WindowStaysOnTopHint)
self.watchdog = WatchDog(self.recompile)
self.watchdog.start() | identifier_body |
wine_recommender.py | : data: list, cust_tag_bridge_rdd: spark rdd
Output: clean_data_rdd, spark rdd'''
data_rdd = sc.parallelize(data)
tag_data_bridge_rdd = data_rdd.map(lambda row: (row[0], (row[1], row[2]) ))
clean_data_rdd = \
tag_data_bridge_rdd.sortByKey()\
.join( cust_tag_bridge_rdd.s... |
elif local == False:
print "Create spark context for remote cluster..."
sc = pyspark.SparkContext(master = remote_cluster_path)
return
else:
print "ERROR: local is set to False, however remote_cluster_path is not specified!"
def get_clean_data_rdd(sc, return_cust_brige_rdd = F... | print "Create spark context for local cluster..."
sc = pyspark.SparkContext(master = "local[{}]".format(n_worker_cups))
return sc | conditional_block |
wine_recommender.py | Input: data: list, cust_tag_bridge_rdd: spark rdd
Output: clean_data_rdd, spark rdd'''
data_rdd = sc.parallelize(data)
tag_data_bridge_rdd = data_rdd.map(lambda row: (row[0], (row[1], row[2]) ))
clean_data_rdd = \
tag_data_bridge_rdd.sortByKey()\
.join( cust_tag_bridge... | iterations = 30
regularization_parameter = 0.1
rank = 20
model = ALS.train(training_RDD,
rank=rank,
seed=seed,
iterations=iterations,
lambda_=regularization_parameter,
nonnegative=True)
... | # TODO: still need to optimize hyperparameters in a grid search
seed = 5L | random_line_split |
wine_recommender.py | dd: spark rdd
Output: clean_data_rdd, spark rdd'''
data_rdd = sc.parallelize(data)
tag_data_bridge_rdd = data_rdd.map(lambda row: (row[0], (row[1], row[2]) ))
clean_data_rdd = \
tag_data_bridge_rdd.sortByKey()\
.join( cust_tag_bridge_rdd.sortByKey())\
... | '''Checks if top variatls have at lease 3 wines'''
cnt = 0
for row in most_common_varietals:
if row[1] >= 3:
cnt += 1
return cnt | identifier_body | |
wine_recommender.py | : data: list, cust_tag_bridge_rdd: spark rdd
Output: clean_data_rdd, spark rdd'''
data_rdd = sc.parallelize(data)
tag_data_bridge_rdd = data_rdd.map(lambda row: (row[0], (row[1], row[2]) ))
clean_data_rdd = \
tag_data_bridge_rdd.sortByKey()\
.join( cust_tag_bridge_rdd.s... | (most_common_varietals):
'''Checks if top variatls have at lease 3 wines'''
cnt = 0
for row in most_common_varietals:
if row[1] >= | check_top_varietal_wine_count | identifier_name |
Helicopter-OMO.py | .loans.append({
'amount': amt,
'i': self.i
})
self.accounts[customer.id] += amt #Increase liabilities
return amt #How much you actually borrowed
#Returns the amount you actually pay – the lesser of amt or your outstanding balance
def amortize(self, customer, amt):
if |
def step(self, stage):
self.lastWithdrawal = 0
for l in self.credit: self.credit[l].step()
#Pay interest on deposits
lia = self.liabilities
profit = self.assets - lia
if profit > self.model.param('agents_agent'):
print('Disbursing profit of $',profit)
for id, a in self.accounts.items():
sel... | amt < 0.001: return 0 #Skip blanks and float errors
l = self.credit[customer.id] #Your loan object
l.amortizeAmt += amt #Count it toward minimum repayment
leftover = amt
#Reduce assets; amortize in the order borrowed
while leftover > 0 and len(l.loans) > 0:
if leftover >= l.loans[0]['amount']:
... | identifier_body |
Helicopter-OMO.py | #Remember the price from this period before altering it for the next period
self.inflation = (19 * self.inflation + inflation) / 20 #Decaying average
#Set interest rate and/or minimum repayment schedule
#Count potential borrowing in the interest rate adjustment
targeti = self.i * self.targetRR / (self.reser... | er(model | identifier_name | |
Helicopter-OMO.py | ed, breed.title()+' Target Balances', d.color2)
heli.addSeries('rbal', 'rBal-'+breed, breed.title()+ 'Real Balances', d.color)
heli.addSeries('inventory', 'invTarget-'+AgentGoods[breed], AgentGoods[breed].title()+' Inventory Target', heli.goods[AgentGoods[breed]].color2)
heli.addSeries('capital', 'portion-'+AgentGoo... | # Central Bank
# | random_line_split | |
Helicopter-OMO.py | .loans.append({
'amount': amt,
'i': self.i
})
self.accounts[customer.id] += amt #Increase liabilities
return amt #How much you actually borrowed
#Returns the amount you actually pay – the lesser of amt or your outstanding balance
def amortize(self, customer, amt):
if amt < 0.001: return 0 #... | if self.i < self.inflation + 0.005: self.i = self.inflation + 0.005 #no negative real rates
if self.i < 0.005: self.i = 0.005 #no negative nominal rates
class Loan():
def __init__(self, customer, bank):
self.customer = customer
self.bank = bank
self.loans = []
self.amortizeAmt = 0
@property
d... | lf.i = 1 + self.inflation #interest rate cap at 100%
| conditional_block |
shared.go | .RPCClient | testCore *core.Core
)
// We use this to wrap tests
func TestWrapper(runner func() int) int {
fmt.Println("Running with integration TestWrapper (rpc/tendermint/test/shared_test.go)...")
ffs := fixtures.NewFileFixtures("burrow")
defer func() {
// Tendermint likes to try and save to priv_validator.json af... | httpClient client.RPCClient
clients map[string]client.RPCClient | random_line_split |
shared.go | PCClient
httpClient client.RPCClient
clients map[string]client.RPCClient
testCore *core.Core
)
// We use this to wrap tests
func TestWrapper(runner func() int) int {
fmt.Println("Running with integration TestWrapper (rpc/tendermint/test/shared_test.go)...")
ffs := fixtures.NewFileFixture... | (account *acm.PrivAccount) *genesis.GenesisValidator {
return &genesis.GenesisValidator{
Amount: 1000000,
Name: fmt.Sprintf("full-account_%X", account.Address),
PubKey: account.PubKey,
UnbondTo: []genesis.BasicAccount{
{
Address: account.Address,
Amount: 100,
},
},
}
}
func genesisAccountF... | genesisValidatorFromPrivAccount | identifier_name |
shared.go | }
genesisBytes, err := genesisFileBytesFromUsers(chainID, users)
if err != nil {
return err
}
testConfigFile := ffs.AddFile("config.toml", string(configBytes))
rootWorkDir = ffs.AddDir("rootWorkDir")
rootDataDir := ffs.AddDir("rootDataDir")
genesisFile := ffs.AddFile("rootWorkDir/genesis.json", string(genesi... | {
t.Fatal(err)
} | conditional_block | |
shared.go | time.Sleep(time.Second)
ffs.RemoveAll()
}()
vm.SetDebug(true)
err := initGlobalVariables(ffs)
if err != nil {
panic(err)
}
tmServer, err := testCore.NewGatewayTendermint(serverConfig)
defer func() {
// Shutdown -- make sure we don't hit a race on ffs.RemoveAll
tmServer.Shutdown()
testCore.Stop()
}... | {
resp, err := edbcli.CallCode(client, fromAddress, code, data)
if err != nil {
t.Fatal(err)
}
ret := resp.Return
// NOTE: we don't flip memory when it comes out of RETURN (?!)
if bytes.Compare(ret, word256.LeftPadWord256(expected).Bytes()) != 0 {
t.Fatalf("Conflicting return value. Got %x, expected %x", ret,... | identifier_body | |
BaseRole.js | // private testScale(ary):void
// {
// var roleID = ary[0];
// var sca = ary[1];
// if(this.roleVo && this.roleVo.id == roleID)
// {
// var s:number = this.roleVo.isEnemy ? 1 : -1;
// this.skeletonAni.scaleX = s * sca;
// this.skeletonAni.scaleY =... | var _this = _super.call(this) || this;
_this.templet = null;
_this.skeletonAni = null;
_this.aniCount = 0;
_this.aniScale = 1;
_this.LblName = null;
_this.roleBloodBar = null;
_this.showPriority = 0;
_this.showBloodBar = false;
_this.clipShad... | identifier_body | |
BaseRole.js | ) || this;
_this.templet = null;
_this.skeletonAni = null;
_this.aniCount = 0;
_this.aniScale = 1;
_this.LblName = null;
_this.roleBloodBar = null;
_this.showPriority = 0;
_this.showBloodBar = false;
_this.clipShadow = new Laya.Image("comp/img_shad... | @param aniID 动画id
*/
BaseRole.prototype.aniPlay = function (aniID, loop, caller, method, defRole) {
this.aniId = aniID;
this.loop = loop;
this.caller = caller;
this.method = method;
this.defRole = defRole;
if (this.isLoaded) {
loop = loop === undefine... | setAttribute(40,"#ff0000");
// floatFontTip.show(tipString,this,-30,-200,0.5,40,80,this.baseRoleVo.isEnemy);
floatFontTip.showFlontClip(tipString, this, -30, -200, 0.5, 40, 80, this.baseRoleVo.isEnemy);
}
};
/**
*
* | conditional_block |
BaseRole.js |
var _this = _super.call(this) || this;
_this.templet = null;
_this.skeletonAni = null;
_this.aniCount = 0;
_this.aniScale = 1;
_this.LblName = null;
_this.roleBloodBar = null;
_this.showPriority = 0;
_this.showBloodBar = false;
_this.clipS... | Role() { | identifier_name | |
BaseRole.js | ) || this;
_this.templet = null;
_this.skeletonAni = null;
_this.aniCount = 0;
_this.aniScale = 1;
_this.LblName = null;
_this.roleBloodBar = null;
_this.showPriority = 0;
_this.showBloodBar = false;
_this.clipShadow = new Laya.Image("comp/img_shad... | };
BaseRole.prototype.setVis = function (bool) {
//延迟回调判断,复活就设置隐藏
if | BaseRole.prototype.setVisible = function (bool) {
// Laya.timer.once(1000 / GameConfig.BATTLE_ADDSPEED_TIMES,this, this.setVis,[bool]);
Laya.timer.once(1000, this, this.setVis, [bool]); | random_line_split |
preprocessorImpl.go | a macro.")
return args, false
}
if level == 0 {
switch reader.Peek().Info.Token {
case OpRParen:
args = append(args, arg)
return args, true
case OpLParen:
level++
arg = append(arg, reader.Next())
continue
case ast.BoComma:
reader.Next()
args = append(args, arg)
arg = ... | }
} else {
list = append(list, newTokenExpansion(args[i])) | random_line_split | |
preprocessorImpl.go | t = r.next.Peek()
}
return
}
// processList is a helper function for processMacro. It calls processMacro on all tokens in the
// list.
func (p *preprocessorImpl) processList(r *listReader) (result []tokenExpansion) {
for len(r.list) > 0 {
token := r.Next()
result = append(result, p.processMacro(token, r)...)
... |
}
// Macro argument pre-expansion
for i := range args {
args[i] = p.processList(&listReader{args[i], nil})
}
set := intersect(macro.HideSet, lastTok.HideSet)
return args, set
}
// processMacro checks t for macro definitions and fully expands it. reader is an interface to
// the following tokens, needed for... | {
args = append(args, nil)
} | conditional_block |
preprocessorImpl.go |
func (r *listReader) Peek() (t tokenExpansion) {
if len(r.list) > 0 {
t = r.list[0]
} else if r.next != nil {
t = r.next.Peek()
}
return
}
// processList is a helper function for processMacro. It calls processMacro on all tokens in the
// list.
func (p *preprocessorImpl) processList(r *listReader) (result []t... | {
if len(r.list) > 0 {
t = r.list[0]
r.list = r.list[1:]
} else if r.next != nil {
t = r.next.Next()
}
return
} | identifier_body | |
preprocessorImpl.go | () []Extension {
return p.extensions
}
func (p *preprocessorImpl) Errors() []error {
return ast.ConcatErrors(p.lexer.err.GetErrors(), p.err.GetErrors())
}
// skipping returnes true if we should skip this token. We skip if any of the #if directives in
// the stack says we should skip.
func (p *preprocessorImpl) skip... | Extensions | identifier_name | |
auto_chords.go | 2, 3, 7, 10}
c_iv7 = intervals{0, 3, 5, 8}
c_VI7 = intervals{0, 3, 7, 8}
c_vii_7 = intervals{2, 5, 8, 10}
)
var tonicChords = []intervals{
c_I,
}
var subDominantChords = []intervals{
c_ii7,
c_IV7,
}
var dominantChords = []intervals{
c_V7,
c_vii_dim_7,
}
var otherChords = []intervals{
c_iii7,
... | (minor bool, function int) []intervals {
if minor {
return nil
} else {
switch function {
case funcTonic:
return []intervals{
c_vi7,
c_I6,
}
case funcDom:
return []intervals{
c_ii7b5,
c_bIII_aug_7,
c_V7sus4,
}
}
}
return nil
}
func middleFunctions(prevFunction int, nextFu... | substituteChords | identifier_name |
auto_chords.go | {2, 3, 7, 10}
c_iv7 = intervals{0, 3, 5, 8}
c_VI7 = intervals{0, 3, 7, 8}
c_vii_7 = intervals{2, 5, 8, 10}
)
var tonicChords = []intervals{
c_I,
}
var subDominantChords = []intervals{
c_ii7,
c_IV7,
}
var dominantChords = []intervals{
c_V7,
c_vii_dim_7,
}
var otherChords = []intervals{
c_iii7,
... | break
}
}
if chromaticNote != 0 {
r := float64(0)
for i := len(scale) - 1; i >= 0; i-- {
if r == 0 ||
math.Abs(scale[i]-chromaticNote) < math.Abs(r-chromaticNote) {
r = scale[i]
}
}
requiredNotes = append(requiredNotes, r)
}
for attempts := 0; ; attempts++ {
function := nextFunction(p... | {
scale := s_Major.Add(a.TonicPitch).Expand()
if a.Minor {
scale = s_Minor.Add(a.TonicPitch).Expand()
}
var chromaticNote float64
var requiredNotes []float64
for i := range prevChord {
found := false
for j := range scale {
if prevChord[i] == scale[j] {
found = true
break
} else if prevChord[i... | identifier_body |
auto_chords.go | Function {
case funcTonic:
funcs = []int{funcSubDom, funcDom, funcOther}
case funcSubDom:
funcs = []int{funcTonic, funcDom, funcOther}
case funcDom:
funcs = []int{funcTonic}
case funcOther:
funcs = []int{funcTonic, funcSubDom, funcDom}
default:
panic("no")
}
return funcs
}
func nextFunction(currentFun... | {
n -= 12
} | conditional_block | |
auto_chords.go | {2, 3, 7, 10}
c_iv7 = intervals{0, 3, 5, 8}
c_VI7 = intervals{0, 3, 7, 8}
c_vii_7 = intervals{2, 5, 8, 10}
)
var tonicChords = []intervals{
c_I,
}
var subDominantChords = []intervals{
c_ii7,
c_IV7,
}
var dominantChords = []intervals{
c_V7,
c_vii_dim_7,
}
var otherChords = []intervals{
c_iii7,
... | }
if minDistChord == nil || dist < minDist {
minDist = dist
minDistChord = c1
}
}
return minDistChord
}
const chordDuration = 96000
const microOffset = 0.5
func (a *autoChord) progression(reps int, length int, prevBass float64, prevFunction int, prevChord intervals) (es []aujo.Event, lastBass float64,... | dist += 100
} | random_line_split |
shopping-list.reducer.ts | /api/store/createReducer#description
*!/
export interface ActionReducer<T, V extends Action = Action> {
(state: T | undefined, action: V): T; // <<<<<<<<<<<<<<<<<<<<<<<<< hmmmmmm... 'state', 'action'
}
--------
...but, hmm, apparently that does not make them required, reserved words. ok. (MBU)
********************... | return {
...ngrxState,
ingredients: [
...ngrxState.ingredients,
/* No. This puts an array into this array. Not What You Want.
ngrxAction.myPayload // Nope.
*/
...ngrxAction.myPayload
// << Yes. T... | {
switch (ngrxAction.type) {
/* WAS: 'string'
case 'ADD_INGREDIENT_ACTION':
NOW: const
*/
case MyShoppingListActions.ADD_INGREDIENT_ACTION:
// Do NOT mutate the existing state!! Get a COPY, work on that
return { // reducer returns a new state!
...ngrxState, ... | identifier_body |
shopping-list.reducer.ts | /api/store/createReducer#description
*!/
export interface ActionReducer<T, V extends Action = Action> {
(state: T | undefined, action: V): T; // <<<<<<<<<<<<<<<<<<<<<<<<< hmmmmmm... 'state', 'action'
}
--------
...but, hmm, apparently that does not make them required, reserved words. ok. (MBU)
********************... | (
ngrxState = initialStateShoppingListPart, // ngrxState will get initialState if null
// state = initialState, // state will get initialState if null
/*
action: Action, // No longer used. This was just NgRx Action interface
*/
/* When there was only One Action:
action: MyShoppingListActions.AddIngred... | shoppingListReducer | identifier_name |
shopping-list.reducer.ts | <T, V extends Action = Action> {
(state: T | undefined, action: V): T; // <<<<<<<<<<<<<<<<<<<<<<<<< hmmmmmm... 'state', 'action'
}
--------
...but, hmm, apparently that does not make them required, reserved words. ok. (MBU)
***************************************
*/
export function shoppingListReducer (
ngrxSt... | ingredients: ngrxState.ingredients.filter(
(nextIngredient, nextIngredientIndex) => {
return nextIngredientIndex !== ngrxState.myBeingEditedIngredientIndex; // << PART of STATE = good | random_line_split | |
Runner.ts | LandRequestQueue,
private history: LandRequestHistory,
private client: BitbucketClient,
private config: Config,
) {
// call our checkWaitingLandRequests() function on an interval so that we are always clearing out waiting builds
const timeBetweenChecksMins = 2;
setInterval(() => {
this.... | triggererAaid: landRequestOptions.triggererAaid,
pullRequestId: pr.prId,
forCommit: landRequestOptions.commit,
});
}
async removeLandRequestByPullRequestId(pullRequestId: number, user: ISessionUser) {
const requests = await LandRequest.findAll<LandRequest>({
where: {
pullReq... | authorAaid: landRequestOptions.prAuthorAaid,
title: landRequestOptions.prTitle,
}));
return await LandRequest.create<LandRequest>({ | random_line_split |
Runner.ts | LandRequestQueue,
private history: LandRequestHistory,
private client: BitbucketClient,
private config: Config,
) {
// call our checkWaitingLandRequests() function on an interval so that we are always clearing out waiting builds
const timeBetweenChecksMins = 2;
setInterval(() => {
this.... | private getPauseState = async (): Promise<IPauseState> => {
const state = await PauseStateTransition.findOne<PauseStateTransition>({
order: [['date', 'DESC']],
});
if (!state) {
return {
id: '_',
date: new Date(0),
paused: false,
pauserAaid: '',
reason: ... | await PauseStateTransition.create<PauseStateTransition>({
paused: false,
pauserAaid: user.aaid,
});
}
| identifier_body |
Runner.ts | RequestQueue,
private history: LandRequestHistory,
private client: BitbucketClient,
private config: Config,
) {
// call our checkWaitingLandRequests() function on an interval so that we are always clearing out waiting builds
const timeBetweenChecksMins = 2;
setInterval(() => {
this.check... | {
Logger.info('Checking for waiting landrequests ready to queue');
for (let landRequest of await this.queue.getStatusesForWaitingRequests()) {
const pullRequestId = landRequest.request.pullRequestId;
let isAllowedToLand = await this.client.isAllowedToLand(pullRequestId);
if (isAllowedToLand... | eckWaitingLandRequests() | identifier_name |
client_iface.go | queue.bolt"
tables = []string{
TableMetadata,
TablePackages,
TableToCrawl,
TablePendingReferences,
TableCrawlResults,
}
qTables = []string{
TableToCrawl,
TableCrawlResults,
}
// pkgSepB is a byte array of the package component separator character.
// It's used for hierarchical searches and lookup... | db, err := bolt.Open(queueFile, 0600, NewBoltConfig("").BoltOptions)
if err != nil {
panic(fmt.Errorf("Creating bolt queue: %s", err))
}
q := NewBoltQueue(db)
return newKVClient(be, q)
case Postgres:
be := NewPostgresBackend(config.(*PostgresConfig))
q := NewPostgresQueue(config.(*PostgresConfig))
... | {
typ := config.Type()
switch typ {
case Bolt:
be := NewBoltBackend(config.(*BoltConfig))
// TODO: Return an error instead of panicking.
if err := be.Open(); err != nil {
panic(fmt.Errorf("Opening bolt backend: %s", err))
}
q := NewBoltQueue(be.db)
return newKVClient(be, q)
case Rocks:
// MORE TE... | identifier_body |
client_iface.go | rawlResults,
}
qTables = []string{
TableToCrawl,
TableCrawlResults,
}
// pkgSepB is a byte array of the package component separator character.
// It's used for hierarchical searches and lookups.
pkgSepB = []byte{'/'}
)
type Client interface {
Open() error ... | KVTables | identifier_name | |
client_iface.go | TablePackages = "packages"
TablePendingReferences = "pending-references"
TableCrawlResults = "crawl-result"
TableToCrawl = "to-crawl"
MaxPriority = 10 // Number of supported priorities, 1-indexed.
)
var (
ErrKeyNotFound = errors.New("requested key not found")
ErrNotImplem... | TableMetadata = "andromeda-metadata" | random_line_split | |
client_iface.go | queue.bolt"
tables = []string{
TableMetadata,
TablePackages,
TableToCrawl,
TablePendingReferences,
TableCrawlResults,
}
qTables = []string{
TableToCrawl,
TableCrawlResults,
}
// pkgSepB is a byte array of the package component separator character.
// It's used for hierarchical searches and lookup... |
return
}
// kvTables returns the names of the "regular" key-value tables.
func kvTables() []string {
kv := []string{}
for _, table := range tables {
regular := true
for _, qTable := range qTables {
if table == qTable {
regular = false
break
}
| {
return
} | conditional_block |
center-control.js | = fly.Component.extend({
name: 'router-view',
template: fly.template(__inline('./center-control.html')),
ctor: function (element, options) {
this._super(element, options);
that = this;
// var socket = this.socket = io.connect('http://localhost:1414');
// console.log(socket);... | r: 100,
scale: true
}
],
series : [
{
name:'bubbleGraphGreen',
type:'scatter',
symbolSize: function (value){
return Math.round(value[2] / 5);
},
itemStyle : {
... | }
},
// legend: {
// data:['scatter1','scatter2']
// },
xAxis : [
{
type : 'value',
show: false,
splitNumber: 100,
scale: true
}
],
yAxis : [
{
... | conditional_block |
center-control.js | .exports = fly.Component.extend({
name: 'router-view',
template: fly.template(__inline('./center-control.html')),
ctor: function (element, options) {
this._super(element, options);
that = this;
// var socket = this.socket = io.connect('http://localhost:1414');
// console.log(... | init();
// bubble graph
var agencyUnits = ['省文化厅','省教育厅','省财政厅','省地震局','合肥市','省气象局','安庆市','省体育局','省农科院','省管局','省质监局','淮南市','淮北市','省司法厅','毫州市','省林业厅'];
function random(){
var r = Math.round(Math.random() * 700);//这个数据代表了气泡大小
return (r * (r % 2 == 0 ? 1 : -1));
}
function randomRadius(){
var r = Math.round(M... | // init();
// } | random_line_split |
center-control.js | = fly.Component.extend({
name: 'router-view',
template: fly.template(__inline('./center-control.html')),
ctor: function (element, options) {
this._super(element, options);
that = this;
// var socket = this.socket = io.connect('http://localhost:1414');
// console.log(socket);... | ar d = [];
var len = 20; //这个值就代表了气泡数量,scatter1显示20个,scatter2显示20个,一共显示40个
while (len--) {
d.push([
random(),
random(), //前面两个数据是气泡圆心坐标位置
// Math.abs(random()), //这个数据为什么要绝对值,因为这个是气泡半径值,也就是气泡大小
randomRadius(), //这个数据为什么要绝对值,因为这个是气泡半径值,也就是气泡大小
]);
... |
v | identifier_name |
center-control.js | = fly.Component.extend({
name: 'router-view',
template: fly.template(__inline('./center-control.html')),
ctor: function (element, options) {
this._super(element, options);
that = this;
// var socket = this.socket = io.connect('http://localhost:1414');
// console.log(socket);... | {
type : 'value',
show: false,
splitNumber: 100,
scale: true
}
],
series : [
{
name:'bubbleGraphGreen',
type:'scatter',
symbolSize: function (value){
... | rue,
type : 'cross',
lineStyle: {
type : 'dashed',
width : 1
}
}
},
// legend: {
// data:['scatter1','scatter2']
// },
xAxis : [
{
type : 'value',
... | identifier_body |
server.rs | //! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from ... | (&self) {
// Iterate all the peers sending a clone of the data. This operation
// performs a deep clone for each peer, which is not going to be super
// efficient as the data set grows, but improving this is out of scope
// for MiniDB.
for peer in &self.peers {
peer.s... | replicate | identifier_name |
server.rs |
//! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from... | //
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Su... | // and respond with Success | random_line_split |
server.rs | . Once the mutation succeeds, the server
//! state is replicated to all the peers. Replication involves sending the
//! entire data set to all the peers. This is not the most efficient strategy,
//! but we aren't trying to build Riak (or even MongoDB).
//!
//! In the event that replication is unable to keep up with the... | {
info!("[COMMAND] Clear");
let mut state = self.server_state.borrow_mut();
let actor_id = state.actor_id;
state.data.clear(actor_id);
state.replicate();
let resp = Response::Success(proto::Success);
Box:... | conditional_block | |
server.rs | //! extracted this topology, leaving the list of peers.
//!
//! After the server starts, connections will be established to all the peers.
//! If a peer cannot be reached, the connection will be retried until the peer
//! becomes reachable.
//!
//! # Replication
//!
//! When the server receives a mutation request from ... | state.data.insert(actor_id, cmd.value());
// Replicate the new state to all peers
state.replicate();
let resp = Response::Success(proto::Success);
Box::new(futures::done(Ok(resp)))
}
Request::Remove(cmd) => {
... | {
match request {
Request::Get(_) => {
info!("[COMMAND] Get");
// Clone the current state and respond with the set
//
let data = self.server_state.borrow().data.clone();
let resp = Response::Value(data);
... | identifier_body |
heap.rs | enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
/// Creates a new empty heap which... | {
let label = format!("{:?}", self.store[*n]);
graphviz::LabelText::LabelStr(label.into_cow())
} | identifier_body | |
heap.rs | in `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemente... | store: Vec<T>,
}
#[derive(Debug)]
enum ChildType {
Left,
Right
}
fn left_child(i: NodeIdx) -> NodeIdx {
2 * i + 1
}
fn right_child(i: NodeIdx) -> NodeIdx {
2 * i + 2
}
impl<T: Ord> Heap<T> {
/// Creates a new empty heap.
pub fn new() -> Heap<T> {
Heap { store: Vec::new() }
}
... | use self::core::borrow::IntoCow;
pub type NodeIdx = usize;
pub struct Heap<T: Ord> { | random_line_split |
heap.rs | `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented a... | else { Some((idx - 1) / 2) }
} else {
panic!("Heap.parent({}): given `idx` not in the heap.", idx)
}
}
fn left_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
self.child(ChildType::Left, parent)
}
fn right_child(&self, parent: NodeIdx) -> Option<NodeIdx> {
... | { None } | conditional_block |
heap.rs | `std::vec::Vec`.
///
/// The heap can contain more than one element with the same priority. No
/// guarantees are made about the order in which elements with equivalent
/// priorities are popped from the queue.
///
/// The data sturcture can be output in Graphviz `.dot` format.
// This data structure is implemented a... | (&self) -> bool {
self.len() == 0
}
/// Takes the index of a node and returns the index of its parent. Returns
/// `None` if the given node has no such parent (i.e. the given node is
/// the root.
///
/// The function panics if the given index is not valid.
fn parent(&self, idx: No... | empty | identifier_name |
oauth2.py | return OAuth2Token(
access_token=token_record.access_token,
refresh_token=token_record.refresh_token,
scope=token_record.scope,
issued_at=token_record.issued_at,
expires_in=token_record.expires_in,
client_id=toke... | delete_oauth2_client | identifier_name | |
oauth2.py | )
class Client(DatabaseModel):
client_secret: str
grant_types: List[GrantType] = []
response_types: List[ResponseType] = []
redirect_uris: List[str] = []
scope: str = ""
ComputableProperty("client_id", "<str>__source__.id")
class AuthorizationCode(DatabaseModel):
code: str
client: Cl... |
resp = await server.create_authorization_response(
(await _oauth2_request(request))(user, query_params)
)
return _to_fastapi_response(resp)
@router.post("/token")
async def oauth2_token(
request: Request, oauth2_request=Depends(_oauth2_request)
):
"""Endpoint to ob... | query_params[key] = request.session.pop(key) | conditional_block |
oauth2.py | )
class Client(DatabaseModel):
client_secret: str
grant_types: List[GrantType] = []
response_types: List[ResponseType] = []
redirect_uris: List[str] = []
scope: str = ""
ComputableProperty("client_id", "<str>__source__.id")
class AuthorizationCode(DatabaseModel):
|
class Token(DatabaseModel):
user: User
access_token: str
refresh_token: str
scope: str
issued_at: int
expires_in: int
client: Client
token_type: str = "Bearer"
revoked: bool = False
class OAuth2Backend(AuthenticationBackend):
async def authenticate(self, conn):
token... | code: str
client: Client
redirect_uri: str
response_type: ResponseType
scope: str
auth_time: int
code_challenge: Optional[str] = None
code_challenge_method: Optional[CodeChallengeMethod] = None
nonce: Optional[str] = None | identifier_body |
oauth2.py | )
class Client(DatabaseModel):
client_secret: str
grant_types: List[GrantType] = []
response_types: List[ResponseType] = []
redirect_uris: List[str] = []
scope: str = ""
ComputableProperty("client_id", "<str>__source__.id")
class AuthorizationCode(DatabaseModel):
code: str
client: Cl... | )
return authorization_code
async def get_token(self, *args, **kwargs) -> Optional[OAuth2Token]:
"""Get token from the database by provided request from user.
Returns:
Token: if token exists in db.
None: if no token in db.
"""
token_record = ... | client_id=client_id,
**data, | random_line_split |
printtips.js | 8%;padding: 0 10px; z-index: 999">智慧接种</span>'+
'<p style="margin: 0; line-height: 22px;font-size: 12px;padding-left: 5px; margin-top:8px;"><span>编号:</span>' + data.no.substring(0,1) + '</p>'+
'<p style="margin: 0; line-height: 22px;font-size: 12px;padding-left: 5px;"><span>姓名:</span>' + data.name.childname + '... | && data.impart.choose != 'normal'){
// hh = hh + 200;
// var cho = data.impart.choose;
// html += cho.replace(new RegExp("#","gm"),"\"");
// }
hh = hh + 100;
html += '<p style="margin: 0; line-height: 20px;font-size: 14px;padding-left: 5px;font-weight: bold;">' + data.vac + '</p>';
html += '<p style="margi... | ta.sign){
hh = hh + 200;
html += '<p style="margin: 0; line-height: 20px;font-size: 13px;padding-left: 5px; padding-top: 5px;"><span>家长或监护人签字:<span> </span></span></p>'
html += '<p style="marg... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.