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 |
|---|---|---|---|---|
main.js | optional.",
"image6": "img/slideline_placeholder_images_6.jpg",
"caption6": "This is the sixth caption. This is optional.",
"label6": "Label 6. This is optional.",
}
};
$(document).ready(function(){
// variables for values
var val;
var wholeVal;
var decVal;
var last = 0;
var lastStop... | {
$(this).load();
} | conditional_block | |
main.js | var oldVal;
var currentVal;
var newVal;
var dataSource = s9.initialParams['dataSource'];
function clearGhosts(start, end) {
$('.image').each(function() {
if (this.getAttribute('id') == 'image' + start || this.getAttribute('id') == 'image' + end) {
return;
}
$(this).c... | captionSizing | identifier_name | |
main.js | is optional.",
"label5": "Label 5. This is optional.",
"image6": "img/slideline_placeholder_images_6.jpg",
"caption6": "This is the sixth caption. This is optional.",
"label6": "Label 6. This is optional.",
}
};
$(document).ready(function(){
// variables for values
var val;
var w... |
// variables for catching and storing values during slide
var oldVal;
var currentVal;
var newVal;
var dataSource = s9.initialParams['dataSource'];
function clearGhosts(start, end) {
$('.image').each(function() {
if (this.getAttribute('id') == 'image' + start || this.getAttribute('id') == 'ima... | var prevCaption;
var currentCaption;
var nextCaption; | random_line_split |
main.js | is optional.",
"label5": "Label 5. This is optional.",
"image6": "img/slideline_placeholder_images_6.jpg",
"caption6": "This is the sixth caption. This is optional.",
"label6": "Label 6. This is optional.",
}
};
$(document).ready(function(){
// variables for values
var val;
var w... |
//This function initializes the jQuery slider and shows the first slide
function buildSlider(){
$('#slide_images #image1').css("opacity", 1);
$('#slide_labels #label1').css("opacity", 1);
$('#slide_captions #caption1').css("opacity", 1);
currentImage = document.getElementById('image1');
currentLabel =... | {
$('.image').each(function() {
if (this.getAttribute('id') == 'image' + start || this.getAttribute('id') == 'image' + end) {
return;
}
$(this).css({opacity: 0});
});
} | identifier_body |
iconfont.js | 4.872 0 0 1 5.048 4.568l2.544 52.656a4.816 4.816 0 0 1-4.56 5.04h-0.232z" fill="#FDF1F6" ></path>' +
'' +
'<path d="M378.752 490.664l-0.232-0.008-52.656-2.552a4.808 4.808 0 0 1 0.472-9.616l52.64 2.56a4.8 4.8 0 0 1-0.224 9.616z" fill="#FDF1F6" ></path>' +
'' +
'<path d="M378.736 490.664a4.824 4.824 0 0 1... | {
var d = w.document,
done = false,
// only fire once
init = function() {
if (!done) {
done = true
fn()
}
}
// polling for no errors
var polling = function() {
try {
// throws errors until after ondocumentr... | identifier_body | |
iconfont.js | .616l52.64 2.56a4.8 4.8 0 0 1-0.224 9.616z" fill="#FDF1F6" ></path>' +
'' +
'<path d="M378.736 490.664a4.824 4.824 0 0 1-4.8-4.576l-2.544-52.656a4.808 4.808 0 0 1 4.56-5.04 4.848 4.848 0 0 1 5.032 4.568l2.56 52.664a4.792 4.792 0 0 1-4.576 5.032l-0.232 0.008z" fill="#FDF1F6" ></path>' +
'' +
'</symbol>' ... | {
before(el, target.firstChild)
} | conditional_block | |
iconfont.js | a4.8 4.8 0 0 1-0.224 9.616z" fill="#FDF1F6" ></path>' +
'' +
'<path d="M378.736 490.664a4.824 4.824 0 0 1-4.8-4.576l-2.544-52.656a4.808 4.808 0 0 1 4.56-5.04 4.848 4.848 0 0 1 5.032 4.568l2.56 52.664a4.792 4.792 0 0 1-4.576 5.032l-0.232 0.008z" fill="#FDF1F6" ></path>' +
'' +
'</symbol>' +
'' +
... | appendSvg | identifier_name | |
iconfont.js | .928l-0.248-0.008-52.656-2.56a4.784 4.784 0 0 1-4.56-5.032 4.832 4.832 0 0 1 5.032-4.568l52.656 2.56a4.784 4.784 0 0 1 4.56 5.032 4.784 4.784 0 0 1-4.784 4.576z" fill="#FDF1F6" ></path>' +
'' +
'<path d="M469.016 631.024a4.824 4.824 0 0 1-4.816-4.576l-2.544-52.648a4.8 4.8 0 0 1 4.56-5.04 4.872 4.872 0 0 1 5.048... | '</symbol>' + | random_line_split | |
main.rs | AZIOT_IDENTITYD_CONFIG_DIR",
"/etc/aziot/identityd/config.d",
)
.await?
}
ProcessName::Keyd => {
run(
aziot_keyd::main,
"AZIOT_KEYD_CONFIG",
"/etc/aziot/keyd/config.toml",
"AZIOT_KEYD_CON... | hyper::Request<hyper::Body>,
Response = hyper::Response<hyper::Body>,
Error = std::convert::Infallible,
> + Clone
+ Send
+ 'static,
<TServer as hyper::service::Service<hyper::Request<hyper::Body>>>::Future: Send,
{
log::info!("Starting service...");
... | Output = Result<(http_common::Connector, TServer), Box<dyn std::error::Error>>,
>,
TServer: hyper::service::Service< | random_line_split |
main.rs | IOT_IDENTITYD_CONFIG_DIR",
"/etc/aziot/identityd/config.d",
)
.await?
}
ProcessName::Keyd => {
run(
aziot_keyd::main,
"AZIOT_KEYD_CONFIG",
"/etc/aziot/keyd/config.toml",
"AZIOT_KEYD_CONFI... |
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum ProcessName {
Certd,
Identityd,
Keyd,
Tpmd,
}
/// If the symlink is being used to invoke this binary, the process name can be determined
/// from the first arg, ie `argv[0]` in C terms.
///
/// An alternative is supported where the bin... | {
run(
aziot_tpmd::main,
"AZIOT_TPMD_CONFIG",
"/etc/aziot/tpmd/config.toml",
"AZIOT_TPMD_CONFIG_DIR",
"/etc/aziot/tpmd/config.d",
)
.await?
} | conditional_block |
main.rs | let arg = std::path::Path::new(&arg);
let process_name = arg.file_name().ok_or_else(|| {
ErrorKind::GetProcessName(
format!(
"could not extract process name from arg {:?}",
arg.display(),
)
.into(),
)
})?;
match process... | merge_toml | identifier_name | |
main.rs | "/etc/aziot/identityd/config.toml",
"AZIOT_IDENTITYD_CONFIG_DIR",
"/etc/aziot/identityd/config.d",
)
.await?
}
ProcessName::Keyd => {
run(
aziot_keyd::main,
"AZIOT_KEYD_CONFIG",
... | {
let mut args = std::env::args_os();
let process_name = process_name_from_args(&mut args)?;
match process_name {
ProcessName::Certd => {
run(
aziot_certd::main,
"AZIOT_CERTD_CONFIG",
"/etc/aziot/certd/config.toml",
"AZIOT_... | identifier_body | |
blackboxexporter.go | /core/v1"
policyv1 "k8s.io/api/policy/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
vpaautoscalingv1 "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"
"k8s.... |
func (b *blackboxExporter) computeResourcesData() (map[string][]byte, error) {
var (
intStrOne = intstr.FromInt(1)
registry = managedresources.NewRegistry(kubernetes.ShootScheme, kubernetes.ShootCodec, kubernetes.ShootSerializer)
serviceAccount = &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
... | {
timeoutCtx, cancel := context.WithTimeout(ctx, TimeoutWaitForManagedResource)
defer cancel()
return managedresources.WaitUntilDeleted(timeoutCtx, b.client, b.namespace, ManagedResourceName)
} | identifier_body |
blackboxexporter.go | /api/core/v1"
policyv1 "k8s.io/api/policy/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
vpaautoscalingv1 "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"
"... | Limits: corev1.ResourceList{
corev1.ResourceMemory: resource.MustParse("128Mi"),
},
},
Ports: []corev1.ContainerPort{
{
Name: "probe",
ContainerPort: int32(9115),
Protocol: corev1.ProtocolTCP,
},
},
... | corev1.ResourceCPU: resource.MustParse("10m"),
corev1.ResourceMemory: resource.MustParse("25Mi"),
}, | random_line_split |
blackboxexporter.go | values: values,
}
}
type blackboxExporter struct {
client client.Client
namespace string
values Values
}
func (b *blackboxExporter) Deploy(ctx context.Context) error {
data, err := b.computeResourcesData()
if err != nil {
return err
}
return managedresources.CreateForShoot(ctx, b.client, b.namesp... | getLabels | identifier_name | |
blackboxexporter.go | /core/v1"
policyv1 "k8s.io/api/policy/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
vpaautoscalingv1 "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1"
"k8s.... |
return managedresources.CreateForShoot(ctx, b.client, b.namespace, ManagedResourceName, managedresources.LabelValueGardener, false, data)
}
func (b *blackboxExporter) Destroy(ctx context.Context) error {
return managedresources.DeleteForShoot(ctx, b.client, b.namespace, ManagedResourceName)
}
// TimeoutWaitForMan... | {
return err
} | conditional_block |
mod.rs | , and remove that example from strata.
///
/// A `Shared Weight Table` maintains the sum of the weights of all examples in each stratum.
/// The `Assigner`s increase the value in the `Shared Weight Table` when a new example is inserted into
/// a stratum.
/// The `Sampler`s use the weights in the `S... | for i in 1..11 {
let t = get_example(vec![i as TFeature], i as f32); | random_line_split | |
mod.rs | disk, while a small number of examples remains
/// in memory to be writen to disk or just read from disk and ready to send out to the sampler.
///
/// The overall structure of the stratified storage is as follow:
///
/// >,
// sampling_signal: Receiver<Signal>,
// models: Receiver<Model>,
positive: String,
}
impl StratifiedStorage {
/// Create the stratified storage structure.
///
/// * `num_examples`: the total number of examp... | weights_table_w.update(index, Box::new(F64 { val: cur + weight }));
{
counts_table_w.refresh();
weights_table_w.refresh();
}
}
});
}
// Monitor the distribution of stra... | {
let strata = Strata::new(num_examples, feature_size, num_examples_per_block,
disk_buffer_filename);
let strata = Arc::new(RwLock::new(strata));
let (counts_table_r, mut counts_table_w) = evmap::new();
let (weights_table_r, mut weights_table_w) = evmap:... | identifier_body |
mod.rs | Sender<ExampleWithScore>,
// sampled_examples_s: Sender<(ExampleWithScore, u32)>,
// sampling_signal: Receiver<Signal>,
// models: Receiver<Model>,
positive: String,
}
impl StratifiedStorage {
/// Create the stratified storage structure.
///
/// * `num_examples`: the total number of examp... | else {
0
}
}).collect();
let mapped_data = Labeled | {
bins[idx - range.start].get_split_index(*val)
} | conditional_block |
my.js | 时后返回的角度,所以应该还是回到最原始的位置,2160是因为我要让它转6圈,就是360*6得来的
duration:8000,
callback:function (){
alert('网络超时,请检查您的网络设置!');
}
});
};
//旋转转盘 item:奖品位置; txt:提示语;
function rotateFn(item, txt){
//alert(111);
var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length*2));
if(angles<270... | $('.stop').show();
if(turnplate.bRotate) return;
turnplate
.bRotate = !turnplate.bRotate;
$.ajax({
type : 'get',
url : base_url+ '&r=activity/lucky-draw',
success : function(res){
var res = res;
var item = res.data[0];
var gift = res.data[1];
rotateFn(item, gift)... | = !turnplate.bRotate;
}
});
};
$('.pointer').click(function (){
// $.ajax({
// type : 'post',
// url : base_url + '&r=activity/free-draw',
// data : { user_id : 12345 },
// success : function(res){
// var res = res;
// if( res.ret_code == 2070 ){
// alert('您今日免费抽奖次数已用完,如需再次抽奖,需消耗10钻石/次,请确认是否继... | identifier_body |
my.js | ()
{
var name,value;
var str=location.href; //取得整个地址栏
var num=str.indexOf("?")
str=str.substr(num+1); //取得所有参数 stringvar.substr(start [, length ]
var arr=str.split("&"); //各个参数放到数组里
for(var i=0;i < arr.length;i++){
num=arr[i].indexOf("=");
if(num>0){
name=arr[i].substring(0,num);
value=arr[i].substr(... | UrlSearch | identifier_name | |
my.js | 时后返回的角度,所以应该还是回到最原始的位置,2160是因为我要让它转6圈,就是360*6得来的
duration:8000,
callback:function (){
alert('网络超时,请检查您的网络设置!');
}
});
};
//旋转转盘 item:奖品位置; txt:提示语;
function rotateFn(item, txt){
//alert(111);
var angles = item * (360 / turnplate.restaraunts.length) - (360 / (turnplate.restaraunts.length*2));
if(angles<270... | // 中奖区的高度和大转盘一致
var h = $('.turnplate').height();
console.log(h);
$('.txt').height(h);
// 关闭中奖提示框
$('.off').click(function(){
$('.box').hide();
});
// 选项卡切换
$("#content ul").hide(); // Initially hide all content
$("#tabs li:first").attr("id","current"); // Activate first tab
$("#content ul:first").fadeIn(); // Sho... | }
| random_line_split |
core.go | return false
}
}
func (r *Rule) checkIP(v interface{}) (bool, error) {
if strings.HasSuffix(strings.ToLower(r.Key), "ip") {
ver1, ok := r.Val.(string)
if ok {
ver2, ok := v.(string)
if ok {
if len(strings.Split(ver2, ".")) == 4 {
return CheckIP(ver2, ver1), nil
}
}
}
}
return false, e... | edle
var iNum float64
var err error
if isNeedleNum {
if iNum, err = strconv.ParseFloat(needle, 64); err != nil {
return false
}
}
// compatible to "1, 2, 3" and "1,2,3"
li := strings.Split(haystack, ",")
for _, o := range li {
trimO := strings.TrimLeft(o, " ")
if isNeedleNum {
oNum, err := strconv.... | identifier_body | |
core.go | func validLogic(logic string) (string, error) {
formatLogic := formatLogicExpression(logic)
if formatLogic == Space || formatLogic == EmptyStr {
return EmptyStr, nil
}
// validate the formatLogic string
// 1. only contain legal symbol
isValidSymbol := isFormatLogicExpressionAllValidSymbol(formatLogic)
if !isVa... | )
| random_line_split | |
core.go |
for _, rule := range rs.Rules {
v := pluck(rule.Key, o)
if v != nil && rule.Val != nil {
typeV := reflect.TypeOf(v)
typeR := reflect.TypeOf(rule.Val)
if !typeV.Comparable() || !typeR.Comparable() {
return false, nil, nil
}
}
values[rule.ID] = v
flag := rule.fit(v)
results[rule.ID] = flag
... | {
hasLogic = true
} | conditional_block | |
core.go | pairNum[1] = formatNumber(r.Val)
isStr = false
isRuleStr = false
} else {
isNum = false
isRuleStr = true
}
var flagOpIn bool
// if in || nin
if op == "@" || op == "in" || op == "!@" || op == "nin" || op == "<<" || op == "between" {
flagOpIn = true
if !isObjStr && isRuleStr {
pairStr[0] = strconv.F... | nAllIdsExist(strFormatLogic string | identifier_name | |
main.rs | renderer;
mod sampling;
mod scene;
mod shading;
mod surface;
mod timer;
mod tracer;
mod transform_stack;
use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr};
use clap::{App, Arg};
use nom::bytes::complete::take_until;
use kioku::Arena;
use crate::{
accel::BVH4Node,
bbox::BBox,
parse::{pars... |
if !args.is_present("serialized_output") {
println!("Rendering scene with {} threads...", thread_count);
}
let (mut image, rstats) = r.render(
max_samples_per_bucket,
crop,
thread_count,
... | {
println!("\tBuilt scene in {:.3}s", t.tick());
} | conditional_block |
main.rs | renderer;
mod sampling;
mod scene;
mod shading;
mod surface;
mod timer;
mod tracer;
mod transform_stack;
use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr};
use clap::{App, Arg};
use nom::bytes::complete::take_until;
use kioku::Arena;
use crate::{
accel::BVH4Node,
bbox::BBox,
parse::{pars... | .value_name("N")
.help("Number of samples per pixel")
.takes_value(true)
.validator(|s| {
usize::from_str(&s)
.and(Ok(()))
.or(Err("must be an integer".to_string()))
}),
... | {
let mut t = Timer::new();
// Parse command line arguments.
let args = App::new("Psychopath")
.version(VERSION)
.about("A slightly psychotic path tracer")
.arg(
Arg::with_name("input")
.short("i")
.long("input")
.value_nam... | identifier_body |
main.rs | renderer;
mod sampling;
mod scene;
mod shading;
mod surface;
mod timer;
mod tracer;
mod transform_stack;
use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr};
use clap::{App, Arg};
use nom::bytes::complete::take_until;
use kioku::Arena;
use crate::{
accel::BVH4Node,
bbox::BBox,
parse::{pars... | () {
let mut t = Timer::new();
// Parse command line arguments.
let args = App::new("Psychopath")
.version(VERSION)
.about("A slightly psychotic path tracer")
.arg(
Arg::with_name("input")
.short("i")
.long("input")
.value_... | main | identifier_name |
main.rs | renderer;
mod sampling;
mod scene;
mod shading;
mod surface;
mod timer;
mod tracer;
mod transform_stack;
use std::{fs::File, io, io::Read, mem, path::Path, str::FromStr};
use clap::{App, Arg};
use nom::bytes::complete::take_until;
use kioku::Arena;
use crate::{
accel::BVH4Node,
bbox::BBox,
parse::{pars... | let arena = Arena::new().with_block_size((1 << 20) * 4);
let mut r = parse_scene(&arena, child).unwrap_or_else(|e| {
e.print(&psy_contents);
panic!("Parse error.");
});
if let Some(spp) = args.value_of("spp") {
... | if !args.is_present("serialized_output") {
println!("Building scene...");
}
| random_line_split |
index.ts | import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import { CognitoIdentityCredentials } from "@aws-sdk/credential-provider-cognito-identity/dist-types/fromCognitoIdentity"
// @ts-ignore
import Settings = require('./settings');
import {toUtf8} from "@aws-sdk/util-utf8-browser";
const $: JQuerySta... |
}
});
// Invoked when the client stops
this.client.on('stopped', (eventData: mqtt5.StoppedEvent) => {
log("[" + this.name + "]: Stopped");
});
}
// Helper function to make sample code a little cleaner
public async startClient() {
const conne... | {
log(
"[" + this.name + "]: Shared Subscriptions not supported!" +
"\nThis sample will not work unless the endpoint being connected to has Shared Subscriptions support.");
} | conditional_block |
index.ts | import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import { CognitoIdentityCredentials } from "@aws-sdk/credential-provider-cognito-identity/dist-types/fromCognitoIdentity"
// @ts-ignore
import Settings = require('./settings');
import {toUtf8} from "@aws-sdk/util-utf8-browser";
const $: JQuerySta... |
// AWSCognitoCredentialOptions. The credentials options used to create AWSCongnitoCredentialProvider.
interface AWSCognitoCredentialOptions
{
IdentityPoolId : string,
Region: string
}
// AWSCognitoCredentialsProvider. The AWSCognitoCredentialsProvider implements AWS.CognitoIdentityCredentials.
class AWSCogni... | {
let now = new Date();
$('#console').append(`<pre>${now.toString()}: ${msg}</pre>`);
} | identifier_body |
index.ts | import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import { CognitoIdentityCredentials } from "@aws-sdk/credential-provider-cognito-identity/dist-types/fromCognitoIdentity"
// @ts-ignore
import Settings = require('./settings');
import {toUtf8} from "@aws-sdk/util-utf8-browser";
const $: JQuerySta... |
try
{
// Connect all the clients
await publisher.startClient();
await subscriber_one.startClient();
await subscriber_two.startClient();
// Subscribe to the shared topic on the two subscribers
await subscriber_one.client?.subscribe({subscriptions: [{qos: mqtt5.Qo... | random_line_split | |
index.ts | import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import { CognitoIdentityCredentials } from "@aws-sdk/credential-provider-cognito-identity/dist-types/fromCognitoIdentity"
// @ts-ignore
import Settings = require('./settings');
import {toUtf8} from "@aws-sdk/util-utf8-browser";
const $: JQuerySta... | (
provider: AWSCognitoCredentialsProvider,
input_endpoint : string, input_region: string, input_clientId : string, input_clientName : string)
{
this.name = input_clientName;
let wsConfig : iot.WebsocketSigv4Config = {
credentialsProvider: provider,
region: in... | setupMqtt5Client | identifier_name |
elements.rs | under the License.
*/
use crate::{
BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited,
SectionReader, SectionWithLimitedItems, ValType,
};
use std::ops::Range;
/// Represents a core WebAssembly element segment.
#[derive(Clone)]
pub struct Element<'a> {
/// The kind ... |
fn size_hint(&self) -> (usize, Option<usize>) {
let count = self.reader.get_count() as usize;
(count, Some(count))
}
}
/// A reader for the element section of a WebAssembly module.
#[derive(Clone)]
pub struct ElementSectionReader<'a> {
reader: BinaryReader<'a>,
count: u32,
}
impl<'a> ... | {
if self.err || self.left == 0 {
return None;
}
let result = self.reader.read();
self.err = result.is_err();
self.left -= 1;
Some(result)
} | identifier_body |
elements.rs | under the License.
*/
use crate::{
BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited,
SectionReader, SectionWithLimitedItems, ValType,
};
use std::ops::Range;
/// Represents a core WebAssembly element segment.
#[derive(Clone)]
pub struct Element<'a> {
/// The kind ... | /// ```
pub fn read<'b>(&mut self) -> Result<Element<'b>>
where
'a: 'b,
{
let elem_start = self.reader.original_position();
// The current handling of the flags is largely specified in the `bulk-memory` proposal,
// which at the time this commend is written has been merge... | /// for _ in 0..items_reader.get_count() {
/// let item = items_reader.read().expect("item");
/// println!(" Item: {:?}", item);
/// }
/// } | random_line_split |
elements.rs | under the License.
*/
use crate::{
BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited,
SectionReader, SectionWithLimitedItems, ValType,
};
use std::ops::Range;
/// Represents a core WebAssembly element segment.
#[derive(Clone)]
pub struct Element<'a> {
/// The kind ... |
let kind = if flags & 0b001 != 0 {
if flags & 0b010 != 0 {
ElementKind::Declared
} else {
ElementKind::Passive
}
} else {
let table_index = if flags & 0b010 == 0 {
0
} else {
self... | {
return Err(BinaryReaderError::new(
"invalid flags byte in element segment",
self.reader.original_position() - 1,
));
} | conditional_block |
elements.rs | under the License.
*/
use crate::{
BinaryReader, BinaryReaderError, ConstExpr, ExternalKind, Result, SectionIteratorLimited,
SectionReader, SectionWithLimitedItems, ValType,
};
use std::ops::Range;
/// Represents a core WebAssembly element segment.
#[derive(Clone)]
pub struct Element<'a> {
/// The kind ... | (&self) -> u32 {
self.count
}
/// Reads content of the element section.
///
/// # Examples
///
/// ```no_run
/// # let data: &[u8] = &[];
/// use wasmparser::{ElementSectionReader, ElementKind};
/// let mut element_reader = ElementSectionReader::new(data, 0).unwrap();
//... | get_count | identifier_name |
graph_runner.ts | const DEFAULT_INFERENCE_EXAMPLE_INTERVAL_MS = 3000;
export interface GraphRunnerEventObserver {
batchesTrainedCallback?: (totalBatchesTrained: number) => void;
avgCostCallback?: (avgCost: Scalar) => void;
metricCallback?: (metric: Tensor) => void;
inferenceExamplesCallback?:
(feeds: FeedEntry[][], infere... | stopInferring | identifier_name | |
graph_runner.ts | It allows
* the user to provide a set of callbacks for measurements like cost, accuracy,
* and speed of training.
*/
export class GraphRunner {
private costTensor: SymbolicTensor;
private trainFeedEntries: FeedEntry[];
private batchSize: number;
private optimizer: Optimizer;
private currentTrainLoopNumBat... | {
metric = this.math.divide(metric, this.metricBatchSizeScalar);
} | conditional_block | |
graph_runner.ts | Entries: FeedEntry[];
private batchSize: number;
private optimizer: Optimizer;
private currentTrainLoopNumBatches: number|undefined;
private costIntervalMs: number;
private metricTensor: SymbolicTensor|undefined;
private metricFeedEntries: FeedEntry[]|undefined;
private metricBatchSize: number|undefined;... | {
return this.lastComputedMetric;
} | identifier_body | |
graph_runner.ts | Entries: FeedEntry[];
private batchSize: number;
private optimizer: Optimizer;
private currentTrainLoopNumBatches: number|undefined;
private costIntervalMs: number;
private metricTensor: SymbolicTensor|undefined;
private metricFeedEntries: FeedEntry[]|undefined;
private metricBatchSize: number|undefined;... |
getLastComputedMetric(): Scalar {
return this.lastComputedMetric;
} | random_line_split | |
training_modified.py | batch includes a training image, its mask and the 7 augmented versions of it, which are generated on the fly
# batch size means in this case how many original images are loaded for 1 batch,
# the actual batch size is 8 times higher.
# based on https://www.kaggle.com/mukulkr/camvid-segmentation-using-unet
class DataGen... |
# generates a batch
def __data_generation(self, list_IDs_temp, second_half=False):
batch_images = []
batch_masks = []
for i in list_IDs_temp:
# parses the image and the mask of the current pair and then generates the augmented versions
# it wasn't possible to ... | tf.random.shuffle(self.indexes) | conditional_block |
training_modified.py | batch includes a training image, its mask and the 7 augmented versions of it, which are generated on the fly
# batch size means in this case how many original images are loaded for 1 batch,
# the actual batch size is 8 times higher.
# based on https://www.kaggle.com/mukulkr/camvid-segmentation-using-unet
class DataGen... | def __data_generation(self, list_IDs_temp, second_half=False):
batch_images = []
batch_masks = []
for i in list_IDs_temp:
# parses the image and the mask of the current pair and then generates the augmented versions
# it wasn't possible to generate the augmented ima... | if self.shuffle == True:
tf.random.shuffle(self.indexes)
# generates a batch | random_line_split |
training_modified.py | batch includes a training image, its mask and the 7 augmented versions of it, which are generated on the fly
# batch size means in this case how many original images are loaded for 1 batch,
# the actual batch size is 8 times higher.
# based on https://www.kaggle.com/mukulkr/camvid-segmentation-using-unet
class DataGen... | (self):
return int(tf.math.floor(len(self.pair) / self.batch_size))
# returns a single batch
def __getitem__(self, index):
# a list that has the indexes of the pairs from which we want to generate images and masks for the batch
indexes = self.indexes[index*self.batch_size:(index+1)*self... | __len__ | identifier_name |
training_modified.py | returns the length of the data set
def __len__(self):
return int(tf.math.floor(len(self.pair) / self.batch_size)) * 2
# returns a single batch
def __getitem__(self, index):
# a list that has the indexes of the pairs from which we want to generate images and masks for the batch
ind... | return pixelwise_crossentropy(y_true, y_predict) + dice_loss(y_true, y_predict) | identifier_body | |
framebuffer.rs | PassAbstract + Send + Sync> = return;
/// # let my_image: Arc<vulkano::image::ImageViewAccess> = return;
/// // let render_pass: Arc<RenderPassAbstract + Send + Sync> = ...;
/// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1],
/// vec![my_image.clone() as Arc<_>... | where Rp: RenderPassDescAttachmentsList<At>
{
#[inline]
fn check_attachments_list(&self, atch: At) -> Result<Box<AttachmentsList + Send + Sync>, FramebufferCreationError> {
self.render_pass.check_attachments_list(atch)
}
}
unsafe impl<C, Rp, A> RenderPassDescClearValues<C> for Framebuffer<Rp, A... | }
}
unsafe impl<At, Rp, A> RenderPassDescAttachmentsList<At> for Framebuffer<Rp, A> | random_line_split |
framebuffer.rs | PassAbstract + Send + Sync> = return;
/// # let my_image: Arc<vulkano::image::ImageViewAccess> = return;
/// // let render_pass: Arc<RenderPassAbstract + Send + Sync> = ...;
/// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1],
/// vec![my_image.clone() as Arc<_>... | <Ia>(render_pass: Rp, dimensions: [u32; 3], attachments: Ia)
-> Result<Arc<Framebuffer<Rp, Box<AttachmentsList + Send + Sync>>>, FramebufferCreationError>
where Rp: RenderPassAbstract + RenderPassDescAttachmentsList<Ia>
{
let device = render_pass.device().clone();
// This... | new | identifier_name |
framebuffer.rs | PassAbstract + Send + Sync> = return;
/// # let my_image: Arc<vulkano::image::ImageViewAccess> = return;
/// // let render_pass: Arc<RenderPassAbstract + Send + Sync> = ...;
/// let framebuffer = Framebuffer::new(render_pass.clone(), [1024, 768, 1],
/// vec![my_image.clone() as Arc<_>... |
}
// Checking the dimensions against the attachments.
if let Some(dims_constraints) = attachments.intersection_dimensions() {
if dims_constraints[0] < dimensions[0] || dims_constraints[1] < dimensions[1] ||
dims_constraints[2] < dimensions[2]
{
... | {
return Err(FramebufferCreationError::DimensionsTooLarge);
} | conditional_block |
utils.go | 02 Jan 2006 15:04:05 -07:00",
"Mon, 02 Jan 2006 15:04:05 00",
"Mon, 02 Jan 2006 15:04:05 MST -0700",
"Mon, 02 Jan 2006 15:04:05 MST",
"Mon, 02 Jan 2006 15:04:05 MST-07:00",
"Mon, 02 Jan 2006 15:04:05 UT",
"Mon, 02 Jan 2006 15:04:05 Z",
"Mon, 02 Jan 2006 15:04:05",
"Mon, 02 Jan 2006 15:04:05MST",
"Mon, 02 Jan 2... | {
i.Title = i.Description
} | conditional_block | |
utils.go | 6 15:04:05",
"Monday, 2 Jan 2006 15:04:05 -0700",
"Monday, 2 Jan 2006 15:04:05 MST",
"Monday, 2 January 2006 15:04:05 -0700",
"Monday, 2 January 2006 15:04:05 MST",
"Monday, January 02, 2006",
"Monday, January 2, 2006 03:04 PM",
"Monday, January 2, 2006 15:04:05 MST",
"Monday, January 2, 2006",
"Updated Januar... | link, err := base.Parse(s.Link) | random_line_split | |
utils.go | 04:05 MST",
"Monday, January 2, 2006",
"Updated January 2, 2006",
"mon,2 Jan 2006 15:04:05 MST",
time.ANSIC,
time.RFC1123,
time.RFC1123Z,
time.RFC3339,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RubyDate,
time.UnixDate,
}
func parseDate(c appengine.Context, feed *Feed, ds ...string) (t time.Time, err err... | loadImage | identifier_name | |
utils.go | i.User = user
i.IsAdmin = cu.Admin
if len(user.Messages) > 0 {
i.Messages = user.Messages
user.Messages = nil
gn.Put(user)
}
/*
if _, err := r.Cookie("update-bug"); err != nil {
i.Messages = append(i.Messages, "Go Read had some problems updating feeds. It may take a while for new s... | {
i := &Includes{
Angular: Angular,
BootstrapCss: BootstrapCss,
BootstrapJs: BootstrapJs,
Jquery: Jquery,
JqueryUI: JqueryUI,
Underscore: Underscore,
MiniProfiler: c.Includes(r),
GoogleAnalyticsId: GOOGLE_ANALYTICS_ID,
GoogleAnalyti... | identifier_body | |
main.rs | : {}, {}", x, y),
}
}
enum Number_enum {
Zero,
One,
Two,
}
// enum with explicit discriminator
enum Color {
Red = 0xff0000,
Green = 0x00ff00,
Blue = 0x0000ff,
}
fn test_enum() {
let pressed = KeyPress('x');
// `to_owned()` creates an owned `String` from a string slice.
let pas... | else {
println!("`i` is `{:?}`. Try again.", i);
optional = Some(i + 1);
}
}
}
fn isDivisibleBy(lhs: u32, rhs: u32) -> bool {
if (rhs == 0) {
return false;
}
lhs % rhs == 0
}
impl Point {
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
fn... | {
println!("Number is: {}", i);
optional = None;
} | conditional_block |
main.rs | let i = 1;
let f = 1.0;
// `size_of_val` returns the size of a variable in bytes
println!("size of `x` in bytes: {}", std::mem::size_of_val(&x));
println!("size of `y` in bytes: {}", std::mem::size_of_val(&y));
println!("size of `z` in bytes: {}", std::mem::size_of_val(&z));
println!("size ... | random_line_split | ||
main.rs | );
call_me(closure);
}
fn create_fn() -> impl Fn() {
let text = "Fn".to_owned();
move || println!("This is a text: {}", text)
}
fn create_fn_mut() -> impl FnMut() {
let text = "FnMut".to_owned();
move || println!("This is a text: {}", text)
}
fn create_fn_once() -> impl FnOnce() {
let text = ... | dyReturn | identifier_name | |
main.rs | println!(" -1 as a u8 is : {:b}", (-1i8) as u8);
println!("1000 mod 256 is : {:b}", 1000 % 256);
// Unless it already fits, of course.
println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16);
// 128 as u8 -> 128, whose two's complement in eight bits is:
let num: i16 = 128;
println... | {
let x = 30;
println!("x: {:?}", x);
let y = apply_to_3(|x| x + 20);
println!("y: {:?}", y);
let greeting = "Hello";
let mut farewel = "Goodby".to_owned();
let diary = || {
println!("I said {}", greeting);
farewel.push_str("!!!!!");
println!("Than I screemed {}... | identifier_body | |
dec.rs | tuple (lhs, rhs).
Exp::InfixApp(lhs, func, rhs) => {
let val_info = get_val_info(&cx.env, *func)?;
let func_ty = instantiate(st, &val_info.ty_scheme);
let lhs_ty = ck_exp(cx, st, lhs)?;
let rhs_ty = ck_exp(cx, st, rhs)?;
let ret_ty = Ty::Var(st.new_ty_var(false));
let arrow_ty =... |
pub fn ck(cx: &Cx, st: &mut State, dec: &Located<Dec<StrRef>>) -> Result<Env> {
match &dec.val {
// SML Definition (15)
Dec::Val(ty_vars, val_binds) => {
let mut cx_cl;
let cx = if ty_vars.is_empty() {
cx
} else {
cx_cl = cx.clone();
insert_ty_vars(&mut cx_cl, st, t... | {
fun_infos
.iter()
.map(|(&name, fun_info)| {
let ty = fun_info
.args
.iter()
.rev()
.fold(Ty::Var(fun_info.ret), |ac, &tv| {
Ty::Arrow(Ty::Var(tv).into(), ac.into())
});
(name, ValInfo::val(TyScheme::mono(ty)))
})
.collect()
} | identifier_body |
dec.rs | a tuple (lhs, rhs).
Exp::InfixApp(lhs, func, rhs) => {
let val_info = get_val_info(&cx.env, *func)?;
let func_ty = instantiate(st, &val_info.ty_scheme);
let lhs_ty = ck_exp(cx, st, lhs)?;
let rhs_ty = ck_exp(cx, st, rhs)?;
let ret_ty = Ty::Var(st.new_ty_var(false));
let arrow_ty... | Dec::Fun(ty_vars, fval_binds) => {
let mut cx_cl;
let cx = if ty_vars.is_empty() {
cx
} else {
cx_cl = cx.clone();
insert_ty_vars(&mut cx_cl, st, ty_vars)?;
&cx_cl
};
let mut fun_infos = HashMap::with_capacity(fval_binds.len());
for fval_bind in fv... | random_line_split | |
dec.rs | a tuple (lhs, rhs).
Exp::InfixApp(lhs, func, rhs) => {
let val_info = get_val_info(&cx.env, *func)?;
let func_ty = instantiate(st, &val_info.ty_scheme);
let lhs_ty = ck_exp(cx, st, lhs)?;
let rhs_ty = ck_exp(cx, st, rhs)?;
let ret_ty = Ty::Var(st.new_ty_var(false));
let arrow_ty... | (cx: &Cx, st: &mut State, cases: &Cases<StrRef>) -> Result<(Vec<Located<Pat>>, Ty, Ty)> {
let arg_ty = Ty::Var(st.new_ty_var(false));
let res_ty = Ty::Var(st.new_ty_var(false));
let mut pats = Vec::with_capacity(cases.arms.len());
// SML Definition (14)
for arm in cases.arms.iter() {
let (val_env, pat_ty,... | ck_cases | identifier_name |
gittrack_controller.go | itTrack,
namespace: farosflags.Namespace,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
opts := &reconcileGitTrackOpts{
gitTrackMode: farosflags.GitTrack,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
return rec, opts
}
// reconcileGitTrackOpts is the mode that we're running the ... | }
// successResult is a convenience function for creating a success objectResult
func successResult(namespacedName string, timeToDeploy time.Duration, inSync bool) objectResult {
return objectResult{NamespacedName: namespacedName, TimeToDeploy: timeToDeploy, InSync: inSync}
}
func (r *ReconcileGitTrack) newGitTrackO... |
// ignoreResult is a convenience function for creating an ignore objectResult
func ignoreResult(namespacedName string, reason string) objectResult {
return objectResult{NamespacedName: namespacedName, Ignored: true, Reason: reason} | random_line_split |
gittrack_controller.go |
applier, err := farosclient.NewApplier(mgr.GetConfig(), farosclient.Options{})
if err != nil {
panic(fmt.Errorf("unable to create applier: %v", err))
}
rec := &ReconcileGitTrack{
Client: mgr.GetClient(),
scheme: mgr.GetScheme(),
store: gitstore.NewRepoStore(farosfl... | {
panic(fmt.Errorf("unable to parse ignored resources: %v", err))
} | conditional_block | |
gittrack_controller.go | Track,
namespace: farosflags.Namespace,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
opts := &reconcileGitTrackOpts{
gitTrackMode: farosflags.GitTrack,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
return rec, opts
}
// reconcileGitTrackOpts is the mode that we're running the re... |
// listObjectsByName lists and filters GitTrackObjects by the `faros.pusher.com/owned-by` label,
// and returns a map of names to GitTrackObject mappings
func (r *ReconcileGitTrack) listObjectsByName(owner farosv1alpha1.GitTrackInterface) (map[string]farosv1alpha1.GitTrackObjectInterface, error) {
result := make(map... | {
var instance farosv1alpha1.GitTrackInterface
if req.Namespace != "" {
instance = &farosv1alpha1.GitTrack{}
} else {
instance = &farosv1alpha1.ClusterGitTrack{}
}
err := r.Get(context.TODO(), req.NamespacedName, instance)
if err != nil {
if errors.IsNotFound(err) {
// Object not found, return. Created ... | identifier_body |
gittrack_controller.go | itTrack,
namespace: farosflags.Namespace,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
opts := &reconcileGitTrackOpts{
gitTrackMode: farosflags.GitTrack,
clusterGitTrackMode: farosflags.ClusterGitTrack,
}
return rec, opts
}
// reconcileGitTrackOpts is the mode that we're running the ... | (mgr manager.Manager, r reconcile.Reconciler, opts *reconcileGitTrackOpts) error {
// Create a new controller
c, err := controller.New("gittrack-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
if opts.gitTrackMode == farosflags.GTMEnabled {
// Watch for changes to GitTrack
... | add | identifier_name |
parse.go |
// Parse returns the parse tree for the XML from the given Reader.
func Parse(r io.Reader) (*Node, error) {
return ParseWithOptions(r, ParserOptions{})
}
// ParseWithOptions is like parse, but with custom options
func ParseWithOptions(r io.Reader, options ParserOptions) (*Node, error) {
p := createParser(r)
optio... | {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Make sure the Content-Type has a valid XML MIME type
if xmlMIMERegex.MatchString(resp.Header.Get("Content-Type")) {
return Parse(resp.Body)
}
return nil, fmt.Errorf("invalid XML document(%s)", resp.Header.Get("Content-... | identifier_body | |
parse.go | (r io.Reader, options ParserOptions) (*Node, error) {
p := createParser(r)
options.apply(p)
for {
_, err := p.parse()
if err == io.EOF {
return p.doc, nil
}
if err != nil {
return nil, err
}
}
}
type parser struct {
decoder *xml.Decoder
doc *Node
level i... | ParseWithOptions | identifier_name | |
parse.go | node So we can clean it up upon next Read() call.
streamNodePrev *Node // Need to remember target node's prev so upon target node removal, we can restore correct prev.
reader *cachedReader // Need to maintain a reference to the reader, so we can determine whether a node contains CDATA.
}
f... | else if p.level < p.prev.level {
for i := p.prev.level - p.level; i > 1; i-- {
p.prev = p.prev.Parent
}
AddSibling(p.prev.Parent, node)
}
p.prev = node
case xml.Directive:
}
}
}
// StreamParser enables loading and parsing an XML document in a streaming
// fashion.
type StreamParser struct ... | {
AddChild(p.prev, node)
} | conditional_block |
parse.go | target node So we can clean it up upon next Read() call.
streamNodePrev *Node // Need to remember target node's prev so upon target node removal, we can restore correct prev.
reader *cachedReader // Need to maintain a reference to the reader, so we can determine whether a node contains CDAT... | decoder: xml.NewDecoder(reader),
doc: &Node{Type: DocumentNode},
level: 0,
reader: reader,
}
if p.decoder.CharsetReader == nil {
p.decoder.CharsetReader = charset.NewReaderLabel
}
p.prev = p.doc
return p
}
func (p *parser) parse() (*Node, error) {
var streamElementNodeCounter int
space2prefix :... | p := &parser{ | random_line_split |
RoomNotifs.ts | IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
import {
NotificationCountType,
ConditionKind,
PushRule... | // XXX: We have to assume the default is to notify for all messages
// (in particular this will be 'wrong' for one to one rooms because
// they will notify loudly for all messages)
if (!roomRule?.enabled) return RoomNotifState.AllMessages;
// a mute at the room level will still allow mentions
/... | {
if (client.isGuest()) return RoomNotifState.AllMessages;
// look through the override rules for a rule affecting this room:
// if one exists, it will take precedence.
const muteRule = findOverrideMuteRule(client, roomId);
if (muteRule) {
return RoomNotifState.Mute;
}
// for every... | identifier_body |
RoomNotifs.ts | IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
import {
NotificationCountType,
ConditionKind,
PushRule... | (rule: IPushRule): boolean {
// DontNotify is equivalent to the empty actions array
return (
rule.actions.length === 0 || (rule.actions.length === 1 && rule.actions[0] === PushRuleActionName.DontNotify)
);
}
export function determineUnreadState(
room?: Room,
threadId?: string,
): { color: N... | isMuteRule | identifier_name |
RoomNotifs.ts | IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { PushProcessor } from "matrix-js-sdk/src/pushprocessor";
import {
NotificationCountType,
ConditionKind,
PushRule... | rule.actions.length === 0 || (rule.actions.length === 1 && rule.actions[0] === PushRuleActionName.DontNotify)
);
}
export function determineUnreadState(
room?: Room,
threadId?: string,
): { color: NotificationColor; symbol: string | null; count: number } {
if (!room) {
return { symbol: ... |
function isMuteRule(rule: IPushRule): boolean {
// DontNotify is equivalent to the empty actions array
return ( | random_line_split |
parser.rs | ().map(|&b| char::from(b))
}
/// Read the next character from the input
fn read_char(&mut self) -> Option<char> {
self.state.split_first().map(|(&b, tail)| { |
#[must_use]
/// Read the next character from the input if it matches the target.
fn read_given_char(&mut self, target: char) -> Option<()> {
self.read_atomically(|p| {
p.read_char().and_then(|c| if c == target { Some(()) } else { None })
})
}
/// Helper for reading sepa... | self.state = tail;
char::from(b)
})
} | random_line_split |
parser.rs | ZERO;
let mut digit_count = 0;
let has_leading_zero = p.peek_char() == Some('0');
while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
result = result.checked_mul(radix)?;
result = result.checked_add(digit)?;
... | from_str | identifier_name | |
parser.rs | ().map(|&b| char::from(b))
}
/// Read the next character from the input
fn read_char(&mut self) -> Option<char> {
self.state.split_first().map(|(&b, tail)| {
self.state = tail;
char::from(b)
})
}
#[must_use]
/// Read the next character from the input if ... |
// Read a number off the front of the input in the given radix, stopping
// at the first non-digit character or eof. Fails if the number has more
// digits than max_digits or if there is no number.
#[allow(clippy::if_same_then_else)]
fn read_number<T: ReadNumberHelper>(
&mut self,
... | {
self.read_atomically(move |p| {
if index > 0 {
p.read_given_char(sep)?;
}
inner(p)
})
} | identifier_body |
cubic64.rs | ].sort_by(cmp_f64);
let mut valid_count = 0;
let mut index = 0;
while index < extrema {
let min = extreme_ts[index];
index += 1;
let max = extreme_ts[index];
if min == max {
continue;
}
let new_t = self.bina... | continue;
}
t = next_t;
}
let test_at_t = self.point_at_t(t);
cubic_at_t = test_at_t;
calc_pos = cubic_at_t.axis_coord(x_axis);
calc_dist = calc_pos - axis_intercept;
if calc_pos.approximately... | {
let next_t = t + last_step;
if next_t > max {
return -1.0;
}
let more_pt = self.point_at_t(next_t);
if more_pt.x.approximately_equal_half(cubic_at_t.x)
&& more_pt.y.approximately_equal_half(cubic_a... | conditional_block |
cubic64.rs | _t;
valid_count += 1;
}
}
valid_count
}
fn find_inflections(&self, t_values: &mut [f64]) -> usize {
let ax = self.points[1].x - self.points[0].x;
let ay = self.points[1].y - self.points[0].y;
let bx = self.points[2].x - 2.0 * self.points[1].x... |
return num; | random_line_split | |
cubic64.rs | ].sort_by(cmp_f64);
let mut valid_count = 0;
let mut index = 0;
while index < extrema {
let min = extreme_ts[index];
index += 1;
let max = extreme_ts[index];
if min == max {
continue;
}
let new_t = self.bina... | (src: &[f64]) -> (f64, f64, f64, f64) {
let mut a = src[6]; // d
let mut b = src[4] * 3.0; // 3*c
let mut c = src[2] * 3.0; // 3*b
let d = src[0]; // a
a -= d - c + b; // A = -a + 3*b - 3*c + d
b += 3.0 * d - 2.0 * c; // B = 3*a - 6*b + 3*c
c -= 3.0 * d; // C = -3*a + 3*b
(a, b, c, d... | coefficients | identifier_name |
cubic64.rs | ].sort_by(cmp_f64);
let mut valid_count = 0;
let mut index = 0;
while index < extrema {
let min = extreme_ts[index];
index += 1;
let max = extreme_ts[index];
if min == max {
continue;
}
let new_t = self.bina... | }
}
debug_assert!(found_roots < 3);
t[found_roots] = 0.0;
found_roots += 1;
}
}
found_roots
}
fn roots_real(a: f64, b: f64, c: f64, d: f64, s: &mut [f64; 3]) -> usize {
if a.approximately_zero()
&& a.approximately_zero_when_... | {
let mut s = [0.0; 3];
let real_roots = roots_real(a, b, c, d, &mut s);
let mut found_roots = quad64::push_valid_ts(&s, real_roots, t);
'outer: for index in 0..real_roots {
let t_value = s[index];
if !t_value.approximately_one_or_less() && t_value.between(1.0, 1.00005) {
for... | identifier_body |
main.py | ="Light blue", fg=mycolor)
l3.place(x=210, y=80)
l3=tk.Label(window1,text="Amount",bg="Light blue", fg=mycolor)
l3.place(x=310, y=80)
def store() :
global added_count
added_count=added_count+1
global e1,e2
usern=e1.get()
phno=e2.get()
x=entry1.get()
y=entry2.get()
z=entry3.get()
y=... | f=1
la1=tk.Label(w11,text=df_d.iloc[j][2],fg="White", bg=mycolor)
la2=tk.Label(w11,text=df_d.iloc[j][3],fg="White", bg=mycolor)
la3=tk.Label(w11,text=df_d.iloc[j][4],fg="White", bg=mycolor)
la4=tk.Label(w11,text=df_d.iloc[j][5],fg="White", bg=mycolor)
... | conditional_block | |
main.py | # now finally perform the auto completion
if self._hits:
self.delete(0,tk.END)
self.insert(0,self._hits[self._hit_index])
self.select_range(self.position,tk.END)
entry1.delete(0,tk.END)
entry1.insert... | () :
global ind
overall_user.extend(curr_user)
overall_phone.extend(curr_phone)
overall_date.extend(curr_date)
overall_time.extend(curr_time)
overall_name.extend(curr_name)
overall_price.extend(curr_price)
overall_quantity.extend(curr_quantity)
overall_amount.extend(curr_amount)
... | subm | identifier_name |
main.py |
def autocomplete(self, delta=0):
"""autocomplete the Entry, delta may be 0/1/-1 to cycle through possible hits"""
if delta: # need to delete selection otherwise we would fix the current position
self.delete(self.position, tk.END)
else: # ... | self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
self._hits = []
self._hit_index = 0
self.position = 0
self.bind('<KeyRelease>', self.handle_keyrelease) | identifier_body | |
main.py | from functools import partial
import requests
import pandas as pd
import numpy as np
import sys
import os
import tkinter.ttk
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
te=TransactionEncoder()
dff=pd.read_csv("./database.csv")
ind=110
det_ind=200
arrec=[]
mycolor... | import datetime | random_line_split | |
MapServiceDownload.py | import smtplib
import arcpy
import json
import urllib
import urllib2
import uuid
import math
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
# Set global variables
enableLogging = "false" # Use logger.info("Example..."), logger.warning("Example..."), logger.error("Example...")
logFile = "" # os.path.... | # Download the data
fileChunk = 16 * 1024
downloadedFile = os.path.join(arcpy.env.scratchFolder, "Data-" + str(uuid.uuid1()) + ".json")
with open(downloadedFile, 'wb') as file:
downloadCount = 0
while True:
chunk = respo... | mapServiceQuery2 = mapServiceLayer + "/query?where=" + serviceQuery + "&returnCountOnly=false&returnIdsOnly=false&returnGeometry=true&outFields=*&f=pjson"
response = urllib2.urlopen(mapServiceQuery2)
except urllib2.URLError, e:
arcpy.AddError("There was an e... | random_line_split |
MapServiceDownload.py | data to be overwritten
arcpy.env.overwriteOutput = True
# Set global variables
enableLogging = "false" # Use logger.info("Example..."), logger.warning("Example..."), logger.error("Example...")
logFile = "" # os.path.join(os.path.dirname(__file__), "Example.log")
sendErrorEmail = "false"
emailTo = ""
emailUser = ""
em... | logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
# Setup log message handler
logMessage = logging.FileHandler(logFile)
# Setup the log formatting
logFormat = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s", "%d/%m/%Y - %H:%M:%S")
# Add formatter ... | identifier_body | |
MapServiceDownload.py | enableLogging = "false" # Use logger.info("Example..."), logger.warning("Example..."), logger.error("Example...")
logFile = "" # os.path.join(os.path.dirname(__file__), "Example.log")
sendErrorEmail = "false"
emailTo = ""
emailUser = ""
emailPassword = ""
emailSubject = ""
emailMessage = ""
enableProxy = "false"
reques... | sendEmail | identifier_name | |
MapServiceDownload.py | import smtplib
import arcpy
import json
import urllib
import urllib2
import uuid
import math
# Enable data to be overwritten
arcpy.env.overwriteOutput = True
# Set global variables
enableLogging = "false" # Use logger.info("Example..."), logger.warning("Example..."), logger.error("Example...")
logFile = "" # os.path.... |
# Write chunk to output file
file.write(chunk)
downloadCount = downloadCount + 1
file.close()
# If it's the first request
if (count == 0):
# Create new dataset
arcpy.JSONToFeatures_conv... | break | conditional_block |
GatewayToAdventure.py | ] + "\n" for i in range(len(ls))]
print(f"\n{bcolors.CYAN}{''.join(outputList)}{bcolors.ENDC}")
sizeEssentialList = len(ls)
essentialsList = []
choiceInput = False
while choiceInput is False:
choices = input(f"{bcolors.CYAN}Input your selection as numbers 1,... | print(f"{bcolors.FAIL}Sorry, you failed.{bcolors.ENDC}")
if len(player.getAssets()) > self.minEssentials and perkReattempt:
print(f"{bcolors.WHITE}You are eligible for 1 reattempt.{bcolors.ENDC}")
perkReattempt = False
survivalResults = player.... | conditional_block | |
GatewayToAdventure.py |
class GameWorld:
"""Base class for creating different worlds in the game"""
def __init__(self, name='gameWorld', typeW='all'):
self.worldName = name
self.worldType = typeW
self.essentials = []
self.qualifyingQuiz = QualifyingQuiz()
self.survivalQuiz1 = SurvivalQuiz()
... | """Child class to Quiz class that stores dictionary of questions and answers for the Survival quizzes"""
def __init__(self, qNADict={"Ques2": "Ans2"}):
self.questionAndAnswer = qNADict | identifier_body | |
GatewayToAdventure.py | :
"""Base class to store dictionary of questions and answers for the game quizzes"""
def __init__(self, qNADict={"Ques": "Ans"}):
self.questionAndAnswer = qNADict
class QualifyingQuiz(Quiz):
"""Child class to Quiz class that stores dictionary of questions and answers for the qualifying quiz"""
... | Quiz | identifier_name | |
GatewayToAdventure.py | "
}
qNADictS1 = {
"Q1: What would you select to climb in tricky mountain conditions?\n a. Mountaineering boots\n b. mountains": "a",
"Q2: What would you do if someone calls for help?\n a. It's their problem, I will just ignore\n b. Go and help them": "b"
}
qNADictS2 = {
"Q1: Which of the fo... | userLocation = userLocation.capitalize()
if userLocation in worldList:
validInput = True
else: | random_line_split | |
eqivalence.go | "
"k8s.io/kubernetes/pkg/scheduler/algorithm"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
schedulercache "k8s.io/kubernetes/pkg/scheduler/cache"
hashutil "k8s.io/kubernetes/pkg/util/hash"
"github.com/golang/glog"
)
// Cache saves and reuses the output of predicate functions. Use RunPredicate to
// get... |
// InvalidatePredicatesOnNode clears cached results for the given predicates on one node.
func (c *Cache) InvalidatePredicatesOnNode(nodeName string, predicateKeys sets.String) {
if len(predicateKeys) == 0 {
return
}
c.mu.Lock()
defer c.mu.Unlock()
for predicateKey := range predicateKeys {
delete(c.cache[nod... | {
if len(predicateKeys) == 0 {
return
}
c.mu.Lock()
defer c.mu.Unlock()
// c.cache uses nodeName as key, so we just iterate it and invalid given predicates
for _, predicates := range c.cache {
for predicateKey := range predicateKeys {
delete(predicates, predicateKey)
}
}
glog.V(5).Infof("Cache invalida... | identifier_body |
eqivalence.go | sets"
"k8s.io/kubernetes/pkg/scheduler/algorithm"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
schedulercache "k8s.io/kubernetes/pkg/scheduler/cache"
hashutil "k8s.io/kubernetes/pkg/util/hash"
"github.com/golang/glog"
)
// Cache saves and reuses the output of predicate functions. Use RunPredicate to
//... | // NoDiskConflict: the newly scheduled pod fits to existing pods on this node,
// it will also fits to equivalence class of existing pods
// GeneralPredicates: will always be affected by adding a new pod
invalidPredicates := sets.NewString(predicates.GeneralPred)
// MaxPDVolumeCountPredicate: we check the volume... | random_line_split | |
eqivalence.go | "
"k8s.io/kubernetes/pkg/scheduler/algorithm"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
schedulercache "k8s.io/kubernetes/pkg/scheduler/cache"
hashutil "k8s.io/kubernetes/pkg/util/hash"
"github.com/golang/glog"
)
// Cache saves and reuses the output of predicate functions. Use RunPredicate to
// get... | (pod *v1.Pod, nodeName string) {
// MatchInterPodAffinity: we assume scheduler can make sure newly bound pod
// will not break the existing inter pod affinity. So we does not need to
// invalidate MatchInterPodAffinity when pod added.
//
// But when a pod is deleted, existing inter pod affinity may become invalid.... | InvalidateCachedPredicateItemForPodAdd | identifier_name |
eqivalence.go | "
"k8s.io/kubernetes/pkg/scheduler/algorithm"
"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
schedulercache "k8s.io/kubernetes/pkg/scheduler/cache"
hashutil "k8s.io/kubernetes/pkg/util/hash"
"github.com/golang/glog"
)
// Cache saves and reuses the output of predicate functions. Use RunPredicate to
// get... |
glog.V(5).Infof("Cache invalidation: node=%s,predicates=%v", nodeName, predicateKeys)
}
// InvalidateAllPredicatesOnNode clears all cached results for one node.
func (c *Cache) InvalidateAllPredicatesOnNode(nodeName string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.cache, nodeName)
glog.V(5).Infof("Cache invali... | {
delete(c.cache[nodeName], predicateKey)
} | conditional_block |
image_mapper.go | err := loadImageStreamTransforms(input, is, allowMissingImages, path)
if err != nil {
return nil, err
}
imageMapper, err := NewImageMapper(references)
if err != nil {
return nil, err
}
versionMapper := NewComponentVersionsMapper(input.Name, versions, tagsByName)
return func(data []byte) ([]byte, error) {
... | }
return nil, nil, nil, fmt.Errorf("no input image tag named %q", tag.Name)
}
references[tag.Name] = ref
}
// load all version values from the input stream, including any defaults, to perform
// version substitution in the returned manifests.
versions := make(ComponentVersions)
tagsByName := make(map[st... | {
references := make(map[string]ImageReference)
for _, tag := range local.Spec.Tags {
if tag.From == nil || tag.From.Kind != "DockerImage" {
continue
}
if len(tag.From.Name) == 0 {
return nil, nil, nil, fmt.Errorf("no from.name for the tag %s", tag.Name)
}
ref := ImageReference{SourceRepository: tag.F... | identifier_body |
image_mapper.go | err := loadImageStreamTransforms(input, is, allowMissingImages, path)
if err != nil {
return nil, err
}
imageMapper, err := NewImageMapper(references)
if err != nil {
return nil, err
}
versionMapper := NewComponentVersionsMapper(input.Name, versions, tagsByName)
return func(data []byte) ([]byte, error) {
... | (images map[string]ImageReference) (ManifestMapper, error) {
repositories := make([]string, 0, len(images))
bySource := make(map[string]string)
for name, ref := range images {
if len(ref.SourceRepository) == 0 {
return nil, fmt.Errorf("an empty source repository is not allowed for name %q", name)
}
if exist... | NewImageMapper | identifier_name |
image_mapper.go | arts := re.FindSubmatch(in)
repository := string(parts[2])
name, ok := bySource[repository]
if !ok {
klog.V(4).Infof("found potential image %q, but no matching definition", repository)
return in
}
ref := images[name]
suffix := parts[3]
klog.V(2).Infof("found repository %q with locator %q i... | {
return nil, fmt.Errorf("the version name %q must be at least 2 characters", parts[0])
} | conditional_block | |
image_mapper.go | build versions from %s: %s (%s)", tag.Name, value, displayNameValue)
items, err := parseComponentVersionsLabel(value, displayNameValue)
if err != nil {
return nil, nil, nil, fmt.Errorf("input image stream has an invalid version annotation for tag %q: %v", tag.Name, value)
}
for k, v := range items {
exis... |
var ( | random_line_split | |
serde_snapshot.rs | genesis_config::ClusterType,
genesis_config::GenesisConfig,
hard_forks::HardForks,
hash::Hash,
inflation::Inflation,
pubkey::Pubkey,
},
std::{
collections::{HashMap, HashSet},
io::{BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
... | frozen_account_pubkeys: &[Pubkey],
account_paths: &[PathBuf],
append_vecs_path: P,
debug_keys: Option<Arc<HashSet<Pubkey>>>,
additional_builtins: Option<&Builtins>,
) -> Result<Bank, Error>
where
E: Into<AccountStorageEntry>,
P: AsRef<Path>,
{
let mut accounts_db = reconstruct_accountsdb... | genesis_config: &GenesisConfig, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.