file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
binder.go | package config
import (
"errors"
"fmt"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/packages"
"github.com/99designs/gqlgen/internal/code"
"github.com/vektah/gqlparser/v2/ast"
)
var ErrTypeNotFound = errors.New("unable to find type")
// Binder connects graphql types to golang types using static an... | types.Type) (types.Type, bool) {
if t == nil {
return t, false
}
named, ok := t.(*types.Named)
if !ok {
return t, false
}
if named.Origin().String() != "github.com/99designs/gqlgen/graphql.Omittable[T any]" {
return t, false
}
return named.TypeArgs().At(0), true
}
func (b *Binder) TypeReference(schemaTy... | wrapOmittable(t | identifier_name |
binder.go | package config
import (
"errors"
"fmt"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/packages"
"github.com/99designs/gqlgen/internal/code"
"github.com/vektah/gqlparser/v2/ast"
)
var ErrTypeNotFound = errors.New("unable to find type")
// Binder connects graphql types to golang types using static an... | continue
}
return &TypeReference{
Definition: def,
GQL: schemaType,
GO: InterfaceType,
}, nil
}
pkgName, typeName = code.PkgAndType(model)
if pkgName == "" {
return nil, fmt.Errorf("missing package name for %s", schemaType.Name())
}
ref := &TypeReference{
Defini... | if model == "interface{}" {
if !isIntf(bindTarget) { | random_line_split |
binder.go | package config
import (
"errors"
"fmt"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/packages"
"github.com/99designs/gqlgen/internal/code"
"github.com/vektah/gqlparser/v2/ast"
)
var ErrTypeNotFound = errors.New("unable to find type")
// Binder connects graphql types to golang types using static an... | named, ok := t.(*types.Named)
if !ok {
return t, false
}
if named.Origin().String() != "github.com/99designs/gqlgen/graphql.Omittable[T any]" {
return t, false
}
return named.TypeArgs().At(0), true
}
func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret *TypeReference, err error) {
... | return t, false
}
| conditional_block |
tools.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Codes are borrowed from https://github.com/facebookresearch/SentEval/blob/master/senteval/tools/classifier.py
and https://github.com/ganeshjawahar/interpret_bert
with small modifications and our own implement of a simple self-attention layer
Pytorch Classifie... |
"""
MLP with Pytorch (nhid=0 --> Logistic Regression)
"""
class MLP(PyTorchClassifier):
def __init__(self, params, inputdim, nclasses, l2reg=0., batch_size=64,
seed=1111, cudaEfficient=False):
super(self.__class__, self).__init__(inputdim, nclasses, l2reg,
... | probas = vals
else:
probas = np.concatenate(probas, vals, axis=0)
return probas
| random_line_split |
tools.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Codes are borrowed from https://github.com/facebookresearch/SentEval/blob/master/senteval/tools/classifier.py
and https://github.com/ganeshjawahar/interpret_bert
with small modifications and our own implement of a simple self-attention layer
Pytorch Classifie... |
def fit(self, args, model, tokenizer, train_x, train_y, dev_x, dev_y, validation_split=None,
early_stop=True):
self.nepoch = 0
bestaccuracy = -1
stop_train = False
early_stop_count = 0
# Preparing validation data
train_dataloader, train_sampler = self.prepare_data(args, ... | all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
all_segment_ids = torch.tensor([f.input_type_ids for f in featu... | identifier_body |
tools.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Codes are borrowed from https://github.com/facebookresearch/SentEval/blob/master/senteval/tools/classifier.py
and https://github.com/ganeshjawahar/interpret_bert
with small modifications and our own implement of a simple self-attention layer
Pytorch Classifie... |
self.nepoch += epoch_size
def score(self, args, model, tokenizer, dev_x):
dev_dataloader, dev_sampler = self.prepare_data(args, dev_x)
self.model.eval()
correct = 0
all = 0
with torch.no_grad():
for step, batch in enumerate(dev_dataloader):
batch = tuple(t.to(args.dev... | for step, batch in enumerate(train_dataloader):
batch = tuple(t.to(args.device) for t in batch)
inputs = {'input_ids': batch[0],
'attention_mask': batch[1],
'token_type_ids': batch[3]}
ybatch = batch[4]
with torch.no_grad():
... | conditional_block |
tools.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Codes are borrowed from https://github.com/facebookresearch/SentEval/blob/master/senteval/tools/classifier.py
and https://github.com/ganeshjawahar/interpret_bert
with small modifications and our own implement of a simple self-attention layer
Pytorch Classifie... | (self, args, features):
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)
all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
all_segment_ids = torch.tensor... | prepare_data | identifier_name |
google_drive_data.py | import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... |
def count_image(id):
imageList = []
service = get_gdrive_service()
results = service.files().list(pageSize=1000, q="'{}' in parents".format(id)).execute()
items = results.get('files', [])
for item in items:
mime_Type = item["mimeType"]
if mime_Type == "image/jpeg":
... | count=1
for item in items:
id = item["id"]
name = item["name"]
mime_type = item["mimeType"]
file = service.files().get(fileId=id).execute()
del file['id']
if "jpeg" in mime_type:
file['name'] = newName+str(count)+ ".jpg";
if "png" in mime_... | identifier_body |
google_drive_data.py | import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... |
for item in items:
id = item["id"]
name = item["name"]
mime_type = item["mimeType"]
if mime_type == "application/vnd.google-apps.folder":
folder_count = folder_count + 1
if mime_type == "image/jpeg":
# renameFile(item["id"],"rajj_img"+str(imag... | name = item["name"]
mime_type = item["mimeType"]
if name == 'Test Techm':
testtechm_id = item['parents'][0] | conditional_block |
google_drive_data.py | import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... |
def duplicate_image_list(imagelist):
#print(len(imagelist))
dup_list = []
if len(imagelist) >= 1:
for i in range(len(imagelist) - 1):
count=0
l=[]
for j in range(i + 1, len(imagelist)):
image1 = cv2.imread(imagelist[i])
i... | random_line_split | |
google_drive_data.py | import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... | (service):
file_metadata = {
'name': 'Test Techm',
'mimeType': 'application/vnd.google-apps.folder'
}
file = service.files().create(body=file_metadata,
fields='id').execute()
print('Folder ID: %s' % file.get('id'))
def get_gdrive_service():
... | create_folder | identifier_name |
mod.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | items: &[(&[u8], &[u8])], // &[(key, value)]
) -> Result<()> {
let checker = StorageProofChecker::<T::Hashing>::new(state_root, proof)?;
for (k, v) in items {
let actual_value = checker
.read_value(k)?
.ok_or_else(|| anyhow::Error::msg(Error::Stora... | proof: StorageProof, | random_line_split |
mod.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
}
type BridgeId = u64;
pub trait Config: frame_system::Config<Hash = H256> {
type Block: BlockT<Hash = H256, Header = Self::Header>;
}
impl Config for chain::Runtime {
type Block = chain::Block;
}
#[derive(Encode, Decode, Clone, Serialize, Deserialize)]
pub struct LightValidation<T: Config> {
num_bridg... | {
BridgeInfo {
last_finalized_block_header: block_header,
current_set: validator_set,
}
} | identifier_body |
mod.rs | // Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... | (
&mut self,
block_header: T::Header,
validator_set: AuthoritySet,
proof: StorageProof,
) -> Result<BridgeId> {
let state_root = block_header.state_root();
Self::check_validator_set_proof(state_root, proof, &validator_set.list, validator_set.id)
.map_err(... | initialize_bridge | identifier_name |
autodetect.js | //autodetect is used to running the autodetection scheme for the configuration
//and uses a statechart to do it.
//
//
//
// autoDetect should scan the current project folder for the following:
// - a file named sc_config.json
// - a folder called apps.
// - If it exists,
// - scan the subfold... | allConfigs.apps.push(data);
}
}
else {
util.log('app found with name ' + app + " but no config file detected.");
allConfigs.apps.push(app);
}
this.appnames = this.appnames.without(app);
if(this.appnames.length === 0){
this.gotoS... | if(!data.name) data.name = app; | random_line_split |
product.ts | import { Component, ViewChild } from '@angular/core'
import { NavController, NavParams, Content, AlertController, Platform } from 'ionic-angular'
import { ProductService } from '../../providers/service/product-service'
import { Values } from '../../providers/service/values'
import { Functions } from '../../providers/se... | getTime1(time){
this.processHour = time
}
}
| this.processDate = date
}
| identifier_body |
product.ts | import { Component, ViewChild } from '@angular/core'
import { NavController, NavParams, Content, AlertController, Platform } from 'ionic-angular'
import { ProductService } from '../../providers/service/product-service'
import { Values } from '../../providers/service/values'
import { Functions } from '../../providers/se... | addressesCustomer: any;
constructor(
public alert:AlertController,
public translate: TranslateService,
public nav: NavController,
public service: ProductService,
public servi:Service,
public otherservice: Service,
params: NavParams,
public functions: Functions,
public values: Va... | customers: any;
addresses: any; | random_line_split |
product.ts | import { Component, ViewChild } from '@angular/core'
import { NavController, NavParams, Content, AlertController, Platform } from 'ionic-angular'
import { ProductService } from '../../providers/service/product-service'
import { Values } from '../../providers/service/values'
import { Functions } from '../../providers/se... | this.daysConfig.push({
date: moment()
.add(index, 'days')
.toDate(),
marked: true,
})
}
//Por defecto iniciamos con el booking deshabilitado
this.disableSubmit = true
}
handleAddress(result){
this.addresses = result
this.addressesCustomer = this.... | this.daysConfig.push({
date: moment()
.add(index, 'days')
.toDate(),
disable: true,
})
}
| conditional_block |
product.ts | import { Component, ViewChild } from '@angular/core'
import { NavController, NavParams, Content, AlertController, Platform } from 'ionic-angular'
import { ProductService } from '../../providers/service/product-service'
import { Values } from '../../providers/service/values'
import { Functions } from '../../providers/se... |
this.chooseVariation(this.optionss);
}
chooseVariation(option) {
console.log(option);
console.log(this.selectedService);
if (this.selectedService) {
this.selectedService = null
this.product.product.price = this.product.product.minPrice
}
this.product.product.resources_full.forE... | oseVariationOne(){ | identifier_name |
codegen.rs | use super::*;
use crate::ops::cast::cast;
use crate::ops::math::add;
use crate::ops::matmul::lir_unary::{
AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec,
};
use crate::ops::matmul::mir_quant::{
combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8,
};
use crate::ops::mat... | (
op: &EinSum,
model: &TypedModel,
node: &TypedNode,
(_, k_axis, _): (&Axis, &Axis, &Axis),
) -> TractResult<Option<TypedModelPatch>> {
let name = &node.name;
let mut patch = TypedModelPatch::new("Dequantizing einsum");
let taps = patch.taps(model, &node.inputs)?;
let [a, b, bias, mut a0... | dequant | identifier_name |
codegen.rs | use super::*;
use crate::ops::cast::cast;
use crate::ops::math::add;
use crate::ops::matmul::lir_unary::{
AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec,
};
use crate::ops::matmul::mir_quant::{
combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8,
};
use crate::ops::mat... | else {
non_trivial_k_axis.get(0).copied().or_else(|| candidate_k_axes.get(0)).copied()
};
let Some(k_axis) = k_axis else {
return Ok(AxesOrPatch::Patch(inject_k_axis(op, model, node)?));
};
let m_axis = op
.axes
.iter_all_axes()
.filter(|a| {
a.inputs... | {
// TODO: handle case where multiple consecutive k in the same order in both input.
bail!("Multiple k-axis candidate found");
} | conditional_block |
codegen.rs | use super::*;
use crate::ops::cast::cast;
use crate::ops::math::add;
use crate::ops::matmul::lir_unary::{
AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec,
};
use crate::ops::matmul::mir_quant::{
combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8,
};
use crate::ops::mat... |
pub(super) fn inject_k_axis(
op: &EinSum,
model: &TypedModel,
node: &TypedNode,
) -> TractResult<TypedModelPatch> {
let mut new_axes = op.axes.clone();
let name = &node.name;
let mut patch = TypedModelPatch::new("inject k axis");
let mut wire = patch.taps(model, &node.inputs)?;
let rep... | {
let input_facts = model.node_input_facts(node.id)?;
let input_shapes: TVec<&[TDim]> = input_facts.iter().map(|f| &*f.shape).collect();
let output_shape = super::eval::output_shape(&op.axes, &input_shapes);
let candidate_k_axes: TVec<&Axis> = op
.axes
.iter_all_axes()
// Filter ... | identifier_body |
codegen.rs | use super::*;
use crate::ops::cast::cast;
use crate::ops::math::add;
use crate::ops::matmul::lir_unary::{
AddMatMulGeometry, LirMatMulUnary, MapOutputAxisToInput, ProtoFusedSpec,
};
use crate::ops::matmul::mir_quant::{
combine_scales, compensate_zero_points, requant, wire_offset_u8_as_i8,
};
use crate::ops::mat... | )?[0];
}
}
let a = wire_offset_u8_as_i8(&mut patch, &node.name, a, "a", &mut a0, "a0")?;
let b = wire_offset_u8_as_i8(&mut patch, &node.name, b, "b", &mut b0, "b0")?;
let mut output = patch.wire_node(
&node.name,
EinSum {
q_params: None,
axes... | for i in 1..(output_rank - q_axis_in_output) {
a_scale = patch.wire_node(
format!("{name}.a_scale_axis_fix_{i}"),
AxisOp::Add(i),
&[a_scale], | random_line_split |
interface.py | # Interfaces to the Ceilometer API
# import ceilometer
# Brings in HTTP support
import requests
import json
import urllib
from copy import copy
from collections import defaultdict
#
import datetime
# Provides authentication against Openstack
from keystoneclient.v2_0 import client as KeystoneClient
# Provides hook... |
return self._tenancy
class Tenant(object):
def __init__(self, tenant, conn):
self.tenant = tenant
# Conn is the niceometer object we were instanced from
self.conn = conn
self._meters = set()
self._resources = None
self.invoice_type = None
# Invoice... | self._tenancy = {}
for tenant in self.auth.tenants.list():
t = Tenant(tenant, self)
self._tenancy[t["name"]] = t | conditional_block |
interface.py | # Interfaces to the Ceilometer API
# import ceilometer
# Brings in HTTP support
import requests
import json
import urllib
from copy import copy
from collections import defaultdict
#
import datetime
# Provides authentication against Openstack
from keystoneclient.v2_0 import client as KeystoneClient
# Provides hook... | (Artifact):
def volume(self):
measurements = self.usage
measurements = sorted( measurements, key= lambda x: x["timestamp"] )
total_usage = measurements[-1]["counter_volume"] - measurements[0]["counter_volume"]
return total_usage
# Gauge and Delta have very little to do: They are e... | Cumulative | identifier_name |
interface.py | # Interfaces to the Ceilometer API
# import ceilometer
# Brings in HTTP support
import requests
import json
import urllib
from copy import copy
from collections import defaultdict
#
import datetime
# Provides authentication against Openstack
from keystoneclient.v2_0 import client as KeystoneClient
# Provides hook... |
class Usage(object):
"""
This is a dict-like object containing all the datacenters and
meters available in those datacenters.
"""
def __init__(self, contents, start, end, conn):
self.contents = contents
self.start = start
self.end = end
self.conn = conn
s... | def __init__(self, tenant, conn):
self.tenant = tenant
# Conn is the niceometer object we were instanced from
self.conn = conn
self._meters = set()
self._resources = None
self.invoice_type = None
# Invoice type needs to get set from the config, which is
#... | identifier_body |
interface.py | # Interfaces to the Ceilometer API
# import ceilometer
# Brings in HTTP support
import requests
import json
import urllib
from copy import copy
from collections import defaultdict
#
import datetime
# Provides authentication against Openstack
from keystoneclient.v2_0 import client as KeystoneClient
# Provides hook... | data = json.loads(r.text)
assert data
return data
else:
if r.status_code == 404:
# couldn't find it
raise NotFound
class Artifice(object):
"""Produces billable artifacts"""
def __init__(self, config):
super(Artifice... | })
if r.ok: | random_line_split |
fint.py | import re, os, csv, sys, time
import json, random, argparse
from collections import Counter
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
VERSION = "0... |
def get_all_photos(driver, target_id, limit=100):
url = 'https://mbasic.facebook.com/profile.php?id=%s&v=photos' % target_id
driver.get(url)
time.sleep(pause())
see_all = re.findall('<a href="([^"#]+)">See All</a>', driver.page_source)
photos = []
if not see_all:
return photos
e... | links = re.findall('(/photo\.php\?[^;]*;id=%s[^"]+)' % target_id, html)
return ['%s%s' % (BASE_URL, x.replace('&', '&')) for x in set(links)] | identifier_body |
fint.py | import re, os, csv, sys, time
import json, random, argparse
from collections import Counter
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
VERSION = "0... |
else:
break
return stories
def get_all_comments(driver, url, limit=200, cur_length=0):
if cur_length >= limit:
return []
driver.get(url)
html = driver.page_source.encode("utf-8",
errors='replace').decode("utf-8",
... | url = BASE_URL + see_more[0].replace('&', '&')
time.sleep(pause())
driver.get(url) | conditional_block |
fint.py | import re, os, csv, sys, time
import json, random, argparse
from collections import Counter
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
VERSION = "0... | (html):
return re.findall(
'<h3><a class="[^"]+" href="([^"]+)\?r[^"]*">([^<]*)</a>', html)
# Given a "reactions" page ufi/reaction/profile/browser/, returns a list of (url, display name)
def parse_likers(html):
return re.findall(
'<h3 class=".[^"]*"><a href="(.[^"]*)[^"]*">(.[^<]*)</a></h3>',... | parse_commenters | identifier_name |
fint.py | import re, os, csv, sys, time
import json, random, argparse
from collections import Counter
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
VERSION = "0... |
reactions = reactions[:args.limit_reactions]
commenters = commenters[:args.limit_comments]
users = list(set(reactions).union(set(commenters)))
print_statistics(commenters, reactions)
users = fill_user_ids(driver, users)
if args.output:
store_pivots(users, args.output)
else:
... | print(msg, end='\r')
except (KeyboardInterrupt, SystemExit):
print('[!] KeyboardInterrupt received. %d users retrieved' %
len(users)) | random_line_split |
headtail_resolution.py | """
This module contains the logic to resolve the head-tail orientation of a predicted video time series.
"""
import logging
import numpy as np
import numpy.ma as ma
from wormpose.pose.distance_metrics import angle_distance, skeleton_distance
from wormpose.pose.results_datatypes import (
BaseResults,
Shuffle... |
return segments_alignment
def _calculate_smallest_gap_to_adjacent(segment_index, segments, segments_alignment):
# evaluate how far away this segment is from known values
score = np.nan
segment_offset = np.nan
if segment_index - 1 >= 0 and not segments_alignment.mask[segment_index - 1]:
g... | segment_skeletons = labelled_skeletons[segment]
non_nan_labelled = np.any(~np.isnan(segment_skeletons), axis=(1, 2))
labels_count = np.sum(non_nan_labelled)
non_masked = ~np.any(partitioned_skeletons[segment].mask, axis=(1, 2, 3))
to_compare = np.logical_and(non_nan_labelled, non_masked)... | conditional_block |
headtail_resolution.py | """
This module contains the logic to resolve the head-tail orientation of a predicted video time series.
"""
import logging
import numpy as np
import numpy.ma as ma
from wormpose.pose.distance_metrics import angle_distance, skeleton_distance
from wormpose.pose.results_datatypes import (
BaseResults,
Shuffle... | (partitioned_series, shuffled_series, frame_index: int, partition: int):
partitioned_series[frame_index][0] = shuffled_series[frame_index, partition]
partitioned_series[frame_index][1] = shuffled_series[frame_index, 1 - partition]
class _PartitionedResults(BaseResults):
def __init__(self, shuffled_results... | _set_partition | identifier_name |
headtail_resolution.py | """
This module contains the logic to resolve the head-tail orientation of a predicted video time series.
"""
import logging
import numpy as np
import numpy.ma as ma
from wormpose.pose.distance_metrics import angle_distance, skeleton_distance
from wormpose.pose.results_datatypes import (
BaseResults,
Shuffle... |
def mask(self, indices):
self.theta.mask[indices] = True
self.skeletons.mask[indices] = True
self.scores.mask[indices] = True
def num_valid(self):
return np.sum(~self.scores.mask)
class _FinalResults(BaseResults):
@classmethod
def from_resolved(cls, resolved_results:... | self.scores[segment] = self._partitioned_results.scores[segment][:, segment_alignment]
self.skeletons[segment] = self._partitioned_results.skeletons[segment][:, segment_alignment]
self.theta[segment] = self._partitioned_results.theta[segment][:, segment_alignment] | identifier_body |
headtail_resolution.py | """
This module contains the logic to resolve the head-tail orientation of a predicted video time series.
"""
import logging
import numpy as np
import numpy.ma as ma
from wormpose.pose.distance_metrics import angle_distance, skeleton_distance
from wormpose.pose.results_datatypes import (
BaseResults,
Shuffle... | self.theta.mask[indices] = True
self.skeletons.mask[indices] = True
self.scores.mask[indices] = True
self.partitions.mask[indices] = True
def set_partition(self, frame_index: int, partition: int, new_partition: bool = False):
if new_partition:
self.cur_partition ... | random_line_split | |
game.rs | use std::convert::TryFrom;
use hdk::{
utils,
entry_definition::ValidatingEntryType,
error::{ZomeApiResult, ZomeApiError},
holochain_persistence_api::{
cas::content::{AddressableContent, Address},
},
holochain_json_api::{
error::JsonError, json::JsonString,
},
holochain_co... | let new_state = moves.iter().fold(GameState::initial(), move |state, new_move| state.evolve(game.clone(), new_move));
Ok(new_state)
/* get_state_local_chain is similar to get_state function. It takes local_chain and game_address as parameters and return the GameState.
* we first get all the moves assoc... | let game = get_game_local_chain(local_chain, game_address)?; | random_line_split |
game.rs | use std::convert::TryFrom;
use hdk::{
utils,
entry_definition::ValidatingEntryType,
error::{ZomeApiResult, ZomeApiError},
holochain_persistence_api::{
cas::content::{AddressableContent, Address},
},
holochain_json_api::{
error::JsonError, json::JsonString,
},
holochain_co... | (game_address: &Address) -> ZomeApiResult<Vec<Move>> {
match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() {
/* get links returns the ZomeApiResult<GetLinksResult>.
* This will get entries that are linked to the first argument.
* Since ZomeApi... | get_moves | identifier_name |
game.rs | use std::convert::TryFrom;
use hdk::{
utils,
entry_definition::ValidatingEntryType,
error::{ZomeApiResult, ZomeApiError},
holochain_persistence_api::{
cas::content::{AddressableContent, Address},
},
holochain_json_api::{
error::JsonError, json::JsonString,
},
holochain_co... | else {
None
}
})
.next()
.ok_or(ZomeApiError::HashNotFound)
/* get_game_local_chain() gets all the Entry in the local_chain as well as the address of the game and will return ZomeApiResult<Game>.
* now we will call the iter() method on the local_chain so tha... | {
Some(Game::try_from(entry_data.clone()).unwrap())
} | conditional_block |
game.rs | use std::convert::TryFrom;
use hdk::{
utils,
entry_definition::ValidatingEntryType,
error::{ZomeApiResult, ZomeApiError},
holochain_persistence_api::{
cas::content::{AddressableContent, Address},
},
holochain_json_api::{
error::JsonError, json::JsonString,
},
holochain_co... |
pub fn get_state(game_address: &Address) -> ZomeApiResult<GameState> {
let moves = get_moves(game_address)?;
let game = get_game(game_address)?;
let new_state = moves.iter().fold(GameState::initial(), |state, new_move| state.evolve(game.clone(), new_move));
Ok(new_state)
/* get_state takes the add... | {
match hdk::get_links(game_address, LinkMatch::Any, LinkMatch::Any)?.addresses().into_iter().next() {
/* get links returns the ZomeApiResult<GetLinksResult>.
* This will get entries that are linked to the first argument.
* Since ZomeApiResult returns Result<T, ZomeApiError>(where T in thi... | identifier_body |
server_rpc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/server/server_rpc.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... |
# Tables with a message_id field
for table_name in db_models.get_tables_with_column_id('message_id'):
self.rpc_handler_map['^/message/' + table_name + '/count$'] = self.rpc_database_count_rows
self.rpc_handler_map['^/message/' + table_name + '/view$'] = self.rpc_database_get_rows
def rpc_ping(self):
"""... | self.rpc_handler_map['^/campaign/' + table_name + '/count$'] = self.rpc_database_count_rows
self.rpc_handler_map['^/campaign/' + table_name + '/view$'] = self.rpc_database_get_rows | conditional_block |
server_rpc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/server/server_rpc.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... | class KingPhisherRequestHandlerRPC(object):
"""
This superclass of :py:class:`.KingPhisherRequestHandler` maintains
all of the RPC call back functions.
:RPC API: :ref:`rpc-api-label`
"""
def install_handlers(self):
super(KingPhisherRequestHandlerRPC, self).install_handlers()
self.rpc_handler_map['^/ping$'] =... | DATABASE_TABLES = db_models.DATABASE_TABLES
DATABASE_TABLE_OBJECTS = db_models.DATABASE_TABLE_OBJECTS
| random_line_split |
server_rpc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/server/server_rpc.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... |
def rpc_campaign_message_new(self, campaign_id, email_id, target_email, company_name, first_name, last_name):
"""
Record a message that has been sent as part of a campaign. These
details can be retrieved later for value substitution in template
pages.
:param int campaign_id: The ID of the campaign.
:par... | """
Add a landing page for the specified campaign. Landing pages refer
to resources that when visited by a user should cause the visit
counter to be incremented.
:param int campaign_id: The ID of the campaign.
:param str hostname: The VHOST for the request.
:param str page: The request resource.
"""
pa... | identifier_body |
server_rpc.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/server/server_rpc.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... | (self, keys, values):
"""
Insert a new row into the specified table.
:param tuple keys: The column names of *values*.
:param tuple values: The values to be inserted in the row.
"""
if not isinstance(keys, (list, tuple)):
keys = (keys,)
if not isinstance(values, (list, tuple)):
values = (values,)
... | rpc_database_insert_row | identifier_name |
server.rs | use crate::adapter::Adapter;
use crate::socket::{
subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent,
};
use crate::transport::{Transport, TransportCreateData, TransportKind};
use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie};
use dashmap::Das... |
pub fn try_subscribe(
&self,
) -> Result<bmrng::RequestReceiver<ServerEvent, Packet>, AlreadySubscribedError> {
let mut state = self.state.lock().unwrap();
let old_state = std::mem::replace(&mut *state, ServerState::Subscribed);
match old_state {
ServerState::Subscr... | {
self.try_subscribe()
.expect("Already subscribed to engine_io_server::Server")
} | identifier_body |
server.rs | use crate::adapter::Adapter;
use crate::socket::{
subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent,
};
use crate::transport::{Transport, TransportCreateData, TransportKind};
use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie};
use dashmap::Das... | // TODO: or drop the whole thing. The server, the sockets, everything.
todo!();
// for socket in self.clients.iter() {
// socket.value().close(true);
// }
}
pub async fn close_socket(&self, connection_id: &str) {
if let Some((_key, socket)) = self.clients.rem... | // TODO: consider sending signals or dropping channels instead of closing them like this? | random_line_split |
server.rs | use crate::adapter::Adapter;
use crate::socket::{
subscribe_socket_to_transport_events, Callback, Socket, SocketCloseReason, SocketEvent,
};
use crate::transport::{Transport, TransportCreateData, TransportKind};
use crate::util::{HttpMethod, RequestContext, SendPacketError, ServerError, SetCookie};
use dashmap::Das... | (
&self,
sid: Option<&String>,
upgrade: bool,
transport_kind: TransportKind,
http_method: HttpMethod,
) -> Result<(), ServerError> {
if let Some(sid) = sid {
let client = self.clients.get(sid);
if let Some(client) = client {
let... | verify_request | identifier_name |
dkg.go | package dkg
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math/big"
"github.com/MadBase/MadNet/crypto/bn256"
"github.com/MadBase/MadNet/crypto/bn256/cloudflare"
"github.com/MadBase/MadNet/logging"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
)
// Evil
var logger *logrus.Lo... |
// GenerateKeyShare returns G1 key share, G1 proof, G2 key share and potentially an error
func GenerateKeyShare(firstPrivateCoefficients *big.Int) ([2]*big.Int, [2]*big.Int, [4]*big.Int, error) {
h1Base, err := cloudflare.HashToG1(h1BaseMessage)
if err != nil {
return empty2Big, empty2Big, empty4Big, err
}
ord... | {
// create coefficients (private/public)
privateCoefficients, err := cloudflare.ConstructPrivatePolyCoefs(rand.Reader, threshold)
if err != nil {
return nil, nil, nil, err
}
publicCoefficients := cloudflare.GeneratePublicCoefs(privateCoefficients)
// create commitments
commitments := make([][2]*big.Int, len... | identifier_body |
dkg.go | package dkg
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math/big"
"github.com/MadBase/MadNet/crypto/bn256"
"github.com/MadBase/MadNet/crypto/bn256/cloudflare"
"github.com/MadBase/MadNet/logging"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
)
// Evil
var logger *logrus.Lo... |
transportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey)
if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting transport public key to g1: %v", err)
}
sharedEncrypted, err := cloudflare.CondenseCommitments(transportPublicKeyG1, encryptedShares, publicKeyG1s)
if err != ni... | {
publicKeyG1, err := bn256.BigIntArrayToG1(participants[idx].PublicKey)
if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting public key to g1: %v", err)
}
publicKeyG1s[idx] = publicKeyG1
} | conditional_block |
dkg.go | package dkg
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math/big"
"github.com/MadBase/MadNet/crypto/bn256"
"github.com/MadBase/MadNet/crypto/bn256/cloudflare"
"github.com/MadBase/MadNet/logging"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
)
// Evil
var logger *logrus.Lo... | if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error converting transport public key to g1: %v", err)
}
sharedEncrypted, err := cloudflare.CondenseCommitments(transportPublicKeyG1, encryptedShares, publicKeyG1s)
if err != nil {
return nil, empty4Big, empty2Big, fmt.Errorf("error condensing commi... | transportPublicKeyG1, err := bn256.BigIntArrayToG1(transportPublicKey) | random_line_split |
dkg.go | package dkg
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math/big"
"github.com/MadBase/MadNet/crypto/bn256"
"github.com/MadBase/MadNet/crypto/bn256/cloudflare"
"github.com/MadBase/MadNet/logging"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
)
// Evil
var logger *logrus.Lo... | (i, j int) {
pl[i], pl[j] = pl[j], pl[i]
}
// ThresholdForUserCount returns the threshold user count and k for successful key generation
func ThresholdForUserCount(n int) (int, int) {
k := n / 3
threshold := 2 * k
if (n - 3*k) == 2 {
threshold = threshold + 1
}
return int(threshold), int(k)
}
// InverseArrayF... | Swap | identifier_name |
id.rs |
pub fn bug(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match BUGS.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("bug '{}' has no id yet", name),
}
}
pub fn fish(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_l... |
pub fn art(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match ART.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("art '{}' has no id yet", name),
}
}
pub fn villager(name: impl AsRef<str>) -> usize {
let name = name.as_ref().... | {
let name = name.as_ref().to_lowercase();
match FLOWERS.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("flower '{}' has no id yet", name),
}
} | identifier_body |
id.rs |
pub fn bug(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match BUGS.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("bug '{}' has no id yet", name),
}
}
pub fn fish(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_l... | (name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match ART.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("art '{}' has no id yet", name),
}
}
pub fn villager(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase... | art | identifier_name |
id.rs | pub fn bug(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lowercase();
match BUGS.iter().position(|&other| other == name) {
Some(index) => index,
_ => panic!("bug '{}' has no id yet", name),
}
}
pub fn fish(name: impl AsRef<str>) -> usize {
let name = name.as_ref().to_lo... | "black cosmos",
"white tulips",
"red tulips",
"yellow tulips",
"pink tulips",
"orange tulips",
"purple tulips",
"black tulips",
"yellow pansies",
"red pansies",
"white pansies",
"orange pansies",
"purple pansies",
"blue pansies",
"white roses",
"red roses"... | "white cosmos",
"yellow cosmos",
"pink cosmos",
"orange cosmos", | random_line_split |
main.rs | use std::f64::consts::PI;
use clap::*;
use gre::*;
use noise::*;
use rand::Rng;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_value = "100.0")]
pub width: ... | a += rng.gen_range(-0.5, 0.5) * rng.gen_range(0.0, 1.0);
}
}
rng.shuffle(&mut positions);
let disp = rng.gen_range(0.5, 3.0);
let mut eagles = Vec::new();
for p in positions {
if rng.gen_bool(0.2) {
continue;
}
let scale = rng.gen_range(0.3, 0.5);
let p = (
p.0 + disp ... | if p.0 < pad || p.0 > width - pad || p.1 < pad || p.1 > height - pad {
break;
}
p = (p.0 + amp * a.cos(), p.1 + amp * a.sin());
positions.push(p); | random_line_split |
main.rs | use std::f64::consts::PI;
use clap::*;
use gre::*;
use noise::*;
use rand::Rng;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_value = "100.0")]
pub width: ... |
fn eagle<R: Rng>(
origin: (f64, f64),
scale: f64,
rotation: f64,
xreverse: bool,
rng: &mut R,
) -> Vec<Vec<(f64, f64)>> {
let xmul = if xreverse { -1.0 } else { 1.0 };
let count = 2 + (scale * 3.0) as usize;
let mut routes: Vec<Vec<(f64, f64)>> = Vec::new();
let shaking = scale * 0.1;
// body
... | {
path
.iter()
.map(|&(x, y)| {
let dx = rng.gen_range(-scale, scale);
let dy = rng.gen_range(-scale, scale);
(x + dx, y + dy)
})
.collect()
} | identifier_body |
main.rs | use std::f64::consts::PI;
use clap::*;
use gre::*;
use noise::*;
use rand::Rng;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct | {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_value = "100.0")]
pub width: f64,
#[clap(short, long, default_value = "150.0")]
pub height: f64,
#[clap(short, long, default_value = "5.0")]
pub pad: f64,
#[clap(short, long, default_value = "0.0")]
pub se... | Opts | identifier_name |
main.rs | use std::f64::consts::PI;
use clap::*;
use gre::*;
use noise::*;
use rand::Rng;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_value = "100.0")]
pub width: ... | else {
rng.gen_range(-3.0, 3.0)
};
let spread1 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0);
let spread2 = 1.0 + rng.gen_range(0.0, 1.0) * rng.gen_range(0.0, 1.0);
let offset1 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1.0);
let offset2 = rng.gen_range(-1.0, 0.6) * rng.gen_range(0.0, 1.... | {
-dx1
} | conditional_block |
leetcode.rs | //! The common data structure definition for leetcode problems.
/**
The definition of `ListNode`, used by many problems.
*/
#[derive(PartialEq, Eq, Debug)]
pub(crate) struct ListNode {
val: i32,
next: Option<Box<Self>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
Self { next: None, val }
}
}
... | {
val: i32,
left: Option<Rc<RefCell<Self>>>,
right: Option<Rc<RefCell<Self>>>,
}
impl TreeNode {
#[inline]
fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
#[inline]
fn new_option(val: Option<i32>) -> Option<Rc<RefCell<Self>>> {
val.map(|v| Rc::new... | TreeNode | identifier_name |
leetcode.rs | //! The common data structure definition for leetcode problems.
/**
The definition of `ListNode`, used by many problems.
*/
#[derive(PartialEq, Eq, Debug)]
pub(crate) struct ListNode {
val: i32,
next: Option<Box<Self>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
Self { next: None, val }
}
}
... |
}
}
count == 1
}
/// Check element content equivalence without element order.
fn check_element_eq<T>(v1: T, v2: T) -> bool
where
T: IntoIterator,
T::Item: Eq + std::hash::Hash + std::fmt::Debug,
{
use std::collections::HashMap;
let (mut length1, mut length2) = (0, 0);
let (mut content1, mut conten... | {
return false;
} | conditional_block |
leetcode.rs | //! The common data structure definition for leetcode problems.
/**
The definition of `ListNode`, used by many problems.
*/
#[derive(PartialEq, Eq, Debug)]
pub(crate) struct ListNode {
val: i32,
next: Option<Box<Self>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
Self { next: None, val }
}
}
... | mod q87_scramble_string;
mod q89_gray_code;
mod q8_my_atoi;
mod q90_subsets_ii;
mod q91_decode_ways;
mod q92_reverse_linked_list_ii;
mod q93_restore_ip_addresses;
mod q94_binary_tree_inorder_traversal;
mod q95_unique_binary_search_trees_ii;
mod q96_unique_binary_search_trees;
mod q97_interleaving_string;
mod q98_valida... | mod q84_largest_rectangle_in_histogram;
mod q85_maximal_rectangle;
mod q86_partition_list; | random_line_split |
lib.rs | #![no_std]
//!
//! You can populate [`Petnames`] with your own word lists, but the word lists
//! from upstream [petname](https://github.com/dustinkirkland/petname) are
//! included with the `default_dictionary` feature (enabled by default). See
//! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ... | <RNG>(&'a self, rng: &'a mut RNG, words: u8, separator: &str) -> Names<'a, RNG>
where
RNG: rand::Rng,
{
Names { petnames: self, rng, words, separator: separator.to_string() }
}
/// Iterator yielding unique – i.e. non-repeating – petnames.
///
/// # Examples
///
/// ```ru... | iter | identifier_name |
lib.rs | #![no_std]
//!
//! You can populate [`Petnames`] with your own word lists, but the word lists
//! from upstream [petname](https://github.com/dustinkirkland/petname) are
//! included with the `default_dictionary` feature (enabled by default). See
//! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ... | {
self.adjectives.to_mut().retain(|word| predicate(word));
self.adverbs.to_mut().retain(|word| predicate(word));
self.names.to_mut().retain(|word| predicate(word));
}
/// Calculate the cardinality of this `Petnames`.
///
/// If this is low, names may be repeated by the gener... | /// the adjectives, adverbs, and names lists.
///
pub fn retain<F>(&mut self, mut predicate: F)
where
F: FnMut(&str) -> bool, | random_line_split |
lib.rs | #![no_std]
//!
//! You can populate [`Petnames`] with your own word lists, but the word lists
//! from upstream [petname](https://github.com/dustinkirkland/petname) are
//! included with the `default_dictionary` feature (enabled by default). See
//! [`Petnames::small`], [`Petnames::medium`], and [`Petnames::large`] to ... | size_hint(&self) -> (usize, Option<usize>) {
let remains = match self {
Self::Adverb(n) => (n + 3) as usize,
Self::Adjective => 2,
Self::Name => 1,
Self::Done => 0,
};
(remains, Some(remains))
}
}
/// Iterator yielding petnames.
pub struct N... | let list = match self {
Self::Adjective => Some(List::Adjective),
Self::Adverb(_) => Some(List::Adverb),
Self::Name => Some(List::Name),
Self::Done => None,
};
self.advance();
list
}
fn | identifier_body |
califa2_2.py | # -*- coding: utf-8 -*-
'''
Programa para trabalhar os dados do CALIFA
Uma nova abordagem, sem separacao de populacoes estelares
Retomando minha pesquisa... Que o Universo me ajude!
Versão 2.0
07-dezembro-2016
------------------
Versão 2.1
22-fevereiro-2017
Adição dos perfis radiais circulares
------------------
Versã... | lcula a Concentracao de uma populacao, usando a definicao
de Conselice(2014) http://iopscience.iop.org/article/10.1086/375001/pdf
'''
a=1
radius=df.sort_values('raio')
r20=radius.iat[int(0.2*len(df)),-1]
r80=radius.iat[int(0.8*len(df)),-1]
Conc = 5*np.log((r80/r20))
return Conc
def Z(df... | as imagens fits'''
img = f_sdss[0].data
return img
def C(df):
'''funcao que ca | identifier_body |
califa2_2.py | # -*- coding: utf-8 -*-
'''
Programa para trabalhar os dados do CALIFA
Uma nova abordagem, sem separacao de populacoes estelares
Retomando minha pesquisa... Que o Universo me ajude!
Versão 2.0
07-dezembro-2016
------------------
Versão 2.1
22-fevereiro-2017
Adição dos perfis radiais circulares
------------------
Versã... |
hu = mom.hu_moments(df)
hu1.append(hu[0])
hu2.append(hu[1])
hu3.append(hu[2])
hu4.append(hu[3])
hu5.append(hu[4])
hu6.append(hu[5])
hu7.append(hu[6])
hugal.append(gal)
hutype.append(tipo)
#graficos apenas de Halpha
plt.figure(1) #Imagem em Ha
plt.clf()
cx = cube... | print('excentricidade = %f' %exc)
print('inclinacao = %f' %(math.degrees(tetha)))
print('#%d' %i_gal) | random_line_split |
califa2_2.py | # -*- coding: utf-8 -*-
'''
Programa para trabalhar os dados do CALIFA
Uma nova abordagem, sem separacao de populacoes estelares
Retomando minha pesquisa... Que o Universo me ajude!
Versão 2.0
07-dezembro-2016
------------------
Versão 2.1
22-fevereiro-2017
Adição dos perfis radiais circulares
------------------
Versã... | eitura do arquivo fits, criando um dataframe com os dados'''
df = pd.DataFrame()
nrows, ncols = img.shape
xx, yy = np.meshgrid( *np.ogrid[:ncols, :nrows] )
table = np.column_stack(( xx.flatten(), yy.flatten(), img.flatten() ))
temp = pd.DataFrame(table, columns=['x','y',param])
df = pd.concat([d... | função para l | identifier_name |
califa2_2.py | # -*- coding: utf-8 -*-
'''
Programa para trabalhar os dados do CALIFA
Uma nova abordagem, sem separacao de populacoes estelares
Retomando minha pesquisa... Que o Universo me ajude!
Versão 2.0
07-dezembro-2016
------------------
Versão 2.1
22-fevereiro-2017
Adição dos perfis radiais circulares
------------------
Versã... | ] = hutype
df_hu['hu1'] = hu1
df_hu['hu2'] = hu2
df_hu['hu3'] = hu3
df_hu['hu4'] = hu4
df_hu['hu5'] = hu5
df_hu['hu6'] = hu6
df_hu['hu7'] = hu7
#df_hu['hu1','hu2','hu3','hu4','hu5','hu6','hu7'] = hu1
df_hu.to_csv('hu_moments_gal.csv', index=False)
fim = time.time()
time_proc = fim - ini
print('')
#print(bcolors.FAIL ... | DC)
print(bcolors.FAIL + '-'*33 + 'OBJETO: %s' %halpha['num_gal'][i_gal] + '-'*33 + bcolors.ENDC)
print(bcolors.FAIL +'-'*79+ bcolors.ENDC)
plt.close()
image_ha = fits.open('Hamaps/%s_%s_Ha.fits' %(halpha['num_gal'][i_gal],halpha['type'][i_gal]))
img = get_image(image_ha)
#plotando a imagem fit... | conditional_block |
modbase.py | #!/usr/bin/env python
# :noTabs=true:
"""
remotely download from ModBase
internal method "download_models_from_modbase" is the real winner
other methods are for reloading afterwards (if necessary)
so...some quirks, there seem to be multiple "user levels" including a
distinction between "public" and "academic"...this... |
# debug output
if len( matches ) > 1:
temp = 'multiple models are \"equally the best\":'
print temp
text += temp +'\n'
for i in matches:
temp = '\t'+ i['coordinates']
print temp
text += temp +'\n'
temp = 'copying the first on to be... | best_score = max( [i['target length'] for i in details] )
matches = [i for i in details if i['target length'] == best_score] | conditional_block |
modbase.py | #!/usr/bin/env python
# :noTabs=true:
"""
remotely download from ModBase
internal method "download_models_from_modbase" is the real winner
other methods are for reloading afterwards (if necessary)
so...some quirks, there seem to be multiple "user levels" including a
distinction between "public" and "academic"...this... | ( dir_name , tagline = ' to sort the data' ):
"""
Creates the directory <dir_name>
WARNING: this will delete the directory and its contents if it already
exists!
Optionally output something special in <tagline>
"""
# check if it exists
print 'Creating a new directory ' + os.p... | create_directory | identifier_name |
modbase.py | #!/usr/bin/env python
# :noTabs=true:
"""
remotely download from ModBase
internal method "download_models_from_modbase" is the real winner
other methods are for reloading afterwards (if necessary)
so...some quirks, there seem to be multiple "user levels" including a
distinction between "public" and "academic"...this... | # as float
details['evalue'] = float( i.replace( 'EVALUE:' , '' ).strip() )
elif i[:13] == 'TEMPLATE PDB:':
details['template'] = str( i.replace( 'TEMPLATE PDB:' , '' ).strip().upper() )
elif i[:15] == 'TEMPLATE CHAIN:':
details['t... | details['model score'] = float( i.replace( 'MODEL SCORE:' , '' ).strip() )
elif i[:7] == 'EVALUE:': | random_line_split |
modbase.py | #!/usr/bin/env python
# :noTabs=true:
"""
remotely download from ModBase
internal method "download_models_from_modbase" is the real winner
other methods are for reloading afterwards (if necessary)
so...some quirks, there seem to be multiple "user levels" including a
distinction between "public" and "academic"...this... |
# simple wrapper
def get_modbase_model_details( models , add_model_numbers = True , display = True , export = False ):
"""
Returns the details of the model text <models>
Optionally <display> the details
Optionally <export> the details AND a summary str
...this is quite messy, but if... | """
Displays a summary of the ModBase model <details>
Optionally <include_run_details>
Optionally <export> the summary text
"""
# check the input
if isinstance( details , str ):
# assume it just needs to be parsed out
details = extract_model_details_from_modbase_header( ... | identifier_body |
dir.go | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | } | err = fmt.Errorf("DeleteObject: %v", err)
return
}
return | random_line_split |
dir.go | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
d.cache.NoteFile(d.cacheClock.Now(), name)
return
}
// LOCKS_REQUIRED(d)
func (d *dirInode) CloneToChildFile(
ctx context.Context,
name string,
src *gcs.Object) (fn Name, o *gcs.Object, err error) {
// Erase any existing type information for this name.
d.cache.Erase(name)
fn = NewFileName(d.Name(), name)
... | {
return
} | conditional_block |
dir.go | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
// LOCKS_REQUIRED(d)
func (d *dirInode) CreateChildDir(
ctx context.Context,
name string) (fn Name, o *gcs.Object, err error) {
fn = NewDirName(d.Name(), name)
o, err = d.createNewObject(ctx, fn, nil)
if err != nil {
return
}
d.cache.NoteDir(d.cacheClock.Now(), name)
return
}
// LOCKS_REQUIRED(d)
func (... | {
fn = NewFileName(d.Name(), name)
metadata := map[string]string{
SymlinkMetadataKey: target,
}
o, err = d.createNewObject(ctx, fn, metadata)
if err != nil {
return
}
d.cache.NoteFile(d.cacheClock.Now(), name)
return
} | identifier_body |
dir.go | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | (
ctx context.Context,
bucket gcs.Bucket,
name Name) (o *gcs.Object, err error) {
// Call the bucket.
req := &gcs.StatObjectRequest{
Name: name.GcsObjectName(),
}
o, err = bucket.StatObject(ctx, req)
// Suppress "not found" errors.
if _, ok := err.(*gcs.NotFoundError); ok {
err = nil
}
// Annotate oth... | statObjectMayNotExist | identifier_name |
forwarder_test.go | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
func (s *ForwarderTestSuite) TestForwardJSON() {
var ping Ping
var pong Pong
dest, err := s.sender.Lookup("reachable")
s.NoError(err)
headerBytes := []byte(`{"hdr1": "val1"}`)
res, err := s.forwarder.ForwardRequest(ping.Bytes(), dest, "test", "/ping", []string{"reachable"},
tchannel.JSON, &Options{Headers: ... | {
s.channel.Close()
s.peer.Close()
} | identifier_body |
forwarder_test.go | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | (ctx context.Context, b []byte, s athrift.TStruct) error {
reader := bytes.NewReader(b)
transport := athrift.NewStreamTransportR(reader)
return s.Read(ctx, athrift.NewTBinaryProtocolTransport(transport))
}
| DeserializeThrift | identifier_name |
forwarder_test.go | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | Key: "error",
},
}
bytes, err := SerializeThrift(context.Background(), request)
s.NoError(err, "expected ping to be serialized")
res, err := s.forwarder.ForwardRequest(bytes, dest, "test", "PingPong::Ping", []string{"reachable"},
tchannel.Thrift, nil)
s.NoError(err, "expected request to be forwarded")
v... |
request := &pingpong.PingPongPingArgs{
Request: &pingpong.Ping{ | random_line_split |
forwarder_test.go | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
ctx = SetForwardedHeader(ctx, nil)
if !DeleteForwardedHeader(ctx) {
t.Errorf("ringpop was not able to identify that the forwarded header was set")
}
ctx, _ = thrift.NewContext(0 * time.Second)
ctx = thrift.WithHeaders(ctx, map[string]string{
"keep": "this key",
})
if DeleteForwardedHeader(ctx) {
t.Errorf... | {
t.Errorf("ringpop claimed that the forwarded header was set before it was set")
} | conditional_block |
myrule2.js | var firstContent;
var firstLink;
var nowOffset;
var articleLinkArr = [];
var flag = true;
var http = require('http');
//var MongoClient = require('mongodb').MongoClient;
//var DB_CONN_STR = 'mongodb://localhost:27017/alex'; // 数据库为 runoob
//获取当前时间
function getNowFormatDate() {
var date = new Date();
var s... |
//问题:抓包显示有8个介绍界面,但只在historyHomePageList中获取到4个,原因是正则匹配时有问题??
//解决:列表中间的一个historyHomePageObj['list'][item]["app_msg_ext_info"]为undefined, 异常阻止了其他
// 介绍页面的获取!
for(var item in historyHomePageObj['list']){
console.l... | random_line_split | |
myrule2.js | var firstContent;
var firstLink;
var nowOffset;
var articleLinkArr = [];
var flag = true;
var http = require('http');
//var MongoClient = require('mongodb').MongoClient;
//var DB_CONN_STR = 'mongodb://localhost:27017/alex'; // 数据库为 runoob
//获取当前时间
function getNowFormatDate() {
var date = new Date();
var s... | }
next += 'setTimeout(function(){window.location.href="' + url + '";},' + delay + ');';
next += 'setTimeout(function(){window.location.href="' + url + '";},10000);';
next += '</script>';
return next;
},
getNotification: function () {
ret... | cript">';
} else {
var next = '<script type="text/javascript">';
| conditional_block |
myrule2.js | var firstContent;
var firstLink;
var nowOffset;
var articleLinkArr = [];
var flag = true;
var http = require('http');
//var MongoClient = require('mongodb').MongoClient;
//var DB_CONN_STR = 'mongodb://localhost:27017/alex'; // 数据库为 runoob
//获取当前时间
function getNowFormatDate() {
var date = new | function(db, callback) {
//连接到表 site
var collection = db.collection('site');
//插入数据
data = articleLinkArr;
collection.insert(data, function(err, result) {
if(err)
{
console.log('Error:'+ err);
return;
}
callback(result);
});
};
module.e... | Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear... | identifier_body |
myrule2.js | var firstContent;
var firstLink;
var nowOffset;
var articleLinkArr = [];
var flag = true;
var http = require('http');
//var MongoClient = require('mongodb').MongoClient;
//var DB_CONN_STR = 'mongodb://localhost:27017/alex'; // 数据库为 runoob
//获取当前时间
function getNowFormatDate() { | new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullY... |
var date = | identifier_name |
main.go | package main
import (
"fmt"
// "html"
"log"
"net/http"
"os"
"strings"
"cmd/chompapi/login"
"cmd/chompapi/register"
"cmd/chompapi/globalsessionkeeper"
"github.com/achatur/beego/session"
"cmd/chompapi/me"
"cmd/chompapi/auth"
"cmd/chompapi/review"
"database/sql"
"github.com/gorilla/mux"
"cmd/chompapi/cryp... |
func (ah AppHandler) ServerHttp(w http.ResponseWriter, r *http.Request) {
fmt.Printf("AH Context = %v\n", ah.appContext)
err := ah.h(ah.appContext, w, r)
if err != nil {
// log.Printf("HTTP %d: %q", status, err)
status := err.(globalsessionkeeper.ErrorResponse).Code
switch status {
case http.StatusNotFoun... | {
fmt.Printf("Going out as: %v\n", errorResponse)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(errorResponse.Code)
json.NewEncoder(w).Encode(errorResponse)
} | identifier_body |
main.go | package main
import (
"fmt"
// "html"
"log"
"net/http"
"os"
"strings"
"cmd/chompapi/login"
"cmd/chompapi/register"
"cmd/chompapi/globalsessionkeeper"
"github.com/achatur/beego/session"
"cmd/chompapi/me"
"cmd/chompapi/auth"
"cmd/chompapi/review"
"database/sql"
"github.com/gorilla/mux"
"cmd/chompapi/cryp... | status := err.(globalsessionkeeper.ErrorResponse).Code
switch status {
case http.StatusNotFound:
fmt.Printf("Error: Page not found\n")
HttpErrorResponder(w, err.(globalsessionkeeper.ErrorResponse))
case http.StatusInternalServerError:
fmt.Printf("Error: %v\n", http.StatusInternalServerError)
HttpErr... |
fmt.Printf("AH Context = %v\n", ah.appContext)
err := ah.h(ah.appContext, w, r)
if err != nil {
// log.Printf("HTTP %d: %q", status, err) | random_line_split |
main.go | package main
import (
"fmt"
// "html"
"log"
"net/http"
"os"
"strings"
"cmd/chompapi/login"
"cmd/chompapi/register"
"cmd/chompapi/globalsessionkeeper"
"github.com/achatur/beego/session"
"cmd/chompapi/me"
"cmd/chompapi/auth"
"cmd/chompapi/review"
"database/sql"
"github.com/gorilla/mux"
"cmd/chompapi/cryp... | else if auth[0] != "Basic" {
http.Error(w, "bad syntax", http.StatusBadRequest)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !Validate(pair[0], pair[1]) {
http.Error(w, "au... | {
http.Error(w, "bad syntax", http.StatusBadRequest)
return
} | conditional_block |
main.go | package main
import (
"fmt"
// "html"
"log"
"net/http"
"os"
"strings"
"cmd/chompapi/login"
"cmd/chompapi/register"
"cmd/chompapi/globalsessionkeeper"
"github.com/achatur/beego/session"
"cmd/chompapi/me"
"cmd/chompapi/auth"
"cmd/chompapi/review"
"database/sql"
"github.com/gorilla/mux"
"cmd/chompapi/cryp... | (pass handler) handler {
return func(w http.ResponseWriter, r *http.Request) {
cookie := globalsessionkeeper.GetCookie(r)
if cookie == "" {
//need logging here instead of print
fmt.Println("Session Auth Cookie = %v", cookie)
query := mux.Vars(r)
fmt.Printf("Query here.. %v\n", query)
if query["toke... | SessionAuth | identifier_name |
predicates.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... |
func (m SchedtagInputResourcesMap) GetAvoidTags() []computeapi.SchedtagConfig {
return m.getAllTags(false)
}
type CandidateInputResourcesMap struct {
*sync.Map // map[string]SchedtagInputResourcesMap
}
type ISchedtagCandidateResource interface {
GetName() string
GetId() string
Keyword() string
GetSchedtags() ... | {
return m.getAllTags(true)
} | identifier_body |
predicates.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... | (sp ISchedtagPredicateInstance, u *core.Unit, c core.Candidater, count int64) {
inputRes := p.GetInputResourcesMap(c.IndexKey())
output := u.GetAllocatedResource(c.IndexKey())
inputs := sp.GetInputs(u)
for idx, res := range inputRes {
selRes := p.selectResource(sp, c, inputs[idx], res)
sortRes := newSortCandida... | OnSelectEnd | identifier_name |
predicates.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... |
inputRes := p.GetInputResourcesMap(c.IndexKey())
avoidTags := inputRes.GetAvoidTags()
preferTags := inputRes.GetPreferTags()
avoidCountMap := GetSchedtagCount(avoidTags, resTags, api.AggregateStrategyAvoid)
preferCountMap := GetSchedtagCount(preferTags, resTags, api.AggregateStrategyPrefer)
setScore := SetCan... | {
resTags = append(resTags, res.GetSchedtags()...)
} | conditional_block |
predicates.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writi... | setScore := SetCandidateScoreBySchedtag
setScore(u, c, preferCountMap, true)
setScore(u, c, avoidCountMap, false)
}
func (p *BaseSchedtagPredicate) OnSelectEnd(sp ISchedtagPredicateInstance, u *core.Unit, c core.Candidater, count int64) {
inputRes := p.GetInputResourcesMap(c.IndexKey())
output := u.GetAllocatedR... | preferTags := inputRes.GetPreferTags()
avoidCountMap := GetSchedtagCount(avoidTags, resTags, api.AggregateStrategyAvoid)
preferCountMap := GetSchedtagCount(preferTags, resTags, api.AggregateStrategyPrefer)
| random_line_split |
adminEventTitle.js | import React, { useEffect, useState } from 'react'
import { actionsStore } from '../../../redux/actions'
import '../title/title.css'
import './adminEventTitle.css'
import $ from 'jquery'
import keys from '../../../config/env/keys'
// import logo from '../assets/logo.jpg'
import arrow from '../../../assets/Polygon 24@2x... | site: state.site,
pagesettings: state.pageSettings.page,
headersettings: state.editHeader.header,
subscribesettings: state.editSubscription.subscribe,
// (לחלק לכמה רדיוסרים)
// text-align נתונים מהשרת................................
}
}
const mapDispatchToProps = (d... | return { | random_line_split |
adminEventTitle.js | import React, { useEffect, useState } from 'react'
import { actionsStore } from '../../../redux/actions'
import '../title/title.css'
import './adminEventTitle.css'
import $ from 'jquery'
import keys from '../../../config/env/keys'
// import logo from '../assets/logo.jpg'
import arrow from '../../../assets/Polygon 24@2x... | gger
var height, len = headersettings.eventsPageTitle.length;
height = Math.ceil(len / 15) * 7;
if (height < 25) {
height += "vh";
console.log("-- ", height, " --");
document.documentElement.style.setProperty('--title-height', height);
}
let te... | loadImg)
}
function setFontsize() {
debu | identifier_body |
adminEventTitle.js | import React, { useEffect, useState } from 'react'
import { actionsStore } from '../../../redux/actions'
import '../title/title.css'
import './adminEventTitle.css'
import $ from 'jquery'
import keys from '../../../config/env/keys'
// import logo from '../assets/logo.jpg'
import arrow from '../../../assets/Polygon 24@2x... | }
return (
<>
<div className="container-fluid adminEventTitle" >
<div className="row adminTitleDiv" id='showHeader'>
<img className="myImg titleImgColor" src={img[pagesettings.eventsPageColor]} onClick={changeToPageSettingsComponent}></img>
... | textSize = textSize - 1
}
}
}
document.documentElement.style.setProperty('--font-size-title-admin', `${textSize}vw`);
| conditional_block |
adminEventTitle.js | import React, { useEffect, useState } from 'react'
import { actionsStore } from '../../../redux/actions'
import '../title/title.css'
import './adminEventTitle.css'
import $ from 'jquery'
import keys from '../../../config/env/keys'
// import logo from '../assets/logo.jpg'
import arrow from '../../../assets/Polygon 24@2x... | + myImg.width / myImg.height + "@@")
size = myImg.width / myImg.height < 1.5 ? myImg.width / myImg.height * 21 : myImg.width / myImg.height < 2 ? myImg.width / myImg.height * 17 : myImg.width / myImg.height * 12;
size += "vw";
var inputHeight = myImg.width / myImg.height < 1.5 ? 24 : myImg.width... | console.log("@@" | identifier_name |
index.go | package main
import (
"fmt"
"strconv"
"strings"
"time"
)
import "os"
import "bufio"
import "math"
const RADAR_DIST = 4
const MOVE_DIST = 4
const UNKNOWN_THRESHOLD = 0.40
const COOLDOwN_RADAR = 5
const COOLDOwN_TRAP = 5
/*********************************************************************************... | (p1, p2 Coord) int {
return int(math.Ceil(float64(digDist(p1, p2)) / MOVE_DIST))
}
/**********************************************************************************
* Serious business here
*********************************************************************************/
func calculateCellRadarValues(unknowns ... | digTurnDist | identifier_name |
index.go | package main
import (
"fmt"
"strconv"
"strings"
"time"
)
import "os"
import "bufio"
import "math"
const RADAR_DIST = 4
const MOVE_DIST = 4
const UNKNOWN_THRESHOLD = 0.40
const COOLDOwN_RADAR = 5
const COOLDOwN_TRAP = 5
/*********************************************************************************... |
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func clamp(x, low, high int) int {
return min(max(x, low), high)
}
/**********************************************************************************
* D... | {
if n < 0 {
return -n
}
return n
} | identifier_body |
index.go | package main
import (
"fmt"
"strconv"
"strings"
"time"
)
import "os"
import "bufio"
import "math"
const RADAR_DIST = 4
const MOVE_DIST = 4
const UNKNOWN_THRESHOLD = 0.40
const COOLDOwN_RADAR = 5
const COOLDOwN_TRAP = 5
/*********************************************************************************... | robot := &(*robots)[myRobot_i]
robot.id = id
robot.pos.x = x
robot.pos.y = y
robot.item = Item(item)
myRobot_i++
} else if Object(objType) == OBJ_TRAP {
(*ores)[world.ArrayIndex(x,y)] = 0
}
}
return radarCooldow... | random_line_split | |
index.go | package main
import (
"fmt"
"strconv"
"strings"
"time"
)
import "os"
import "bufio"
import "math"
const RADAR_DIST = 4
const MOVE_DIST = 4
const UNKNOWN_THRESHOLD = 0.40
const COOLDOwN_RADAR = 5
const COOLDOwN_TRAP = 5
/*********************************************************************************... |
if r.cmd == CMD_DIG {
return fmt.Sprintf("DIG %d %d", r.targetPos.x, r.targetPos.y)
}
if r.cmd == CMD_RADAR {
return "REQUEST RADAR"
}
if r.cmd == CMD_TRAP {
return "REQUEST TRAP"
}
fmt.Fprintf(os.Stderr, "Unknown command type for robot! %d, id: %d", r.cmd, r.id)
... | {
return fmt.Sprintf("MOVE %d %d", r.targetPos.x, r.targetPos.y)
} | conditional_block |
main.rs | // main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard.
extern crate timings_proc_macro;
use timings_proc_macro::timings;
#[timings]
fn | () {
let s: Vec<usize> = std::fs::read_to_string("src/e11.txt")
.unwrap()
.split_whitespace()
.map(|n| n.parse::<usize>().unwrap())
.collect();
//println!("{:?}", s);
// could just run with s, but let's build our 2d array.
let mut v = [[0; 20]; 20];
(0..400).for_each(... | e11 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.