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 |
|---|---|---|---|---|
cluster_feeder.go | v1lister.NewPodLister(indexer)
stopCh := make(chan struct{})
go controller.Run(stopCh)
return podLister
}
// NewPodListerAndOOMObserver creates pair of pod lister and OOM observer.
func NewPodListerAndOOMObserver(kubeClient kube_client.Interface, namespace string) (v1lister.PodLister, oom.Observer) {
oomObserver ... | VpaName: vpaCRD.Name, | random_line_split | |
cluster_feeder.go | clusterState: m.ClusterState,
specClient: spec.NewSpecClient(m.PodLister),
selectorFetcher: m.SelectorFetcher,
memorySaveMode: m.MemorySaveMode,
controllerFetcher: m.ControllerFetcher,
recommenderName: m.RecommenderName,
}
}
// WatchEvictionEventsWithRetries watches new Events... | (checkpoint *vpa_types.VerticalPodAutoscalerCheckpoint) error {
vpaID := model.VpaID{Namespace: checkpoint.Namespace, VpaName: checkpoint.Spec.VPAObjectName}
vpa, exists := feeder.clusterState.Vpas[vpaID]
if !exists {
return fmt.Errorf("cannot load checkpoint to missing VPA object %+v", vpaID)
}
cs := model.New... | setVpaCheckpoint | identifier_name |
buffers_handler.ts | PeriodBuffer$ observable once every further Buffers have been
// cleared.
createNextPeriodBuffer$.complete();
// emit destruction signal to the next Buffer first
destroyNextBuffers$.next();
destroyNextBuffers$.complete(); // we do not need it anymore
}),
share() // s... | etFirstDeclaredMimeType( | identifier_name | |
buffers_handler.ts | */
export default function BuffersHandler(
content : { manifest : Manifest; period : Period },
clock$ : Observable<IBufferClockTick>,
wantedBufferAhead$ : Observable<number>,
bufferManager : BufferManager,
sourceBufferManager : SourceBufferManager,
segmentPipelinesManager : SegmentPipelinesManager<any>,
... | function manageConsecutivePeriodBuffers(
bufferType : IBufferType,
basePeriod : Period,
destroy$ : Observable<void>
) : Observable<IMultiplePeriodBuffersEvent> {
log.info("creating new Buffer for", bufferType, basePeriod);
/**
* Emits the chosen adaptation for the current type.
* @typ... | */ | random_line_split |
buffers_handler.ts | /**
* Allows to destroy each created Buffer, from the newest to the oldest,
* once destroy$ emits.
* @type {Observable}
*/
const destroyAll$ = destroy$.pipe(
take(1),
tap(() => {
// first complete createNextBuffer$ to allow completion of the
// nextPeriodBuffer$ obse... |
/**
* Array of Observables linked to the Array of Buffers which emit:
* - true when the corresponding buffer is considered _complete_.
* - false when the corresponding buffer is considered _active_.
* @type {Array.<Observable>}
*/
const isCompleteArray : Array<Observable<boolean>> = buffers
... | identifier_body | |
buffers_handler.ts | .value);
} else if (evt.type === "periodBufferCleared") {
removePeriodBuffer$.next(evt.value);
}
}),
share()
);
});
/**
* Emits the active Period every time it changes
* @type {Observable}
*/
const activePeriod$ : Observable<Period> =
... |
// current buffer is full, create the next one if not
createNextPeriodBuffer$.next(nextPeriod);
}
| conditional_block | |
BrowseButton.js | * red background to see how well they are positioned.
*/
debug : false,
/*
* Private constants:
*/
/**
* @property FLOAT_EL_WIDTH
* @type Number The width (in pixels) of floatEl. It should be less than the width of the IE "Browse" button's width
* (65 pixels), since IE doesn't let ... |
this.clipEl.setSize(width, height);
}
}
},
/**
* Creates the input file element and adds it to inputFileCt. The created input file elementis sized, positioned,
* and styled appropriately. Event handlers for the element are set up, and a tooltip is applied if defined in the
* original config.... | {
width = width + 6;
height = height + 6;
} | conditional_block |
BrowseButton.js | * red background to see how well they are positioned.
*/
debug : false,
/*
* Private constants:
*/
/**
* @property FLOAT_EL_WIDTH
* @type Number The width (in pixels) of floatEl. It should be less than the width of the IE "Browse" button's width
* (65 pixels), since IE doesn't let... | */
createInputFile : function() {
// When an input file gets detached and set as the child of a different DOM element,
// straggling <em> elements get left behind.
// I don't know why this happens but we delete any <em> elements we can find under the floatEl to prevent a
// memory leak.
this.floatEl.... | *
* @private
| random_line_split |
win_export.py | result, write_title=False):
import csv
try:
fp = file(fname, 'wb+')
writer = csv.writer(fp)
if write_title:
writer.writerow(fields)
for data in result:
row = []
for d in data:
if type(d)==types.StringType:
r... |
def sig_sel(self, widget=None):
sel = self.view1.get_selection()
sel.selected_foreach(self._sig_sel_add)
def _sig_sel_add(self, store, path, iter):
name, relation = self.fields[store.get_value(iter,1)]
#if relation:
# return
num = self.model2.append()
... | self.model2.set(self.model2.append(), 0, self.fields[field], 1, field) | conditional_block |
win_export.py | result, write_title=False):
import csv
try:
fp = file(fname, 'wb+')
writer = csv.writer(fp)
if write_title:
writer.writerow(fields)
for data in result:
row = []
for d in data:
if type(d)==types.StringType:
r... | self.pref_export.show_all()
def del_export_list_key(self,widget, event, *args):
if event.keyval==gtk.keysyms.Delete:
self.del_selected_export_list()
def del_export_list_btn(self, widget=None):
self.del_selected_export_list()
def del_selected_export_list(self):
... | random_line_split | |
win_export.py | result, write_title=False):
import csv
try:
fp = file(fname, 'wb+')
writer = csv.writer(fp)
if write_title:
writer.writerow(fields)
for data in result:
row = []
for d in data:
if type(d)==types.StringType:
r... | self.view2.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
self.glade.get_widget('exp_vp2').add(self.view2)
self.view1.set_headers_visible(False)
self.view2.set_headers_visible(False)
cell = gtk.CellRendererText()
column = gtk.TreeViewColumn('Field name', cell, text=0, ... | self.glade = glade.XML(common.terp_path("openerp.glade"), 'win_save_as',
gettext.textdomain())
self.win = self.glade.get_widget('win_save_as')
self.ids = ids
self.model = model
self.fields_data = {}
if context is None:
context = {}
self.context... | identifier_body |
win_export.py | result, write_title=False):
import csv
try:
fp = file(fname, 'wb+')
writer = csv.writer(fp)
if write_title:
writer.writerow(fields)
for data in result:
row = []
for d in data:
if type(d)==types.StringType:
r... | (self, widget=None):
self.del_selected_export_list()
def del_selected_export_list(self):
store, paths = self.pref_export.get_selection().get_selected_rows()
for p in paths:
export_fields= store.get_value(store.__getitem__(p[0]).iter,0)
export_name= store.get_value(st... | del_export_list_btn | identifier_name |
main.py | long}&formatted=0')
sun_times = response.json()
return sun_times
#COLLECTS USER LAT / LONG & ASKS IF THEY WANT TO SUBMIT EMAIL FOR ALERTS. SAVES DATA TO JSON IF YES.
def user_input():
user = {}
search = False
while search == False:
search_area = input("Type in your country name / ISO code. ... | response.raise_for_status()
data = response.json()
latitude = float(data["iss_position"]["latitude"])
longitude = float(data["iss_position"]["longitude"])
return (latitude,longitude)
iss_location = get_iss_location()
def find_user():
ISS = get_iss_location()
try:
json_stored = pd.r... | random_line_split | |
main.py | user_longitude = matched_result['longitude'].item()
print(f"Database entry for {matched_result['name'].item()} used for latitude ({user_latitude}) & longitude({user_longitude})")
search = True
elif len(df.loc[(df['country'] == search_area.upper())]) > 0:
matched_result = df... | print("Checking") | identifier_body | |
main.py | }&formatted=0')
sun_times = response.json()
return sun_times
#COLLECTS USER LAT / LONG & ASKS IF THEY WANT TO SUBMIT EMAIL FOR ALERTS. SAVES DATA TO JSON IF YES.
def user_input():
user = {}
search = False
while search == False:
search_area = input("Type in your country name / ISO code. \nOr... | ():
ISS = get_iss_location()
try:
json_stored = pd.read_json('users.json')
df_stored = pd.DataFrame(json_stored)
print(f" ISS location = {ISS}")
except FileNotFoundError:
print("File not Found")
return False
else:
print("df_stored")
print(df_store... | find_user | identifier_name |
main.py | .loc[(df['name'] == search_area.title())]
user_latitude = matched_result['latitude'].item()
user_longitude = matched_result['longitude'].item()
print(f"Database entry for {matched_result['name'].item()} used for latitude ({user_latitude}) & longitude({user_longitude})")
s... | user_email = user[2]
local_is_night(user_la,user_lo) | conditional_block | |
helpers.py | # Set as return variables
final_X = corrected_tf_filt_X
final_Y = corrected_tf_Y
else:
# Set unmodified values as return variables
final_X = filt_X
final_Y = Y
return final_Y, final_X, dIDs, filt_tIDs, tfs, ths, t_idx
def filter_features(Y, N):
"""
... | normalize_feature | identifier_name | |
helpers.py |
vmin, vmax, midpoint = self.vmin, self.vmax, self.midpoint
if cbook.iterable(value):
val = ma.asarray(value)
val = 2 * (val-0.5)
val[val>0] *= abs(vmax - midpoint)
val[val<0] *= abs(vmin - midpoint)
val += midpoint
return val
... | raise ValueError("Not invertible until scaled") | conditional_block | |
helpers.py | ]['transcriptIDs'].value
donorIDs = f[t]['donorIDs'].value
technical_factors, technical_headers, technical_idx = \
get_technical_factors(t, donorIDs)
size_group = f[t][l][ca][ps]
features = size_group[m][a]['ordered_aggregated_features'].value
features[features < 0] =... | random_line_split | ||
helpers.py | -midpoint) + midpoint
else:
return val*abs(vmax-midpoint) + midpoint
def extract_final_layer_data(t, m, a, ps, genotypes=False, shuffle=False):
with h5py.File(GTEx_directory +
'/data/h5py/aggregated_features.h5py', 'r') as f:
X = f[t]['ordered_expression'].value... |
def filter_expression(X, tIDs, M, k):
"""
Return top M varying transcripts, with mean expression > k, along with their transcript names.
"""
k_threshold_idx = np.mean(X, axis=0) > k
M_varying_idx = np.argsort(np.std(X[:,k_threshold_idx], axis=0))[-M:]
idx = np.array(list(range(X.shape[1])... | """
Return top N varying image features.
"""
most_varying_feature_idx = np.argsort(np.std(Y, axis=0))[-N:]
filt_Y = Y[:, most_varying_feature_idx]
return filt_Y, most_varying_feature_idx | identifier_body |
object_ptr.rs | ::convert::TryFrom;
use std::ffi::CString;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
use tvm_sys::ffi::{self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeKey2Index};
use tvm_sys::{ArgValue, RetValue};
use crate::errors::Error;
type Deleter = unsafe extern "C" fn(object: *mut Object) -> ();
#[derive(... | <U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> {
let child_index = Object::get_type_index::<U>();
let object_index = self.as_object().type_index;
let is_derived = if child_index == object_index {
true
} else {
// TODO(@jroesch): write tests
deriv... | downcast | identifier_name |
object_ptr.rs | ::convert::TryFrom;
use std::ffi::CString;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
use tvm_sys::ffi::{self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeKey2Index};
use tvm_sys::{ArgValue, RetValue};
use crate::errors::Error;
type Deleter = unsafe extern "C" fn(object: *mut Object) -> ();
#[derive(... |
pub fn upcast(&self) -> ObjectPtr<Object> {
ObjectPtr {
ptr: self.ptr.cast(),
}
}
pub fn downcast<U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> {
let child_index = Object::get_type_index::<U>();
let object_index = self.as_object().type_index;
let ... | {
unsafe { self.ptr.as_ref().as_object() }
} | identifier_body |
object_ptr.rs | std::convert::TryFrom;
use std::ffi::CString;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
use tvm_sys::ffi::{self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeKey2Index};
use tvm_sys::{ArgValue, RetValue};
use crate::errors::Error;
type Deleter = unsafe extern "C" fn(object: *mut Object) -> ();
#[der... | let object = | random_line_split | |
object_ptr.rs | ::convert::TryFrom;
use std::ffi::CString;
use std::ptr::NonNull;
use std::sync::atomic::AtomicI32;
use tvm_sys::ffi::{self, TVMObjectFree, TVMObjectRetain, TVMObjectTypeKey2Index};
use tvm_sys::{ArgValue, RetValue};
use crate::errors::Error;
type Deleter = unsafe extern "C" fn(object: *mut Object) -> ();
#[derive(... |
}
impl Object {
fn new(type_index: u32, deleter: Deleter) -> Object {
Object {
type_index,
// Note: do not touch this field directly again, this is
// a critical section, we write a 1 to the atomic which will now
// be managed by the C++ atomics.
... | {
true
} | conditional_block |
FtpContext.js | => void} ResponseHandler
*/
/**
* FTPContext holds the control and data sockets of an FTP connection and provides a
* simplified way to interact with an FTP server, handle responses, errors and timeouts.
*
* It doesn't implement or use any FTP commands. It's only a foundation to make writing an FTP
* client as... |
});
}
/**
* Removes reference to current task and handler. This won't resolve or reject the task.
*/
_stopTrackingTask() {
// Disable timeout on control socket if there is no task active.
this.enableControlTimeout(false);
this._task = undefined;
this._hand... | {
this.send(command);
} | conditional_block |
FtpContext.js | => void} ResponseHandler
*/
/**
* FTPContext holds the control and data sockets of an FTP connection and provides a
* simplified way to interact with an FTP server, handle responses, errors and timeouts.
*
* It doesn't implement or use any FTP commands. It's only a foundation to make writing an FTP
* client as... | () {
return this._socket;
}
/**
* Set the socket for the control connection. This will only close the current control socket
* if the new one is set to `undefined` because you're most likely to be upgrading an existing
* control connection that continues to be used.
*
* @type ... | socket | identifier_name |
FtpContext.js | => void} ResponseHandler
*/
/**
* FTPContext holds the control and data sockets of an FTP connection and provides a
* simplified way to interact with an FTP server, handle responses, errors and timeouts.
*
* It doesn't implement or use any FTP commands. It's only a foundation to make writing an FTP
* client as... | * A multiline response might be received as multiple chunks.
* @private
* @type {string}
*/
this._partialResponse = "";
/**
* The encoding used when reading from and writing to the control socket.
* @type {string}
*/
this.encoding = ... | {
/**
* Timeout applied to all connections.
* @private
* @type {number}
*/
this._timeout = timeout;
/**
* Current task to be resolved or rejected.
* @private
* @type {(Task | undefined)}
*/
this._task = undefined;
... | identifier_body |
FtpContext.js | ) => void} ResponseHandler
*/
/**
* FTPContext holds the control and data sockets of an FTP connection and provides a
* simplified way to interact with an FTP server, handle responses, errors and timeouts.
*
* It doesn't implement or use any FTP commands. It's only a foundation to make writing an FTP
* client a... | }
/**
* Set the socket for the data connection. This will automatically close the former data socket.
*
* @type {(Socket | undefined)}
**/
set dataSocket(socket) {
this._closeSocket(this._dataSocket);
if (socket) {
socket.setTimeout(this._timeout);
... | return this._dataSocket; | random_line_split |
custom_fingers.py | for Known node:
# path_len is the path length source node,
# ident is the identity value of the Known node.
# lindex is the list index of the Known node.
Knode = namedtuple('Knode', ['path_len', 'ident','lindex'])
def rand_ident():
"""
Generate random identity in the range [0,MAX_IDENT)
"""
return ra... | def remove_knodes_duplicates(knodes):
"""
Go over a list of knodes, and remove knodes that show up more than once.
In case of node ident showing more than once, we pick the shorter path.
"""
if len(knodes) == 0:
return knodes
knodes.sort(key=lambda kn:(kn.ident,kn.path_len))
# Resu... | random_line_split | |
custom_fingers.py | [0].ident
res = [knodes[0]]
for kn in knodes[1:]:
if kn.ident != cur_ident:
cur_ident = kn.ident
res.append(kn)
return res
# A node:
class Node():
def __init__(self,fk,ident=None):
"""
Initialize a node.
"""
# If ident value is not spec... | for f in SUCC_FINGERS:
sum_finger_path += sn.get_best_succ_finger(f).path_len
for f in PRED_FINGERS:
sum_finger_path += sn.get_best_pred_finger(f).path_len | conditional_block | |
custom_fingers.py | Known node:
# path_len is the path length source node,
# ident is the identity value of the Known node.
# lindex is the list index of the Known node.
Knode = namedtuple('Knode', ['path_len', 'ident','lindex'])
def rand_ident():
"""
Generate random identity in the range [0,MAX_IDENT)
"""
return random... |
def verify_succ_pred_fingers(self):
"""
Verify the succ and pred fingers found for all nodes.
"""
# Get all nodes (as Knodes), and sort them according to ident:
lnodes = list(map(self.make_knode,range(self.num_nodes)))
lnodes.sort(key=lambda ln:ln.ident)
ide... | """
"converge" the DHT by iterating until nothing changes.
"""
for i in range(max_iters):
self.iter_all()
print(".",end="",flush=True)
if self.verify():
print("\nReached correct succ and pred + fingers.")
return
print("... | identifier_body |
custom_fingers.py | Known node:
# path_len is the path length source node,
# ident is the identity value of the Known node.
# lindex is the list index of the Known node.
Knode = namedtuple('Knode', ['path_len', 'ident','lindex'])
def rand_ident():
"""
Generate random identity in the range [0,MAX_IDENT)
"""
return random... | (self):
"""
Generate n nodes with random identity numbers.
"""
self.nodes = []
for i in range(self.num_nodes):
self.nodes.append(Node(self.fk))
def make_knode(self,i,path_len=0):
"""
Given an index i of a node in self.nodes,
create a Knode... | gen_nodes | identifier_name |
utils_test.go | FeegrantKeeper: suite.app.FeeGrantKeeper,
IBCKeeper: suite.app.IBCKeeper,
FeeMarketKeeper: suite.app.FeeMarketKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
})
suite.Require().NoError(err)
suite.anteHandler = anteHandler
... | GetMsgs | identifier_name | |
utils_test.go | .com/evmos/ethermint/encoding"
"github.com/evmos/ethermint/tests"
"github.com/evmos/ethermint/x/evm/statedb"
evmtypes "github.com/evmos/ethermint/x/evm/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
type AnteTestSuite struc... | // We're using TestMsg amino encoding in some tests, so register it here.
encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil)
suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig)
anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{
AccountKeeper: sui... | random_line_split | |
utils_test.go | /evmos/ethermint/encoding"
"github.com/evmos/ethermint/tests"
"github.com/evmos/ethermint/x/evm/statedb"
evmtypes "github.com/evmos/ethermint/x/evm/types"
feemarkettypes "github.com/evmos/ethermint/x/feemarket/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
type AnteTestSuite struct {
... | ChainID: suite.ctx.ChainID(),
AccountNumber: accNum,
Sequence: txData.GetNonce(),
}
sigV2, err = tx.SignWithPrivKey(
suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, suite.clientCtx.TxConfig, txData.GetNonce(),
)
suite.Require().NoError(err)
sig... | {
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: txDa... | conditional_block |
utils_test.go | github.com/evmos/ethermint/x/feemarket/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
type AnteTestSuite struct {
suite.Suite
ctx sdk.Context
app *app.EthermintApp
clientCtx client.Context
anteHandler sdk.AnteHandler
ethSigner ethtypes.Signer... | {
// Build MsgSend
recipient := sdk.AccAddress(common.Address{}.Bytes())
msgSend := types2.NewMsgSend(from, recipient, sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(1))))
return suite.CreateTestEIP712CosmosTxBuilder(from, priv, chainId, gas, gasAmount, msgSend)
} | identifier_body | |
RealTimePlotTemplate.py | 663e-07, 1.68822071e-07, 2.43800712e-04]])
B = [-28.43905915, 51.22161875, -72.33527491]
global S,B
def BLEconnection(connNode,addr,connType,iface):
''' do ble connection '''
connNode.Peripheral = btle.Peripheral(addr , connType , iface = iface)
connNode.Peripheral.setDelegate(MyDelegate(connNode... |
def struct_isqrt(number):
threehalfs = 1.5
x2 = number * 0.5
y = number
packed_y = struct.pack('f', y)
i = struct.unpack('i', packed_y)[0] # treat float's bytes as int
i = 0x5f3759df - (i >> 1) # arithmetic with magic number
packed_i = struct.pack('i', i)
... | '''Scan '''
scanner = btle.Scanner(iface)
while True :
print("Still scanning... count: %s" % 1)
try:
devcies = scanner.scan(timeout = 3)
# print devcies
for dev in devcies:
# print "xx"
if dev.addr == "3c:cd:40:18:c1... | identifier_body |
RealTimePlotTemplate.py | (self):
self.Peripheral = None
self.nodeCube = None
self.drawWindowNumber = -1
self.accBias = [0.0,0.0,0.0]
self.gyroBias = [0.0,0.0,0.0]
self.magBias = [0.0,0.0,0.0]
self.magScale = [0.0,0.0,0.0]
self.magCalibration = [0.0,0.0,0.0]
self.noti = Non... | __init__ | identifier_name | |
RealTimePlotTemplate.py | 663e-07, 1.68822071e-07, 2.43800712e-04]])
B = [-28.43905915, 51.22161875, -72.33527491]
global S,B
def BLEconnection(connNode,addr,connType,iface):
''' do ble connection '''
connNode.Peripheral = btle.Peripheral(addr , connType , iface = iface)
connNode.Peripheral.setDelegate(MyDelegate(connNode... |
if resetFlag.value == True:
plotMyData.ResetGraph()
resetFlag.value = False
endIdx = Idx.value
data[0]= plot1[0:endIdx]
data[1]= plot2[0:endIdx]
data[2]= plot3[0:endIdx]
data[3]= plot4[0:endIdx]
data[4]= plot5[0:endIdx]
data[5]= p... | pass | conditional_block |
RealTimePlotTemplate.py | self.noti = None
self.fail_notify=0
self.workingtime=0.0
self.datagram=[]
self.seq=0
self.count_received_data=0
S = np.array([[ 2.42754810e-04, 3.41614666e-07, -2.07507663e-07],
[ 3.41614666e-07, 2.43926399e-04, 1.68822071e-07],
[ -2.07507663e-07, 1.68822071e-0... | self.accBias = [0.0,0.0,0.0]
self.gyroBias = [0.0,0.0,0.0]
self.magBias = [0.0,0.0,0.0]
self.magScale = [0.0,0.0,0.0]
self.magCalibration = [0.0,0.0,0.0] | random_line_split | |
main.rs | seem simple, but the behavior of code can be
// unexpected in more complicated situations when we want to
// have multiple variables use the data that's been allocated
// on the heap.
//
// + Ways variables and data interact: Move
// Multiple variables can interact with the same data in different
// ways... | {
// [References and Borrowing]
// The issue with the returning tuple code we've seen elsewhere in
// the ownership section is that we have to return the String to
// the calling function so we can still use the String after the call.
// Here we define calculate_length so that it uses a *reference* to
// an... | identifier_body | |
main.rs | variables are valid
// is similar to other programming langs. Let's build on top
// of this introducing the String type.
//
// + String type
// We're going to illustrate the rules of ownership using a data type
// that's more complex than the ones we've seen before. All the data
// types we've seen befor... | () {
// With string literals, we know the contents of the string at compile
// time, so the text is literally hardcoded into the executable,
// making them extremely fast and efficient. This property only comes
// from its immutability. We can't put a blob of memory into the binary
// for each piece of text w... | moves_and_mem | identifier_name |
main.rs | // the opposite order (LIFO). This is referred to as
// *pushing onto the stack* and *popping off of the stack*
//
// It's fast because of the way it accesses the data: it never has to
// search for a place to put new data or a place to get data from because
// that place is *always* the top of the stack. Another prope... | // stores values in the order it gets them and removes the values in | random_line_split | |
audition.js | success: (res) => {
if(res.data) {
this.setData({ localAudioState: res.data });
for(var idx in res.data.audios) {
switch(idx) {
case 1:
this.setData({
firstFinished: true
});
break;
cas... | this.saveLocalState(0);
var hasPreAudio = this.data.content.preAudio
this.data.content.audios[0].finished = true;
var preAudioFinshed = this.data.preAudioFinshed
if ((!hasPreAudio || preAudioFinshed)) {
this.setData({
firstFinished: true
})
... | case 1: | random_line_split |
audition.js | success: (res) => {
if(res.data) {
this.setData({ localAudioState: res.data });
for(var idx in res.data.audios) {
switch(idx) {
case 1:
this.setData({
firstFinished: true
});
break;
cas... | */
onReady: function () {
},
/**
* 下一步
*/
next: function() {
const step = this.data.currentStep + 1;
this.setData({
currentStep: step,
fixed: true
})
if (this.data.currentStep == 3) {
setTimeout(() => {
util.showToast("Lire au moins cinq fois pour passer l’ét... | 染完成
| identifier_name |
audition.js | : (res) => {
if(res.data) {
this.setData({ localAudioState: res.data });
for(var idx in res.data.audios) {
switch(idx) {
case 1:
this.setData({
firstFinished: true
});
break;
case 2:
... | tep,
fixed: true
})
if (this.data.currentStep == 3) {
setTimeout(() => {
util.showToast("Lire au moins cinq fois pour passer l’étape suivante.", 2500)
} ,1000)
}
this.stopAudio()
},
toggle: function(e) {
var key = e.target.dataset.target
this.setData({
[key]:... | his.setData({
currentStep: s | identifier_body |
audition.js | success: (res) => {
if(res.data) {
this.setData({ localAudioState: res.data });
for(var idx in res.data.audios) {
switch(idx) {
case 1:
this.setData({
firstFinished: true
});
break;
cas... | case 4:
this.saveLocalState(0, 'optAudios');
wx.setStorage({
key: 'optRecord_' + this.data.paper.id,
data: true,
})
this.setData({
optRecordFinished: true,
optFinished: true
})
break
}
if(this.data.currentStep == 3) {
... | this.setData({
secondFinished: true
})
break
| conditional_block |
Minitaur_Env.py | numHeightfieldColumns=numHeightfieldColumns)
textureId = p.loadTexture("heightmaps/wm_height_out.png")
terrain = p.createMultiBody(0, terrainShape)
# p.changeVisualShape(terrain, -1, rgbaColor=[1,1,1,1])
p.changeVisualShape(terrain, -1, tex... | '''Generate a heightfield.
Resource: https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/heightfield.py'''
p = self.p
numHeightfieldRows = num_rows
numHeightfieldColumns = num_rows
heightfieldData = [0]*numHeightfieldRows*numHeightfieldColumns
... | identifier_body | |
Minitaur_Env.py | 0,l2/2]
x_temp = 0.5 + obs*l1
y_temp = 0
posObs_obs1[0] = x_temp
posObs_obs1[1] = y_temp
posObs_obs1[2] = -h # set z at ground level
posObs[2*obs] = posObs_obs1
colIdxs[2*obs] = p.createCollisionShape(p.GEOM_BOX, flags = p.... | Parameters | random_line_split | |
Minitaur_Env.py | = p.createMultiBody(0, terrainShape)
# p.changeVisualShape(terrain, -1, rgbaColor=[1,1,1,1])
p.changeVisualShape(terrain, -1, textureUniqueId = textureId)
# Remove the previous terrain and establish the new one
# Note: first time this function is called, the default terrain of... | (self, policy, goal, alpha, time_step=0.01, speed=40, comp_len=10, prim_horizon=50,
image_size=50, device=torch.device('cuda'), record_vid=False, vid_num=0):
if record_vid:
import cv2
# videoObj = cv2.VideoWriter('video'+str(vid_num)+'.avi', cv2.VideoWrit... | execute_policy | identifier_name |
Minitaur_Env.py | = p.createMultiBody(0, terrainShape)
# p.changeVisualShape(terrain, -1, rgbaColor=[1,1,1,1])
p.changeVisualShape(terrain, -1, textureUniqueId = textureId)
# Remove the previous terrain and establish the new one
# Note: first time this function is called, the default terrain of... |
x_goal = self.goal
y_goal = 0
posObs = np.array([None] * 3)
posObs[0] = x_goal
posObs[1] = y_goal
posObs[2] = 0 # set z at ground level
# colIdxs = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1,5.0,0.1])
colIdxs = -1
visIdxs = p.createVisu... | p.changeVisualShape(obsUid, visIdxs[obs], textureUniqueId=self.terraintextureId) | conditional_block |
content-parse.ts | 96;')
const classes = lang ? ` class="language-${lang}"` : ''
return `><pre><code${classes}>${code}</code></pre>`
})
.replace(/`([^`\n]*)`/g, (_1, raw) => {
return raw ? `<code>${htmlToText(raw).replace(/</g, '<').replace(/>/g, '>')}</code>` : ''
})
}
// Always sanit... | (node: Node, transform: Transform, root: Node) {
if (Array.isArray(node.children)) {
const children = [] as (Node | string)[]
for (let i = 0; i < node.children.length; i++) {
const result = visit(node.children[i], transform, root)
if (Array.isArray(result))
children.push(...res... | visit | identifier_name |
content-parse.ts | 96;')
const classes = lang ? ` class="language-${lang}"` : ''
return `><pre><code${classes}>${code}</code></pre>`
})
.replace(/`([^`\n]*)`/g, (_1, raw) => {
return raw ? `<code>${htmlToText(raw).replace(/</g, '<').replace(/>/g, '>')}</code>` : ''
})
}
// Always sanit... | }
| {
return (node) => {
if (node.type !== TEXT_NODE)
return node
const split = node.value.split(/\s?:([\w-]+?):/g)
if (split.length === 1)
return node
return split.map((name, i) => {
if (i % 2 === 0)
return name
const emoji = customEmojis[name] as mastodon.v1.CustomEmoj... | identifier_body |
content-parse.ts | 96;')
const classes = lang ? ` class="language-${lang}"` : ''
return `><pre><code${classes}>${code}</code></pre>`
})
.replace(/`([^`\n]*)`/g, (_1, raw) => {
return raw ? `<code>${htmlToText(raw).replace(/</g, '<').replace(/>/g, '>')}</code>` : ''
})
}
// Always sanit... | let start = 0
const matches = [] as (string | Node)[]
findAndReplaceEmojisInText(emojiRegEx, node.value, (match, result) => {
matches.push(result.slice(start).trimEnd())
start = result.length + match.match.length
return undefined
})
if (matches.length === 0)
return node
matches.push(node.v... | function removeUnicodeEmoji(node: Node) {
if (node.type !== TEXT_NODE)
return node
| random_line_split |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | () {
let (mut game, event_loop) = Game::new("Example 03 - 3rd person");
// Create simple user interface that will show some useful info.
let interface = create_ui(
&mut game.engine.user_interface.build_ctx(),
Vector2::new(100.0, 100.0),
);
let mut previous = Instant::now();
let... | main | identifier_name |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... |
let settings = match input.physical_key {
KeyCode::Digit1 => Some(QualitySettings::ultra()),
KeyCode::Digit2 => Some(QualitySettings::high()),
KeyCode::Digit3 => Some(QualitySettings::medium()),
... | {
game_scene.player.handle_key_event(input, fixed_timestep);
} | conditional_block |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | // 60 fps.
let elapsed = previous.elapsed();
previous = Instant::now();
lag += elapsed.as_secs_f32();
while lag >= fixed_timestep {
// ************************
// Put your game logic here.
... | {
let (mut game, event_loop) = Game::new("Example 03 - 3rd person");
// Create simple user interface that will show some useful info.
let interface = create_ui(
&mut game.engine.user_interface.build_ctx(),
Vector2::new(100.0, 100.0),
);
let mut previous = Instant::now();
let fi... | identifier_body |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | //! blending machines are used in all modern games to create complex animations from set
//! of simple ones.
//!
//! TODO: Improve explanations. Some places can be explained better.
//!
//! Known bugs: Sometimes character will jump, but jumping animations is not playing.
//!
//! Possible improvements:
//! - Smart came... | //! Also this example demonstrates the power of animation blending machines. Animation | random_line_split |
cargo-deploy.rs | ).into_iter() {
if let cargo_metadata::Message::CompilerArtifact(artifact) =
message.unwrap_or_else(|_| panic!("Failed to parse output of cargo"))
{
if artifact.target.kind == vec![String::from("bin")]
|| artifact.target.kind == vec![String::from("example")]
{
bin.push((
artifact.target.name,
... | f let Some(profile) = profile {
let _ = cargo.arg(format!("--profile={}", profile));
}
for features in features {
let _ = cargo.arg(format!("--features={}", features));
}
if all_features {
let _ = cargo.arg("--all-features");
}
if no_default_features {
let _ = cargo.arg("--no-default-features");
}
if le... | let _ = cargo.arg("--release");
}
i | conditional_block |
cargo-deploy.rs | 7059559d71de3fffe8c8cb81e32f323454aa96c5/src/bin/cargo/cli.rs#L205-L277
// https://github.com/rust-lang/cargo/blob/982622252a64d7c526c04a244f1a81523dc9ae54/src/bin/cargo/commands/run.rs
App::new("cargo")
.bin_name("cargo")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
App... | Self::opt(name, help)
.value_name(value_name)
.multiple(true)
.min_values(0)
.number_of_values(1)
}
f | identifier_body | |
cargo-deploy.rs | ).into_iter() {
if let cargo_metadata::Message::CompilerArtifact(artifact) =
message.unwrap_or_else(|_| panic!("Failed to parse output of cargo"))
{
if artifact.target.kind == vec![String::from("bin")]
|| artifact.target.kind == vec![String::from("example")]
{
bin.push((
artifact.target.name,
... | `--` go to the binary, the ones before go to Cargo.
",
),
)
}
fn cargo(args: &ArgMatches) -> process::Command {
let verbose: u64 = args.occurrences_of("verbose");
let color: Option<&str> = args.value_of("color");
let frozen: bool = args.is_present("frozen");
let locked: bool = args.is_present("locked");
let... | and `--example` specifies the example target to run. At most one of `--bin` or
`--example` can be provided.
All the arguments following the two dashes (`--`) are passed to the binary to
run. If you're passing arguments to both Cargo and the binary, the ones after | random_line_split |
cargo-deploy.rs | command(
SubCommand::with_name("deploy")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
AppSettings::TrailingVarArg,
])
.version(crate_version!())
.about("Run a binary or example of the local package on a conste... | get_triple(ta | identifier_name | |
generator.rs | if let Some(target_docs_dir) = target_docs_dir {
if !target_docs_dir.exists() {
fs::create_dir(&target_docs_dir)?;
}
transfer_bindings_to_docs(&OUT_DIR, &target_docs_dir);
}
Ok(())
}
fn run(&self, modules: &'static [String], opencv_header_dir: &Path, opencv: &Library) -> Result<()> {
let additio... |
let add_manual = |file: &mut BufWriter<File>, module: &str| -> Result<bool> {
if manual_dir.join(format!("{module}.rs")).exists() {
writeln!(file, "pub use crate::manual::{module}::*;")?;
Ok(true)
} else {
Ok(false)
}
};
let start = Instant::now();
let mut hub_rs = BufWriter::new(File::create(targ... | {
// Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too well:
// https://github.com/twistedfall/opencv-rust/issues/418
// https://github.com/rust-lang/rust-analyzer/issues/11682
Ok(writeln!(
write,
r#"include!(concat!(env!("OUT_DIR"), "/opencv/{... | identifier_body |
generator.rs | if let Some(target_docs_dir) = target_docs_dir {
if !target_docs_dir.exists() {
fs::create_dir(&target_docs_dir)?;
}
transfer_bindings_to_docs(&OUT_DIR, &target_docs_dir);
}
Ok(())
}
fn run(&self, modules: &'static [String], opencv_header_dir: &Path, opencv: &Library) -> Result<()> {
let additio... | (mut write: impl Write, module: &str) -> Result<()> {
Ok(writeln!(write, "#[cfg(ocvrs_has_module_{module})]")?)
}
fn write_module_include(write: &mut BufWriter<File>, module: &str) -> Result<()> {
// Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too w... | write_has_module | identifier_name |
generator.rs | if let Some(target_docs_dir) = target_docs_dir {
if !target_docs_dir.exists() {
fs::create_dir(&target_docs_dir)?;
}
transfer_bindings_to_docs(&OUT_DIR, &target_docs_dir);
}
Ok(())
}
fn run(&self, modules: &'static [String], opencv_header_dir: &Path, opencv: &Library) -> Result<()> {
let additio... |
// add module entry to hub.rs and move the module file into opencv/
write_has_module(&mut hub_rs, module)?;
write_module_include(&mut hub_rs, module)?;
let module_filename = format!("{module}.rs");
let module_src_file = OUT_DIR.join(&module_filename);
let mut module_rs = BufWriter::new(File::create(&targe... | {
let module_types_cpp = OUT_DIR.join(format!("{module}_types.hpp"));
let mut module_types_file = BufWriter::new(
OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(module_types_cpp)?,
);
let mut type_files = files_with_extension(&OUT_DIR, "cpp")?
.filter(|f| is_... | conditional_block |
generator.rs | if let Some(target_docs_dir) = target_docs_dir {
if !target_docs_dir.exists() {
fs::create_dir(&target_docs_dir)?;
}
transfer_bindings_to_docs(&OUT_DIR, &target_docs_dir);
}
Ok(())
}
fn run(&self, modules: &'static [String], opencv_header_dir: &Path, opencv: &Library) -> Result<()> {
let additio... | io::copy(&mut BufReader::new(File::open(&entry)?), &mut module_types_file)?;
let _ = fs::remove_file(entry);
}
}
// add module entry to hub.rs and move the module file into opencv/
write_has_module(&mut hub_rs, module)?;
write_module_include(&mut hub_rs, module)?;
let module_filename = format!("{m... | random_line_split | |
Mission_Util_V01.py | ", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"]
if (self.iden.upper() in illegalFileNames):
showinfo(title="Error", message="Illegal file name.")
return False
for chara in illegalFileNameChars:
if chara in self.iden:
showinfo(title="Er... | skip = True
break | conditional_block | |
Mission_Util_V01.py | (self):
self.iden = "mission"
self.name = "Mission"
self.description = "a mission"
self.time_limit = "300"
self.strikes = "3"
self.needy_activation_time = "90"
self.front_only = 0
self.widgets = "5"
self.modules = ""
self.separa... | __init__ | identifier_name | |
Mission_Util_V01.py | .strikes
self.needy_activation_time = needy_activation_time.strip() if needy_activation_time.strip() != "" else self.needy_activation_time
self.front_only = front_only
self.widgets = widgets.strip() if widgets.strip() != "" else self.widgets
self.modules = modules.strip() if modules.... | showinfo(title="Error", message="Illegal character in Widgets.")
return False
# TODO figure out what characters cause the descriptions to throw a fit, or what I can include to make them acceptable
# currently most special characters in the description break the file according ... | random_line_split | |
Mission_Util_V01.py |
class AssetFile:
# default settings/variable init
def __init__(self):
self.iden = "mission"
self.name = "Mission"
self.description = "a mission"
self.time_limit = "300"
self.strikes = "3"
self.needy_activation_time = "90"
self.front_only =... | try: #ScrolledText
widget.delete("1.0", tk.END)
widget.insert("1.0", text)
except tk.TclError: #Bad entry index - Entry
widget.delete(0, tk.END)
widget.insert(0, text) | identifier_body | |
flood_order.rs | ,
"Tool run with no parameters.",
));
}
for i in 0..args.len() {
let mut arg = args[i].replace("\"", "");
arg = arg.replace("\'", "");
let cmd = arg.split("="); // in case an equals sign was used
let vec = cmd.collect::<Vec<&str... | partial_cmp | identifier_name | |
flood_order.rs | sep);
FloodOrder {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage,
}
}
}
impl WhiteboxTool for FloodOrder {
fn get_source_file(&self) -> String {
String::from(file!())
... | random_line_split | ||
flood_order.rs | arg = arg.replace("\'", "");
let cmd = arg.split("="); // in case an equals sign was used
let vec = cmd.collect::<Vec<&str>>();
let mut keyval = false;
if vec.len() > 1 {
keyval = true;
}
if vec[0].to_lowercase() == "-i"... | {
// Some(other.priority.cmp(&self.priority))
other.priority.partial_cmp(&self.priority)
} | identifier_body | |
main.js | this._childs.text.align = 'center';
this._childs.text.fontWeight = 'normal';
this._childs.text.fontSize = 24;
this._childs.text.fill = '#fff';
},
preload: function(){
console.log('loading.preload');
var _this = this;
game.load.onFileComplete.add(function(p){
_this._childs.te... | _this._childs.point.text = _this._result.point;
});
}
},
update: function(){
this._childs.bg.tilePosition.y+=1;
},
shutdown: function(){
game.world.alpha=1;
}
},
play: {
create: function(){
console.log('play.create');
var _this=this, temp;
th... | }).onComplete.addOnce(function(){
| random_line_split |
main.js | this._childs.text.align = 'center';
this._childs.text.fontWeight = 'normal';
this._childs.text.fontSize = 24;
this._childs.text.fill = '#fff';
},
preload: function(){
console.log('loading.preload');
var _this = this;
game.load.onFileComplete.add(function(p){
_this._childs.te... | emp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.scale).from({x:0, y:0}, 200, Phaser.Easing.Linear.None, true).onComplete.addOnce... |
var t | conditional_block |
main.js | this._childs.text.align = 'center';
this._childs.text.fontWeight = 'normal';
this._childs.text.fontSize = 24;
this._childs.text.fill = '#fff';
},
preload: function(){
console.log('loading.preload');
var _this = this;
game.load.onFileComplete.add(function(p){
_this._childs... | r type = game.rnd.frac()>0.3 ? 0 : (game.rnd.frac()>0.4 ? 1 : 2);
var temp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.sca... | va | identifier_name |
main.js | ._childs.text.fill = '#fff';
},
preload: function(){
console.log('loading.preload');
var _this = this;
game.load.onFileComplete.add(function(p){
_this._childs.text.text = p+'%';
_this._childs.line2.moveTo(game.width*0.2, game.height*0.5);
_this._childs.line2.lineTo(game.width*0.... | type = game.rnd.frac()>0.3 ? 0 : (game.rnd.frac()>0.4 ? 1 : 2);
var temp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.scale... | identifier_body | |
worldcup.js | // * resize radius of circles from each team per category
teamG
.select("circle")
.transition()
.duration(1000)
.attr('r', function(p) {
return radiusScale(p[datapoint]);
});
}
*/
// --------------------------------------------------------------------
/*
// ** add interactivity on mouseover
... | d3.select('svg').node().appendChild( // use .node() to access dom elements
d3.select(svgData).select('path').node());
}
d | conditional_block | |
worldcup.js | /*
// ** add interactivity on mouseover
teamG.on("mouseover", highlightRegion);
function highlightRegion(d) {
teamG // = d3.selectAll("g.overallG")
.select("circle")
.style('fill', function(p) { // changed to p because d already defined
return p.region == d.region ? "red" : "gray"; // circle turns red i... | SVG2(svg | identifier_name | |
worldcup.js | ') // how the label aligns compared to the position you give it
.attr('y', 30)
// .style('font-size', '10px')
.text(function(d) { return d.team;
})
// --------------------------------------------------------------------
// ** add buttons to filter / adjust the chart
// \ creating buttons dynamically (like ... | // --------------------------------------------------------------------
// \ access dom element with 'this' (only in inline function) or '.node()'
// \ useful cause you can use js functionality (ex: clone, measure path length) & re-append a child element
d3.select("circle").each(function(d,i) { // select one cir... | .style("fill", "pink");
});
*/
| random_line_split |
worldcup.js | ', function(p) {
return radiusScale(p[datapoint]);
});
}
*/
// --------------------------------------------------------------------
/*
// ** add interactivity on mouseover
teamG.on("mouseover", highlightRegion);
function highlightRegion(d) {
teamG // = d3.selectAll("g.overallG")
.select("circle")
... | load svg into the fragment
// \ .empty() checks if selection has elements inside it, fires true after we moved the paths out of the fragments into main svg
// \ .empty() with while statement lets us move all path elements into the SVG canvas out of the fragment
while (!d3.select(svgData).selectAll('path').empty(... | identifier_body | |
System.py | System` with parameters
# `pivotalLines = []` and `nonPivotalLines` as the previous result of
# the gluing of both sides of the equation.
# example: if the equation of the system is
# 0 1 2 | x 9
# 3 4 5 | y = 9
# 6 7 8 | z 9
# then `maybeSystemInit would call:
# maybeSystem([], [ [0,1,2,9], [3,4,5,9], [6,7,8,... | # to isolate the line into which the pivot was found from the aforementioned list.
# findPivot : System n . Index -> Maybe Index
def findPivot(system, colIndex):
if len(system.nonPivotalLines) == 0:
return Nothing
col = columnAt(colIndex, system.nonPivotalLines)
maybeLineIndex = firstIndex(isNo... | # that line index depends on the number of lines in system.nonPivotalLines,
# but that's not a problem because we'll use that index only | random_line_split |
System.py | ivotalLines
allLines = pivotalLines + nonPivotalLines
if len(allLines) == 0:
error(System.__init__, "wrong input (two empty lists) "
+ "for System constructor")
self.leftSideWidth = len(allLines[0]) - 1
# number of columns of the leftside ... | return map(normalizedLine, pivotalLines) | identifier_body | |
System.py | System` with parameters
# `pivotalLines = []` and `nonPivotalLines` as the previous result of
# the gluing of both sides of the equation.
# example: if the equation of the system is
# 0 1 2 | x 9
# 3 4 5 | y = 9
# 6 7 8 | z 9
# then `maybeSystemInit would call:
# maybeSystem([], [ [0,1,2,9], [3,4,5,9], [6,7,8,... |
# the previous function starts by calling
# findPivot : System n . Index -> Maybe Index
# which `Maybe` returns the index of the first non-pivotal line
# (that is the line which wasn't used previously for the pivot
# of another column) which
# contains a non-null element at the index column `colIndex`.
# returns N... | return echelonized(newSystem, colIndex + 1) | conditional_block |
System.py | System` with parameters
# `pivotalLines = []` and `nonPivotalLines` as the previous result of
# the gluing of both sides of the equation.
# example: if the equation of the system is
# 0 1 2 | x 9
# 3 4 5 | y = 9
# 6 7 8 | z 9
# then `maybeSystemInit would call:
# maybeSystem([], [ [0,1,2,9], [3,4,5,9], [6,7,8,... | (pivotalLines, nonPivotalLines):
if forall(pivotalLines + nonPivotalLines, isValidLine):
return Maybe(value = System(pivotalLines, nonPivotalLines))
else: return Nothing
# returns True if and only if the list
# is not a series of zeroes ended with one
# last non-zero value, as it would amount to
# an e... | maybeSystem | identifier_name |
ecoliver.py | orrelation Function
+ve lags mean x leads y
-ve lags mean x lags y
'''
x = (x-np.mean(x))/(np.std(x)*len(x))
y = (y-np.mean(y))/np.std(y)
ccf = np.correlate(x, y, mode='full')
lags = np.arange(len(ccf)) - (len(x)-1)
return lags, ccf
def ttest_serialcorr(x, y):
'''
Calculates t... |
else:
X = np.array([np.ones(len | return np.nan, np.nan, np.nan | conditional_block |
ecoliver.py | orrelation Function
+ve lags mean x leads y
-ve lags mean x lags y
'''
x = (x-np.mean(x))/(np.std(x)*len(x))
y = (y-np.mean(y))/np.std(y)
ccf = np.correlate(x, y, mode='full')
lags = np.arange(len(ccf)) - (len(x)-1)
return lags, ccf
def ttest_serialcorr(x, y):
'''
Calculates t... | # t-statistic
t = (np.nanmean(x) - np.nanmean(y))/s
# Degrees of freedom
df = (sx**2/nx + sy**2/ny)**2 / ((sx**2/nx)**2/(nx-1) + (sy**2/ny)**2/(ny-1))
# p-value
p = 1 - stats.t.cdf(t, df)
return t, p
def pad(data, maxPadLength=False):
'''
Linearly interp... | sy = np.sqrt(y[validy].var())
s = np.sqrt(sx**2/nx + sy**2/ny) | random_line_split |
ecoliver.py | relation Function
+ve lags mean x leads y
-ve lags mean x lags y
'''
x = (x-np.mean(x))/(np.std(x)*len(x))
y = (y-np.mean(y))/np.std(y)
ccf = np.correlate(x, y, mode='full')
lags = np.arange(len(ccf)) - (len(x)-1)
return lags, ccf
def | (x, y):
'''
Calculates the t-test for the means of two samples under an assumption of serial
correlation, following the technique of Zwiers and von Storch (Journal of Climate, 1995)
'''
# Valid (non-Nan) data, and return NaN if insufficient valid data
validx = ~np.isnan(x)
validy = ~np.isnan... | ttest_serialcorr | identifier_name |
ecoliver.py | 95)
'''
# Valid (non-Nan) data, and return NaN if insufficient valid data
validx = ~np.isnan(x)
validy = ~np.isnan(y)
if (validx.sum() <= 1) + (validy.sum() <= 1):
return np.nan, np.nan
else:
# Sample lengths
nx = len(x[validx])
ny = len(y[validy])
# Autoc... | '''
Calculates the trend of y given the linear
independent variable x. Outputs the mean,
trend, and alpha-level (e.g., 0.05 for 95%)
confidence limit on the trend.
returns mean, trend, dtrend_95
'''
valid = ~np.isnan(y)
if valid.sum() <= 1:
return np.nan, np.nan, np.nan
else:... | identifier_body | |
window.rs | );
// support f64 seconds by multiplying then using from_millis
let interval = std::time::Duration::from_millis((interval * 1000.0) as u64);
crossterm::terminal::enable_raw_mode()?;
// stdout().execute(crossterm::event::EnableMouseCapture)?
stdout().execute(cursor::Hide)?;
... | (&mut self) -> Result<bool, Error> {
use crossterm::event::Event::{Key, Mouse, Resize};
use crossterm::event::KeyCode::Char;
use crossterm::event::{KeyEvent, KeyModifiers};
match crossterm::event::read()? {
Key(KeyEvent {
code: Char('q'), ..
})
... | handle_event | identifier_name |
window.rs | );
// support f64 seconds by multiplying then using from_millis
let interval = std::time::Duration::from_millis((interval * 1000.0) as u64);
crossterm::terminal::enable_raw_mode()?;
// stdout().execute(crossterm::event::EnableMouseCapture)?
stdout().execute(cursor::Hide)?;
... | elapsed,
true,
)))?
.queue(cursor::MoveTo(0, 2))?
.queue(Print(self.per_code_line(&alltime_stats)))?;
} // mutex on alltime_stats
{
let mut ring_buffer = self.ring_buffer.lock().unwrap();
//... | {
let mut stdout = stdout();
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::MoveTo(0, 0))?
.queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))?
.queue(cursor::MoveTo(self.cols / 2, 0))?
.queue(Print(self.started... | identifier_body |
window.rs | );
// support f64 seconds by multiplying then using from_millis
let interval = std::time::Duration::from_millis((interval * 1000.0) as u64);
crossterm::terminal::enable_raw_mode()?;
// stdout().execute(crossterm::event::EnableMouseCapture)?
stdout().execute(cursor::Hide)?;
... | else {
0.0
};
// intelligent dp detection: eg 2.34%, 10.5%, 100%
let dp = if (pct - 100.0).abs() < f64::EPSILON {
0
} else if pct < 10.0 {
2
} else {
1
};
(pct, dp)
... | {
100.0 * (rb_stats.requests as f64 / stats.global.requests as f64)
} | conditional_block |
window.rs | (options);
// support f64 seconds by multiplying then using from_millis
let interval = std::time::Duration::from_millis((interval * 1000.0) as u64);
crossterm::terminal::enable_raw_mode()?;
// stdout().execute(crossterm::event::EnableMouseCapture)?
stdout().execute(cursor::Hide... | .queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))?
.queue(cursor::MoveTo(self.cols / 2, 0))?
.queue(Print(self.started_at.to_string()))?
.queue(cursor::MoveTo(self.cols - 8 as u16, 0))?
.queue(Print(chrono::Local::now().format("%H:%M:%S").to_string()))... | .queue(cursor::MoveTo(0, 0))? | random_line_split |
util.js | (n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-overlay'></div><div id... | isNumeric | identifier_name | |
util.js | timeout));
});
// also detect paste
$(this).bind('paste',function() {
clearTimeout($(this).data('keyup_timeout_id'));
callback($(this));
});
$(this).change(function() {
clearTimeout($(this).data('keyup_timeout_id'));
callback($(this));
});
};
$.alert = function(msg,title)
{
// hide pleas... | overlay.select(function() { overlay.hide(); original.show().change(); original.focus(); });
overlay.focus(function() { overlay.hide(); original.show().change(); original.focus(); });
original.blur(function() { if(!original.val()) { overlay.show().change(); original.hide(); } else { original.show(); overlay.hide(... | random_line_split | |
util.js | 'auto'});
//j(this).height('auto');
}
j(this).modaloption('width', j(this).parent().width());
// ie7 title bar bug fix when width: auto;
//
//
// ONLY show vert scrollbar.
j(this).css({overflow: 'hidden', overflowY: 'auto'});
// Also adjust width so no horiz scrollbars, in case new conte... | {
opts = defaults;//{};
} | conditional_block | |
util.js |
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-overlay'></div><div id='' class='progress ui-corner-all'>Loading...<div cla... | {
return !isNaN(parseFloat(n)) && isFinite(n);
} | identifier_body | |
core.py | the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED B... |
@classmethod
def get_weights_for_op(cls, op):
"""
Get the weight tensor for a given op
:param op: TF op
:return: Weight tensor for the op
"""
weights = None
if cls._is_op_with_weights(op):
weights = op.inputs[constants.OP_WEIGHT_INDICES[op.ty... | """
Checks if a given op has weights
:param op: TF op
:return: True, if op has weights, False otherwise
"""
return (op.type in constants.OP_WEIGHT_TYPES and
not op.name.startswith(_SKIPPED_PREFIXES)) | identifier_body |
core.py | the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED B... |
return bias
def get_weight_ops(self, ops=None, skip_bias_op=False):
"""
Get all ops that contain weights. If a list of ops is passed search only ops
from this list. Return the sequenced list of weight ops always with Conv/FC
first, followed by the bias op, if present.
... | bias = op.inputs[constants.OP_WEIGHT_INDICES[op.type]] | conditional_block |
core.py | the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED B... | :
"""
Class for query a graph's operations and related data.
"""
def __init__(self, graph, op_map=None, ops_to_ignore=None, strict=True):
"""
Constructor
:param graph: The graph to search
:param op_map: The map of operations used to identify op sequences as "one op".
... | OpQuery | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.