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 |
|---|---|---|---|---|
lib.rs | Self::IOError(_) => write!(f, "An IO error happened"),
Self::InvalidHeaderMagic(value) => write!(f, "The header is invalid. It should either be PKDPX or AT4PX. The actual value of this header (in base 10) is {:?}", value),
Self::InvalidDecompressedLength => write!(f, "The decompresse... | <F: Read + Seek>(file: &mut F) -> Result<bool, PXError> {
if file.seek(SeekFrom::End(0))? < 4 {
return Ok(false);
};
file.seek(SeekFrom::Start(0))?;
let mut header_5 = [0; 5];
file.read_exact(&mut header_5)?;
if &header_5 == b"PKDPX" {
return Ok(true);
};
if &header_5 ... | is_px | identifier_name |
lib.rs | Self::IOError(_) => write!(f, "An IO error happened"),
Self::InvalidHeaderMagic(value) => write!(f, "The header is invalid. It should either be PKDPX or AT4PX. The actual value of this header (in base 10) is {:?}", value),
Self::InvalidDecompressedLength => write!(f, "The decompresse... | }
None => {
let new_byte = px_read_u8(&mut raw_file)?;
let offset_rel: i16 =
-0x1000 + (((nb_low as i16) * 256) + (new_byte as i16));
let offset = (offset_rel as i32) + (result.len... | random_line_split | |
lib.rs | Self::IOError(_) => write!(f, "An IO error happened"),
Self::InvalidHeaderMagic(value) => write!(f, "The header is invalid. It should either be PKDPX or AT4PX. The actual value of this header (in base 10) is {:?}", value),
Self::InvalidDecompressedLength => write!(f, "The decompresse... | )?)
} else if &header_5 == b"AT4PX" {
let decompressed_lenght = px_read_u16(&mut file)? as u32;
Ok(decompress_px_raw(
file,
control_flags,
decompressed_lenght,
container_lenght,
18,
)?)
} else {
Err(PXError::Inva... | {
debug!("decompressing a px-compressed file file");
file.seek(SeekFrom::Start(0))?;
let mut header_5 = [0; 5];
file.read_exact(&mut header_5)?;
let container_lenght = px_read_u16(&mut file)?;
let mut control_flags_buffer = [0; 9];
file.read_exact(&mut control_flags_buffer)?;
let contr... | identifier_body |
contributions-infromation-form.component.ts | .module";
import {CustomStoreService} from "../../shared/services/custom-store.service";
import {CapitalRepairNotifyService} from "../../shared/services/capital-repair-notify.service";
import {ContributionsInformationMistakeService} from "../../shared/services/contributions-information-mistake.service";
import {DxiGrou... | }
} else {
this.sendForApprovalButtonVisibility = false;
this.rejectButtonVisibility = false;
this.acceptButtonVisibility = false;
this.saveButtonVisibility = false;
}
}
}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = pa... | ontrib_info.status.id == NotifyStatus.Approving) {
this.acceptButtonVisibility = false;
this.sendForApprovalButtonVisibility = false;
this.saveButtonVisibility = false;
this.rejectButtonVisibility = true;
if (user.is_staff) {
this.acceptButtonVisibility = true;
... | identifier_body |
contributions-infromation-form.component.ts | ipes.module";
import {CustomStoreService} from "../../shared/services/custom-store.service";
import {CapitalRepairNotifyService} from "../../shared/services/capital-repair-notify.service";
import {ContributionsInformationMistakeService} from "../../shared/services/contributions-information-mistake.service";
import {Dxi... | contribInfoService.retrieve(this.id).subscribe(res => {
this.contrib_info = res;
this.contrib_info = JSON.parse(JSON.stringify(res));
this.setPermissions(this.auth.current_user);
}
);
if (this.auth.current_user.is_staff) {
this.contribInfoService.g... | this. | identifier_name |
contributions-infromation-form.component.ts | ipes.module";
import {CustomStoreService} from "../../shared/services/custom-store.service";
import {CapitalRepairNotifyService} from "../../shared/services/capital-repair-notify.service";
import {ContributionsInformationMistakeService} from "../../shared/services/contributions-information-mistake.service";
import {Dxi... | ceptButtonVisibility = false;
this.saveButtonVisibility = false;
}
}
}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = params.id;
if (this.id !== '0') {
this.contribInfoService.retrieve(this.id).subscribe(res => {
this.contrib_info = ... | this.rejectButtonVisibility = false;
this.ac | conditional_block |
contributions-infromation-form.component.ts | ipes.module";
import {CustomStoreService} from "../../shared/services/custom-store.service";
import {CapitalRepairNotifyService} from "../../shared/services/capital-repair-notify.service";
import {ContributionsInformationMistakeService} from "../../shared/services/contributions-information-mistake.service";
import {Dxi... | //и по которым недавно не подавались сведения о взносах
const today = new Date();
const t2 = this.formatDate(this.addDays(today, -10));
const t1 = this.formatDate(today);
//this.contribInfoDataSource.filter([['status.id', '=', '3'], 'and', ['organization.inn', '<>', '5902990563'], 'and',
// ['!... | //отображаются только согласованые уведомления, у которых не указана ороанизация Фонд кап. ремонта ПК(5902990563) | random_line_split |
film.rs | , crop_pixel_bounds);
// Allocate film image storage
let pixels = vec![Pixel::default(); crop_pixel_bounds.area() as usize];
// TODO: filmPixelMemory
// Precompute filter weight table
let mut offset = 0;
let mut filter_table = [0.0; FILTER_TABLE_WIDTH * FILTER_TABLE_WID... |
let pi = Point2i::from(p.floor());
if !self.cropped_pixel_bounds.inside_exclusive(&pi) { return; }
if v.y() > self.max_sample_luminance {
v *= self.max_sample_luminance / v.y();
}
let mut pixels = self.pixels.write().unwrap();
let xyz = v.to_xyz();
... | {
error!("Ignoring slatted spectrum with infinite luminance at ({}, {})", p.x, p.y);
return;
} | conditional_block |
film.rs | , crop_pixel_bounds);
// Allocate film image storage
let pixels = vec![Pixel::default(); crop_pixel_bounds.area() as usize];
// TODO: filmPixelMemory
// Precompute filter weight table
let mut offset = 0;
let mut filter_table = [0.0; FILTER_TABLE_WIDTH * FILTER_TABLE_WID... | (&self, p: &Point2f, mut v: Spectrum) {
// TODO: ProfilePhase
if v.has_nans() {
error!("Ignoring splatted spectrum with NaN values at ({}, {})", p.x, p.y);
return;
} else if v.y() < 0.0 {
error!("Ignoring splatted spectrum with negative luminance {} at ({}, {}... | add_splat | identifier_name |
film.rs | _window, crop_pixel_bounds);
// Allocate film image storage
let pixels = vec![Pixel::default(); crop_pixel_bounds.area() as usize];
// TODO: filmPixelMemory
// Precompute filter weight table | let p = Point2f::new(
(x as Float + 0.5) * filt.radius().x / FILTER_TABLE_WIDTH as Float,
(y as Float + 0.5) * filt.radius().y / FILTER_TABLE_WIDTH as Float
);
filter_table[offset] = filt.evaluate(&p);
offset += 1;
... | let mut offset = 0;
let mut filter_table = [0.0; FILTER_TABLE_WIDTH * FILTER_TABLE_WIDTH];
for y in 0..FILTER_TABLE_WIDTH {
for x in 0..FILTER_TABLE_WIDTH { | random_line_split |
film.rs |
}
pub struct Film {
pub full_resolution : Point2i,
pub diagonal : Float,
pub filter : Filters,
pub filename : PathBuf,
pub cropped_pixel_bounds: Bounds2i,
pixels : RwLock<Vec<Pixel>>,
filter_table : [Float; FILTER_TABLE_WID... | {
Self {
xyz: [0.0; 3],
filter_weight_sum: 0.0,
splat_xyz: [AtomicFloat::default(), AtomicFloat::default(), AtomicFloat::default()],
_pad: 0.0
}
} | identifier_body | |
auth.rs | (AuthResult::Rejected(resp))
}
fn cookie_params(req: &RequestWrapper) -> &'static str {
if req.is_https() && get_config().is_cors_enabled(&req.request) {
"SameSite=None; Secure"
} else {
"SameSite=Lax"
}
}
impl Authenticator for SharedSecretAuthenticator {
type Credentials = ();
fn... | test_token | identifier_name | |
auth.rs | _NAME).is_some())
.unwrap_or(false)
{
resp.headers_mut().append(
SET_COOKIE,
HeaderValue::from_str(&format!(
"{}=; Expires={}; {}",
COOKIE_NAME,
COOKIE_DELETE_DATE, | ); // unwrap is safe as we control
}
Ok(AuthResult::Rejected(resp))
}
fn cookie_params(req: &RequestWrapper) -> &'static str {
if req.is_https() && get_config().is_cors_enabled(&req.request) {
"SameSite=None; Secure"
} else {
"SameSite=Lax"
}
}
impl Authenticator for Share... | cookie_params(req)
))
.unwrap(), | random_line_split |
wixSelector.ts | ?: Connection
$wScope?: $WScope
itemId?: string
}) => SdkInstance | Array<SdkInstance> | null
$wFactory: (controllerId: string, getInstancesForRole: GetInstanceFunction, repeaterId?: string) => $W
flushOnReadyCallbacks: () => Promise<any>
onPageReady: (onReadyCallback: () => Promise<any>, controllerId: string) ... | })
if (_.isArray(instance)) {
instances.push(...instance)
} else if (instance) {
instances.push(instance)
}
return instances
}, [] as Array<SdkInstance>)
}
const getComponentInstances = (slctr: string): Array<SdkInstance> => {
if (resolveSelectorType(slctr) === 'type') {
con... | role,
compType, | random_line_split |
wixSelector.ts | Connection
$wScope?: $WScope
itemId?: string
}) => SdkInstance | Array<SdkInstance> | null
$wFactory: (controllerId: string, getInstancesForRole: GetInstanceFunction, repeaterId?: string) => $W
flushOnReadyCallbacks: () => Promise<any>
onPageReady: (onReadyCallback: () => Promise<any>, controllerId: string) =>... |
return instancesObjectFactory(instances)
}
const $wFactory: WixSelector['$wFactory'] = (controllerId: string, getInstancesForRole, repeaterId): $W => {
const wixSelectorInternal = (selector: string, { findOnlyNestedComponents } = { findOnlyNestedComponents: false }) => {
if (selector === 'Document') {
re... | {
return _.first(instances) || []
} | conditional_block |
wixSelector.ts | Connection
$wScope?: $WScope
itemId?: string
}) => SdkInstance | Array<SdkInstance> | null
$wFactory: (controllerId: string, getInstancesForRole: GetInstanceFunction, repeaterId?: string) => $W
flushOnReadyCallbacks: () => Promise<any>
onPageReady: (onReadyCallback: () => Promise<any>, controllerId: string) =>... |
const createInstancesGetter = (controllerId: string): GetInstanceFunction => (role: string) => {
const connections = modelsApi.getConnectionsByCompId(controllerId, role)
return connections.map((connection: Connection) => {
const compId = connection.compId
const compType = modelsApi.getCompType(compId)
i... | {
onReadyCallbacks[controllerId] = onReadyCallbacks[controllerId] || []
onReadyCallbacks[controllerId].push(onReadyCallback)
} | identifier_body |
wixSelector.ts | ?: Connection
$wScope?: $WScope
itemId?: string
}) => SdkInstance | Array<SdkInstance> | null
$wFactory: (controllerId: string, getInstancesForRole: GetInstanceFunction, repeaterId?: string) => $W
flushOnReadyCallbacks: () => Promise<any>
onPageReady: (onReadyCallback: () => Promise<any>, controllerId: string) ... | (onReadyCallback: () => Promise<any>, controllerId: string) {
onReadyCallbacks[controllerId] = onReadyCallbacks[controllerId] || []
onReadyCallbacks[controllerId].push(onReadyCallback)
}
const createInstancesGetter = (controllerId: string): GetInstanceFunction => (role: string) => {
const connections = modelsA... | queueOnReadyCallback | identifier_name |
train.py | parser
def program_config(parser):
# ------ Add new params here ------>
parser.add_argument('--max_seq_len', default=cfg.max_seq_len, type=int)
parser.add_argument('--test_ratio', default=cfg.test_ratio, type=float)
parser.add_argument('--hidden_dim', default=cfg.hidden_dim, type=int)
parser.add_a... | data_train = data[:num_train]
data_test = data[num_train:]
# Torch dataset and dataloader
train_dataset = LanguageDataset(data_train, wv_dict, padding, cfg.max_seq_len)
train_loader = DataLoader(dataset=train_dataset, batch_size=cfg.batch_size, shuffle=False)
if cfg.test_ratio > 0:
tes... | # Split data into training and testing sets
num_train = int(len(data) * (1 - cfg.test_ratio)) | random_line_split |
train.py | parser
def program_config(parser):
# ------ Add new params here ------>
parser.add_argument('--max_seq_len', default=cfg.max_seq_len, type=int)
parser.add_argument('--test_ratio', default=cfg.test_ratio, type=float)
parser.add_argument('--hidden_dim', default=cfg.hidden_dim, type=int)
parser.add_a... |
# Main
if __name__ == '__main__':
# Hyper parameters and configs
parser = argparse.ArgumentParser()
parser = program_config(parser)
opt = parser.parse_args()
cfg.init_param(opt)
# Get word2vec dict with embedding model
cfg.logger.info('Loading embedding model.')
wv_dict = Word2VecDic... | total_loss, total_acc = 0, 0
model.eval()
with torch.no_grad():
for feature, target in tqdm(test_loader, desc='Test'):
feature, target = feature.to(cfg.device), target.long().to(cfg.device)
hidden = init_hidden(feature.size(0), cfg.hidden_dim, cfg.device)
... | identifier_body |
train.py | parser
def program_config(parser):
# ------ Add new params here ------>
parser.add_argument('--max_seq_len', default=cfg.max_seq_len, type=int)
parser.add_argument('--test_ratio', default=cfg.test_ratio, type=float)
parser.add_argument('--hidden_dim', default=cfg.hidden_dim, type=int)
parser.add_a... |
cfg.logger.info('Training.')
for epoch in range(1, cfg.num_epochs + 1):
train_losses_, train_accs_ = train_dis_epoch(epoch, language_model, train_loader, criterion, optimizer)
train_losses += train_losses_
train_accs += train_accs_
| test_losses, test_accs = [], [] | conditional_block |
train.py | parser
def | (parser):
# ------ Add new params here ------>
parser.add_argument('--max_seq_len', default=cfg.max_seq_len, type=int)
parser.add_argument('--test_ratio', default=cfg.test_ratio, type=float)
parser.add_argument('--hidden_dim', default=cfg.hidden_dim, type=int)
parser.add_argument('--batch_size', de... | program_config | identifier_name |
xdp.go | descriptor to the same UMEM area in the RX queue, signifying
// that userspace may read the packet.
// - Trasmit: Userspace adds a descriptor to TX queue. The kernel
// sends the packet (stored in UMEM) pointed to by the descriptor.
// Upon completion, the kernel places a desciptor in the completion
// ... | 0,
)
if err != nil {
return nil, fmt.Errorf("failed to mmap umem: %v", err)
}
cleanup := cleanup.Make(func() {
memutil.UnmapSlice(umemMemory)
})
if sliceBackingPointer(umemMemory)%uintptr(unix.Getpagesize()) != 0 {
return nil, fmt.Errorf("UMEM is not page aligned (address 0x%x)", sliceBackingPointer(umem... | {
if opts.FrameSize != 2048 && opts.FrameSize != 4096 {
return nil, fmt.Errorf("invalid frame size %d: must be either 2048 or 4096", opts.FrameSize)
}
if bits.OnesCount32(opts.NDescriptors) != 1 {
return nil, fmt.Errorf("invalid number of descriptors %d: must be a power of 2", opts.NDescriptors)
}
var cb Cont... | identifier_body |
xdp.go | descriptor to the same UMEM area in the RX queue, signifying
// that userspace may read the packet.
// - Trasmit: Userspace adds a descriptor to TX queue. The kernel
// sends the packet (stored in UMEM) pointed to by the descriptor.
// Upon completion, the kernel places a desciptor in the completion
// ... |
if bits.OnesCount32(opts.NDescriptors) != 1 {
return nil, fmt.Errorf("invalid number of descriptors %d: must be a power of 2", opts.NDescriptors)
}
var cb ControlBlock
// Create the UMEM area. Use mmap instead of make([[]byte) to ensure
// that the UMEM is page-aligned. Aligning the UMEM keeps individual
// ... | {
return nil, fmt.Errorf("invalid frame size %d: must be either 2048 or 4096", opts.FrameSize)
} | conditional_block |
xdp.go | //
// The ControlBlock and the structures it contains are meant to be used with a
// single RX goroutine and a single TX goroutine.
type ControlBlock struct {
UMEM UMEM
Fill FillQueue
RX RXQueue
TX TXQueue
Completion CompletionQueue
}
// ReadOnlySocketOpts configure a read-only AF_XDP ... | unix.PROT_READ|unix.PROT_WRITE,
unix.MAP_SHARED|unix.MAP_POPULATE,
uintptr(sockfd), | random_line_split | |
xdp.go | descriptor to the same UMEM area in the RX queue, signifying
// that userspace may read the packet.
// - Trasmit: Userspace adds a descriptor to TX queue. The kernel
// sends the packet (stored in UMEM) pointed to by the descriptor.
// Upon completion, the kernel places a desciptor in the completion
// ... | (ifaceIdx, queueID uint32, opts ReadOnlySocketOpts) (*ControlBlock, error) {
sockfd, err := unix.Socket(unix.AF_XDP, unix.SOCK_RAW, 0)
if err != nil {
return nil, fmt.Errorf("failed to create AF_XDP socket: %v", err)
}
return ReadOnlyFromSocket(sockfd, ifaceIdx, queueID, opts)
}
// ReadOnlyFromSocket takes an AF... | ReadOnlySocket | identifier_name |
feature.go | /v2alpha1"
apiutils "github.com/DataDog/datadog-operator/apis/utils"
"github.com/DataDog/datadog-operator/controllers/datadogagent/component"
"github.com/DataDog/datadog-operator/controllers/datadogagent/feature"
"github.com/DataDog/datadog-operator/controllers/datadogagent/merger"
"github.com/DataDog/datadog-oper... | hostPortHostPort int32
useHostNetwork bool
udsEnabled bool
udsHostFilepath string
owner metav1.Object
forceEnableLocalService bool
localServiceName string
createKubernetesNetworkPolicy bool
createCiliumNetworkPolicy bool
createSCC bool
}
// ID returns the ID of the F... | hostPortEnabled bool | random_line_split |
feature.go | /v2alpha1"
apiutils "github.com/DataDog/datadog-operator/apis/utils"
"github.com/DataDog/datadog-operator/controllers/datadogagent/component"
"github.com/DataDog/datadog-operator/controllers/datadogagent/feature"
"github.com/DataDog/datadog-operator/controllers/datadogagent/merger"
"github.com/DataDog/datadog-oper... |
if dda.Spec.Global.LocalService != nil {
f.forceEnableLocalService = apiutils.BoolValue(dda.Spec.Global.LocalService.ForceEnableLocalService)
}
f.localServiceName = v2alpha1.GetLocalAgentServiceName(dda)
f.createSCC = v2alpha1.ShouldCreateSCC(dda, v2alpha1.NodeAgentComponentName)
reqComp = feature.Requi... | {
f.owner = dda
apm := dda.Spec.Features.APM
if apm != nil && apiutils.BoolValue(apm.Enabled) {
f.useHostNetwork = v2alpha1.IsHostNetworkEnabled(dda, v2alpha1.NodeAgentComponentName)
// hostPort defaults to 'false' in the defaulting code
f.hostPortEnabled = apiutils.BoolValue(apm.HostPortConfig.Enabled)
f.ho... | identifier_body |
feature.go | /v2alpha1"
apiutils "github.com/DataDog/datadog-operator/apis/utils"
"github.com/DataDog/datadog-operator/controllers/datadogagent/component"
"github.com/DataDog/datadog-operator/controllers/datadogagent/feature"
"github.com/DataDog/datadog-operator/controllers/datadogagent/merger"
"github.com/DataDog/datadog-oper... | ingressRules,
nil,
)
}
else if f.createCiliumNetworkPolicy {
policySpecs := []cilium.NetworkPolicySpec{
{
Description: "Ingress for APM trace",
EndpointSelector: podSelector,
Ingress: []cilium.IngressRule{
{
FromEndpoints: []metav1.LabelSelector{
{},
... | {
protocolTCP := corev1.ProtocolTCP
ingressRules := []netv1.NetworkPolicyIngressRule{
{
Ports: []netv1.NetworkPolicyPort{
{
Port: &intstr.IntOrString{
Type: intstr.Int,
IntVal: f.hostPortHostPort,
},
Protocol: &protocolTCP,
},
},
},
}
retu... | conditional_block |
feature.go | f.createKubernetesNetworkPolicy = true
}
}
}
// UDS defaults to 'true' in the defaulting code
f.udsEnabled = apiutils.BoolValue(apm.UnixDomainSocketConfig.Enabled)
f.udsHostFilepath = *apm.UnixDomainSocketConfig.Path
if dda.Spec.Global.LocalService != nil {
f.forceEnableLocalService = apiutils... | ManageClusterChecksRunner | identifier_name | |
demo.js | (xml, container) {
// Parallel arrays for the chart data, these are populated as the XML/JSON file
// is loaded
this.symbols = [];
this.symbolNames = [];
this.precipitations = [];
this.windDirections = [];
this.windDirectionNames = [];
this.windSpeeds = [];
this.windSpeedNames = [];
... | Meteogram | identifier_name | |
demo.js | Calm', 'Light air', 'Light breeze', 'Gentle breeze', 'Moderate breeze',
'Fresh breeze', 'Strong breeze', 'Near gale', 'Gale', 'Strong gale', 'Storm',
'Violent storm', 'Hurricane']);
if (level === 0) {
path = [];
}
if (level === 2) {
path.push('M', 0, -8, 'L', 4, -8); // sho... | return this.y;
}
| conditional_block | |
demo.js |
/**
* Return weather symbol sprites as laid out at http://om.yr.no/forklaring/symbol/
*/
Meteogram.prototype.getSymbolSprites = function (symbolSize) {
return {
'01d': {
x: 0,
y: 0
},
'01n': {
x: symbolSize,
y: 0
},
'16': {
... | {
// Parallel arrays for the chart data, these are populated as the XML/JSON file
// is loaded
this.symbols = [];
this.symbolNames = [];
this.precipitations = [];
this.windDirections = [];
this.windDirectionNames = [];
this.windSpeeds = [];
this.windSpeedNames = [];
this.temperat... | identifier_body | |
demo.js | x: 0,
y: 9 * symbolSize
},
'11': {
x: 0,
y: 10 * symbolSize
},
'12': {
x: 0,
y: 11 * symbolSize
},
'13': {
x: 0,
y: 12 * symbolSize
},
'14': {
x: 0,... | $.each(chart.series[0].data, function (i, point) {
var sprite,
group;
if (meteogram.resolution > 36e5 || i % 2 === 0) {
sprite = symbolSprites[meteogram.symbols[i]];
if (sprite) {
// Create a group element that is positioned and clipped at 30 pi... | random_line_split | |
cli.rs | to be used to inline a function of small size. Can be empty or `{:inline}`.
pub func_inline: String,
/// A bound to apply to the length of serialization results.
pub serialize_bound: usize,
/// How many times to call the prover backend for the verification problem. This is used for
/// benchmarking... | get_boogie_command | identifier_name | |
cli.rs | verbosity_level: LevelFilter,
/// Whether to run the documentation generator instead of the prover.
pub run_docgen: bool,
/// An account address to use if none is specified in the source.
pub account_address: String,
/// The paths to the Move sources.
pub move_sources: Vec<String>,
/// The ... | /// Whether to minimize execution traces in errors.
pub minimize_execution_trace: bool,
/// Whether to omit debug information in generated model.
pub omit_model_debug: bool,
/// Whether output for e.g. diagnosis shall be stable/redacted so it can be used in test
/// output.
pub stable_test_o... | pub generate_only: bool,
/// Whether to generate stubs for native functions.
pub native_stubs: bool, | random_line_split |
cli.rs | z3_exe: String,
/// Whether to use cvc4.
pub use_cvc4: bool,
/// Path to the cvc4 executable.
pub cvc4_exe: String,
/// List of flags to pass on to boogie.
pub boogie_flags: Vec<String>,
/// Whether to use native array theory.
pub use_array_theory: bool,
/// Whether to produce an SM... | {
Ok(options)
} | conditional_block | |
glideKeeper.py | %s'%self.glidekeeper_constraint)
# string, what our ads will be identified at the factories
self.classad_id=classad_id
ilog('Thread classad_id: %s'%classad_id)
# factory pools is a list of pairs, where
# [0] is factory node
# [1] is factory identity
... |
# Deadvertize my add, so the factory knows we are gone
for factory_pool in self.factory_pools:
factory_pool_node=factory_pool[0]
ilog('Deadvertising for node %s'%dbgp(factory_pool_node))
try:
glideinFrontendInterface.deadvertizeAllWork(factory_pool_no... | random_line_split | |
glideKeeper.py | %s'%self.glidekeeper_constraint)
# string, what our ads will be identified at the factories
self.classad_id=classad_id
ilog('Thread classad_id: %s'%classad_id)
# factory pools is a list of pairs, where
# [0] is factory node
# [1] is factory identity
... |
##############
# INTERNAL
def reload_proxy(self):
ilog('Reloading proxy from fname: %s'%str(self.proxy_fname))
if self.proxy_fname==None:
self.proxy_data=None
return
proxy_fd=open(self.proxy_fname,'r')
try:
self.proxy_data=proxy_fd.read()... | self.shutdown=False
first=True
while (not self.shutdown) or self.need_cleanup:
if first:
first=False
else:
# do not sleep the first round
time.sleep(20)
self.reload_proxy()
if (self.needed_glideins>0) and (n... | identifier_body |
glideKeeper.py | : %s'%self.glidekeeper_constraint)
# string, what our ads will be identified at the factories
self.classad_id=classad_id
ilog('Thread classad_id: %s'%classad_id)
# factory pools is a list of pairs, where
# [0] is factory node
# [1] is factory identity
... |
nr_entries=len(glidein_dict.keys())
if running_glideins>=self.needed_glideins:
additional_glideins=0
else:
# ask for 2/3 since it takes a few cycles to stabilize
additional_glideins=(self.needed_glideins-running_glideins)*2/3+1
if additional | ilog('Now testing glidein with name %s'%glidename)
glidein_el=factory_glidein_dict[glidename]
ilog('Glidein stats: \n\n %s \n\n'%dbgp(glidein_el))
if not glidein_el['attrs'].has_key('PubKeyType'): # no pub key at all, skip
ilog('%s has no PubKeyType --... | conditional_block |
glideKeeper.py | %s'%self.glidekeeper_constraint)
# string, what our ads will be identified at the factories
self.classad_id=classad_id
ilog('Thread classad_id: %s'%classad_id)
# factory pools is a list of pairs, where
# [0] is factory node
# [1] is factory identity
... | (self):
ilog('Thread is cleaning up glideins.')
from glideinwms.frontend import glideinFrontendInterface
from glideinwms.lib import condorMonitor, condorExe
# Deadvertize my add, so the factory knows we are gone
for factory_pool in self.factory_pools:
factory_pool_no... | cleanup_glideins | identifier_name |
main.rs | "Number of panels painted at least once: {}",
painted_hull.len()
);
let registration_id_hull = paint_hull(
robot_program,
iter::once((Point::origin(), Color::White)).collect(),
Color::Black,
)?;
print_hull(®istration_id_hull, Color::Black);
Ok(())
}
fn print_h... | program_str
.split(",")
.map(|num_str| {
num_str
.trim()
.parse()
.map_err(|_| anyhow!("Could not parse number in program as isize: '{}'", num_str))
})
.try_collect()
}
| identifier_body | |
main.rs | Mutex};
use tokio::pin;
use tokio_stream::{Stream, StreamExt};
fn main() -> Result<(), anyhow::Error> {
let matches = App::new("2019-11")
.arg(Arg::from_usage("[input] 'Problem input file'").default_value("input.txt"))
.get_matches();
let input_filename = matches.value_of("input").unwrap();
... | pcode: usize) -> Result<Vec<ParameterModes>, anyhow::Error> {
opcode
.digits()
.rev()
.skip(2)
.map(ParameterModes::try_from)
.try_collect()
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum ParameterModes {
Position,
Immediate,
Relative,
}
impl TryFrom<u8> fo... | t_parameter_modes(o | identifier_name |
main.rs | ::Mutex};
use tokio::pin;
use tokio_stream::{Stream, StreamExt};
fn main() -> Result<(), anyhow::Error> {
let matches = App::new("2019-11")
.arg(Arg::from_usage("[input] 'Problem input file'").default_value("input.txt"))
.get_matches();
let input_filename = matches.value_of("input").unwrap();
... | Up,
Down,
Left,
Right,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, From)]
struct Point {
x: isize,
y: isize,
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("").field(&self.x).field(&self.y).finish()
}
}
impl Point {
fn o... | }
#[derive(Clone, Copy, PartialEq, Eq)]
enum Direction { | random_line_split |
env.rs | {
Single(KObj),
Range(Vec<KObj>),
None,
}
/// Keep track of our repl environment
pub struct Env {
pub config: Config,
pub click_config: ClickConfig,
click_config_path: PathBuf,
pub quit: bool,
pub need_new_editor: bool,
pub kluster: Option<Kluster>,
pub namespace: Option<String... | ObjectSelection | identifier_name | |
env.rs | io::Result<TempDir>,
}
lazy_static! {
static ref CTC_BOOL: Arc<AtomicBool> = {
let b = Arc::new(AtomicBool::new(false));
let r = b.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
b
};
... | }
/// Add a new task for the env to keep track of
pub fn add_port_forward(&mut self, pf: PortForward) {
self.port_forwards | } | random_line_split |
env.rs | ::new(false));
let r = b.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
b
};
}
impl Env {
pub fn new(config: Config, click_config: ClickConfig, click_config_path: PathBuf) -> Env {
le... | {
self.port_forwards.iter()
} | identifier_body | |
bundle_es5.js | Content = document.getElementsByClassName('tab_content'),
tabCalc = document.querySelector('.popup_calc'),
tabCalcInput = tabCalc.getElementsByTagName('input'),
calcItem = document.querySelector('.balcon_icons'),
closeCalc = tabCalc.getElementsByTagName('strong')[0];
var _loop2 = functio... |
function updateClock() {
var t = getTimeRemaining(endtime);
days.innerHTML = t.days < 10 ? '0' + t.days : t.days; | random_line_split | |
bundle_es5.js | ", "application/x-www-form-urlencoded");
var formData = new FormData(form[_i5]);
request.send(formData);
request.onreadystatechange = function () {
if (request.readyState < 4) {
statusMessage.innerHTML = message.loading;
} else if (request.readyState === 4) {
if (request.stat... | ide')) {
| identifier_name | |
bundle_es5.js | return r;
})()({ 1: [function (require, module, exports) {
window.addEventListener('DOMContentLoaded', function () {
var modal = require('../parts/modal.js');
var form = require('../parts/form.js');
var tabFirst = require('../parts/tabFirst.js');
var tabSeconds = require('../parts/tabSeconds.js');
var... | {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = "function" == typeof require && require;if (!f && c) return c(i, !0);if (u) return u(i, !0);var a = new Error("Cannot find module '" + i + "'");throw a.code = "MODULE_NOT_FOUND", a;
}var p = n[i] = { exports: {} };e[i][0].call(p.exports, function ... | identifier_body | |
bundle_es5.js | val = def;
this.value = matrix.replace(/./g, function (a) {
return (/[_\d]/.test(a) && i < val.length ? val.charAt(i++) : i >= val.length ? "" : a
);
});
if (event.type == "blur") {
if (this.value.length == 2) this.value = "";
} else setCursorPosition(this.value.length, this);
};
... | {
if (checkbox[z] | conditional_block | |
lib.rs | Mode::PreOrder, |_, entry| {
if let Ok(commit) =
transaction.repo().find_commit(entry.id())
{
if let Some(id) = josh::get_change_id(&commit) {
amends.insert(id, commit.id());
}
... | HashedPassword | identifier_name | |
lib.rs | (p)?;
let push_options: Vec<&str> = push_options_string.split("\n").collect();
for (refname, (old, new)) in repo_update.refs.iter() {
tracing::debug!("REPO_UPDATE env ok");
let transaction = josh::cache::Transaction::open(
&std::path::Path::new(&repo_update.git_dir),
)?;
... | &repo_update.base_ns, &baseref
);
let backward_commit =
transaction.repo().find_commit(backward_new_oid)?;
if let Ok(Ok(base_commit)) = transaction
.repo()
.revparse_single(&rev)
.map(|x| x.peel_to_commit... | let rev = format!(
"refs/josh/upstream/{}/{}", | random_line_split |
lib.rs | )?;
let push_options: Vec<&str> = push_options_string.split("\n").collect();
for (refname, (old, new)) in repo_update.refs.iter() {
tracing::debug!("REPO_UPDATE env ok");
let transaction = josh::cache::Transaction::open(
&std::path::Path::new(&repo_update.git_dir),
)?;
... | ;
let cmd = format!("git push {} '{}'", &nurl, &spec);
let mut fakehead = repo.reference(&rn, oid, true, "push_head_url")?;
let (stdout, stderr, status) =
shell.command_env(&cmd, &[], &[("GIT_PASSWORD", &password.value)]);
fakehead.delete()?;
tracing::debug!("{}", &stderr);
tracing::debu... | {
url.to_owned()
} | conditional_block |
lib.rs | ::filter::parse(&repo_update.filter_spec)?;
let new_oid = git2::Oid::from_str(&new)?;
let backward_new_oid = {
tracing::debug!("=== MORE");
tracing::debug!("=== processed_old {:?}", old);
match josh::history::unapply_filter(
&transaction,
... | {
f.debug_struct("HashedPassword")
.field("value", &self.hash)
.finish()
} | identifier_body | |
nklab-bids-convert.py | derivatives directories will be deleted.')
parser.add_argument('--exceptionlist', action='store',
help='File containing list of exception dicoms to be manually identifed due to problems with the obtained datetime')
parser.add_argument('--noprompt',action='store_true', default=False,
help='Use this flag to bypass... |
def main():
opts = get_parser().parse_args()
ROOTDIR=os.path.abspath(opts.dicomdir)
STAGEDIR=os.path.abspath(opts.stagedir)
OUTPUTDIR=os.path.abspath(opts.bidsdir)
if opts.workdir:
WORKDIR=os.path.abspath(opts.workdir)
else:
WORKDIR=os.getcwd()
BIDSROOTDIR= os.path.dirname(STAGEDIR)
BIDSKITROOTDIR = os... | stamp=datetime.datetime.now().strftime("%m-%d-%y %H:%M:%S%p")
textstring=stamp + ' ' + textstr
print(textstring)
logfile.write(textstring+'\n') | identifier_body |
nklab-bids-convert.py | derivatives directories will be deleted.')
parser.add_argument('--exceptionlist', action='store',
help='File containing list of exception dicoms to be manually identifed due to problems with the obtained datetime')
parser.add_argument('--noprompt',action='store_true', default=False,
help='Use this flag to bypass... | (logfile, textstr):
stamp=datetime.datetime.now().strftime("%m-%d-%y %H:%M:%S%p")
textstring=stamp + ' ' + textstr
print(textstring)
logfile.write(textstring+'\n')
def main():
opts = get_parser().parse_args()
ROOTDIR=os.path.abspath(opts.dicomdir)
STAGEDIR=os.path.abspath(opts.stagedir)
OUTPUTDIR=os.path.ab... | logtext | identifier_name |
nklab-bids-convert.py | derivatives directories will be deleted.')
parser.add_argument('--exceptionlist', action='store',
help='File containing list of exception dicoms to be manually identifed due to problems with the obtained datetime')
parser.add_argument('--noprompt',action='store_true', default=False,
help='Use this flag to bypass... | if opts.bidstranslator:
BIDSTRANSLATOR=os.path.abspath(opts.bidstranslator)
else:
BIDSTRANSLATOR=None
if opts.exceptionlist:
EXCEPTIONFILE=os.path.abspath(opts.exceptionlist)
else:
EXCEPTIONFILE=None
if opts.logname:
BASELOGNAME=opts.logname
else:
BASELOGNAME='nklab-bids-convert'
bCONVERTONLY=opts... | CLUSTER=0
| random_line_split |
nklab-bids-convert.py | opts.convertonly
bBYPASS=opts.bypass
bNOPROMPT=opts.noprompt
bNOANON= opts.noanon
bINCREMENTAL= opts.incremental
bSTAGEONLY=opts.stageonly
# always run conversions only incrementally
if bCONVERTONLY:
bINCREMENTAL=True
TIMESTAMP=datetime.datetime.now().strftime("%m%d%y%H%M%S%p")
LOGFILENAME=BASELOGNAME + '_... | copyfile(ProtocolTranslator,origProtocolTranslator)
logtext(LOGFILE,"protocol translator backed up as " + origProtocolTranslator) | conditional_block | |
build.rs | use std::io::prelude::*;
use std::io;
use std::path::Path;
pub fn all(path: &Path, mcus: &[Mcu]) -> Result<(), io::Error> {
fs::create_dir_all(path)?;
let mut module_names = Vec::new();
// Create modules for each mcu.
for mcu in mcus.iter() {
let module_nam... |
result.insert(r.name.clone(), r);
}
}
}
result
}
| register.clone()
};
| conditional_block |
build.rs | use std::io::prelude::*;
use std::io;
use std::path::Path;
pub fn all(path: &Path, mcus: &[Mcu]) -> Result<(), io::Error> {
fs::create_dir_all(path)?;
let mut module_names = Vec::new();
// Create modules for each mcu.
for mcu in mcus.iter() {
let module_nam... |
}
Ok(())
}
fn ordered_registers(mcu: &Mcu) -> Vec<Register> {
let mut unique_registers = self::unique_registers(mcu);
insert_high_low_variants(&mut unique_registers);
let mut registers: Vec<Register> = unique_registers.into_iter().map(|a| a.1).collect();
regis... | random_line_split | |
build.rs | use std::io::prelude::*;
use std::io;
use std::path::Path;
pub fn all(path: &Path, mcus: &[Mcu]) -> Result<(), io::Error> {
fs::create_dir_all(path)?;
let mut module_names = Vec::new();
// Create modules for each mcu.
for mcu in mcus.iter() {
let module_nam... | fn insert_high_low_variants(registers: &mut HashMap<String, Register>) {
let wide_registers: Vec<_> = registers.values()
.filter(|r| r.size == 2)
.cloned()
.collect();
for r in wi... | let mut unique_registers = self::unique_registers(mcu);
insert_high_low_variants(&mut unique_registers);
let mut registers: Vec<Register> = unique_registers.into_iter().map(|a| a.1).collect();
registers.sort_by_key(|r| r.offset);
registers
}
| identifier_body |
build.rs | use std::io::prelude::*;
use std::io;
use std::path::Path;
pub fn all(path: &Path, mcus: &[Mcu]) -> Result<(), io::Error> {
fs::create_dir_all(path)?;
let mut module_names = Vec::new();
// Create modules for each mcu.
for mcu in mcus.iter() {
let module_nam... | (mcu: &Mcu, path: &Path) -> Result<(), io::Error> {
let mut file = File::create(path)?;
self::mcu_module_doc(mcu, &mut file)?;
writeln!(file)?;
self::mcu_module_code(mcu, &mut file)?;
Ok(())
}
/// Gets the module name for a mcu.
fn mcu_module_name(mcu: &Mcu) -> Str... | generate_mcu_module | identifier_name |
txtfunctions.py | = 'Hate This & I\'ll Love You'
elif entry == 'IBTY':
entry = 'I Belong To You'
elif entry == 'IS':
entry = 'The 2nd Law: Isolated System'
elif entry == 'KoC':
entry = 'Knights of Cydonia'
elif entry == 'MotP':
entry = 'Map of the Problematique'
elif entry == 'MM':
... | if length != 2:
print("Invalid replacement arguments")
return "ERROR: Invalid number of arguments."
else:
try:
setlist = filehandle.get_list('text/setlist')
except IOError:
raise IOError("Error getting setlist for insert_song")
insertSong ... | random_line_split | |
txtfunctions.py | = 'Hate This & I\'ll Love You'
elif entry == 'IBTY':
entry = 'I Belong To You'
elif entry == 'IS':
entry = 'The 2nd Law: Isolated System'
elif entry == 'KoC':
entry = 'Knights of Cydonia'
elif entry == 'MotP':
entry = 'Map of the Problematique'
elif entry == 'MM':
... | gigParse = gig.split('/')
if len(gigParse) > 1:
i = 1
gigFileName = gigParse[0]
while i < len(gigParse):
gigFileName = '%s-%s' % (gigFileName, gigParse[i])
i += 1
else:
gigFileName = gigParse[0]
except:
r... | setlist = filehandle.get_list('text/setlist')
gig = filehandle.get_list('text/gig')
tour = filehandle.get_list('text/tour')
print('GIG: %s' % (gig))
if len(gig) == 0:
print('SetPrevious Error: GIG not found')
outputString = 'ERROR: No gig set.'
return outputString
if len(se... | identifier_body |
txtfunctions.py | = 'Hate This & I\'ll Love You'
elif entry == 'IBTY':
entry = 'I Belong To You'
elif entry == 'IS':
entry = 'The 2nd Law: Isolated System'
elif entry == 'KoC':
entry = 'Knights of Cydonia'
elif entry == 'MotP':
entry = 'Map of the Problematique'
elif entry == 'MM':
... | (songlist):
setstring = ''
for song in songlist:
if setstring == '':
setstring = filehandle.remove_nr(song)
else:
setstring = "%s, %s" % (setstring, filehandle.remove_nr(song))
return setstring
# Prints any setlest fed into it and returns a string to be messaged
# ... | create_set_string | identifier_name |
txtfunctions.py | = 'Hate This & I\'ll Love You'
elif entry == 'IBTY':
entry = 'I Belong To You'
elif entry == 'IS':
entry = 'The 2nd Law: Isolated System'
elif entry == 'KoC':
entry = 'Knights of Cydonia'
elif entry == 'MotP':
entry = 'Map of the Problematique'
elif entry == 'MM':
... |
filehandle.put_list('text/archive.db', database)
sys.stdout.write('\t[DONE]\nTweeting setlist...')
twit.tweet_setlist()
sys.stdout.write('\t[DONE]\n')
outputString = "Current setlist copied over as previous set."
return outputString
# Takes 2 songs, finds the first song in the set, replaces... | if entry.startswith('c!'):
song = entry.split('!')[1].split('=')[0]
if song in [s.lower() for s in setlist]:
count = int(entry.split('!')[1].split('=')[1])
count = count + 1
database[database.index(entry)] = 'c!%s=%d' % (song, count)
elif e... | conditional_block |
xfer-localToFile.go | jptm IJobPartTransferMgr, p pipeline.Pipeline, pacer *pacer) {
// step 1: Get info from transfer.
info := jptm.Info()
u, _ := url.Parse(info.Destination)
fileURL := azfile.NewFileURL(*u, p)
fileSize := int64(info.SourceSize)
chunkSize := int64(info.BlockSize)
// If the given chunk Size for the Job is greate... | ocalToFile( | identifier_name | |
xfer-localToFile.go | )
chunkSize := int64(info.BlockSize)
// If the given chunk Size for the Job is greater than maximum file chunk size i.e 4 MB
// then chunk size will be 4 MB.
if chunkSize > common.DefaultAzureFileChunkSize {
chunkSize = common.DefaultAzureFileChunkSize
if jptm.ShouldLog(pipeline.LogWarning) {
jptm.Log(pipel... |
body := newRequestBodyPacer(bytes.NewReader(rangeBytes), pacer, srcMMF)
_, err := fileURL.UploadRange(jptm.Context(), startRange, body)
if err != nil {
if jptm.WasCanceled() {
if jpt |
if jptm.ShouldLog(pipeline.LogDebug) {
jptm.Log(pipeline.LogDebug,
fmt.Sprintf("Not uploading range from %d to %d, all bytes are zero", startRange, startRange+rangeSize))
}
rangeDone()
return
}
| conditional_block |
xfer-localToFile.go | File.Read(byteBuffer)
// Get http headers and meta data of file.
fileHTTPHeaders, metaData := jptm.FileDstData(byteBuffer)
// step 3: Create parent directories and file.
// 3a: Create the parent directories of the file. Note share must be existed, as the files are listed from share or directory.
err = createPare... |
return strings.FieldsFunc(str, func(c rune) bool {
return c == token
})
}
| identifier_body | |
xfer-localToFile.go | Size)
chunkSize := int64(info.BlockSize)
// If the given chunk Size for the Job is greater than maximum file chunk size i.e 4 MB
// then chunk size will be 4 MB.
if chunkSize > common.DefaultAzureFileChunkSize {
chunkSize = common.DefaultAzureFileChunkSize
if jptm.ShouldLog(pipeline.LogWarning) {
jptm.Log(p... | rangeDone()
} else {
// rangeBytes is the byte slice of Range for the given range.
rangeBytes := srcMMF.Slice()
allBytesZero := true
for index := 0; index < len(rangeBytes); index++ {
if rangeBytes[index] != 0 {
// If one byte is non 0, then we need to perform the PutRange.
allBytesZero ... | } | random_line_split |
event.go | ARD Code:%d", event.Code, event.Keyboard)
case DeviceMouse:
return fmt.Sprintf("Device: MOUSE Code:%d", event.Code, event.Mouse)
}
return "Device: Unkown"
}
// デバイスの種別を取り扱う列挙型です
type Device int32
// Device型の値
const (
DeviceUnkown Device = iota // 不明なデバイス
DeviceKeyboard // キーボード
DeviceMouse ... | KEYBO | identifier_name | |
event.go | // 不明なデバイス
DeviceKeyboard // キーボード
DeviceMouse // マウス
DeviceJoypad // ジョイパッド
)
// 動作の種類の列挙型です
type EventCode int32
// EventType型の値
const (
NoEvent EventCode = iota // 何もなかった場合
Unknown // 不明のイベント
MouseLeftDown ... | d", event.Code, event.Keyboard)
case DeviceMouse:
return fmt.Sprintf("Device: MOUSE Code:%d", event.Code, event.Mouse)
}
return "Device: Unkown"
}
// デバイスの種別を取り扱う列挙型です
type Device int32
// Device型の値
const (
DeviceUnkown Device = iota | identifier_body | |
event.go | numeric keypad))
K_APPLICATION = sdl.K_APPLICATION // "Application" (the Application / Compose / Context Menu (Windows) key)
K_POWER = sdl.K_POWER // "Power" (The USB document says this is a status flag, not a physical key - but some Mac keyboards do have a power key.)
K_KP_EQUALS = sdl... | K_LALT = sdl.K_LALT // "Left Alt" (alt, option) | random_line_split | |
sort.go | multiWayMerge *multiWayMerge
// spillAction save the Action for spill disk.
spillAction *chunk.SortAndSpillDiskAction
}
// Close implements the Executor Close interface.
func (e *SortExec) Close() error {
for _, container := range e.partitionList {
err := container.Close()
if err != nil {
return err
}
}
... | partitionList []*chunk.SortedRowContainer
// multiWayMerge uses multi-way merge for spill disk.
// The multi-way merge algorithm can refer to https://en.wikipedia.org/wiki/K-way_merge_algorithm | random_line_split | |
sort.go | unk) (err error) {
if e.multiWayMerge == nil {
e.multiWayMerge = &multiWayMerge{e.lessRow, e.compressRow, make([]partitionPointer, 0, len(e.partitionList))}
for i := 0; i < len(e.partitionList); i++ {
row, err := e.partitionList[i].GetSortedRow(0)
if err != nil {
return err
}
e.multiWayMerge.elemen... | keyColumnsLess | identifier_name | |
sort.go | Exec) initCompareFuncs() {
e.keyCmpFuncs = make([]chunk.CompareFunc, len(e.ByItems))
for i := range e.ByItems {
keyType := e.ByItems[i].Expr.GetType()
e.keyCmpFuncs[i] = chunk.GetCompareFunc(keyType)
}
}
func (e *SortExec) buildKeyColumns() {
e.keyColumns = make([]int, 0, len(e.ByItems))
for _, by := range e.... | {
err = e.doCompaction()
if err != nil {
return err
}
} | conditional_block | |
sort.go | return e.Children(0).Close()
}
// Open implements the Executor Open interface.
func (e *SortExec) Open(ctx context.Context) error {
e.fetched = false
e.Idx = 0
// To avoid duplicated initialization for TopNExec.
if e.memTracker == nil {
e.memTracker = memory.NewTracker(e.ID(), -1)
e.memTracker.AttachTo(e.Ct... | {
for _, container := range e.partitionList {
err := container.Close()
if err != nil {
return err
}
}
e.partitionList = e.partitionList[:0]
if e.rowChunks != nil {
e.memTracker.Consume(-e.rowChunks.GetMemTracker().BytesConsumed())
e.rowChunks = nil
}
e.memTracker = nil
e.diskTracker = nil
e.multiW... | identifier_body | |
eth_pubsub.rs | RichHeader, Log};
use sync::{SyncState, Notification};
use client_traits::{BlockChainClient, ChainNotify};
use ethereum_types::H256;
use light::cache::Cache;
use light::client::{LightChainClient, LightChainNotify};
use light::on_demand::OnDemandRequester;
use parity_runtime::Executor;
use parking_lot::{RwLock, Mutex}... | logs(filter, ex).into_future()
})
.collect::<Vec<_>>()
);
let limit = filter.limit;
let executor = self.executor.clone();
let subscriber = subscriber.clone();
self.executor.spawn(logs
.map(move |logs| {
let logs = logs.into_iter().flat_map(|log| log).collect();
for log in limi... | .map(|&(hash, ref ex)| {
let mut filter = filter.clone();
filter.from_block = BlockId::Hash(hash);
filter.to_block = filter.from_block; | random_line_split |
eth_pubsub.rs | RichHeader, Log};
use sync::{SyncState, Notification};
use client_traits::{BlockChainClient, ChainNotify};
use ethereum_types::H256;
use light::cache::Cache;
use light::client::{LightChainClient, LightChainNotify};
use light::on_demand::OnDemandRequester;
use parity_runtime::Executor;
use parking_lot::{RwLock, Mutex}... |
Err(())
})
)
}
}
impl<C> EthPubSubClient<C>
where
C: 'static + Send + Sync {
/// Creates new `EthPubSubClient`.
pub fn new(client: Arc<C>, executor: Executor, pool_receiver: mpsc::UnboundedReceiver<Arc<Vec<H256>>>) -> Self {
let heads_subscribers = Arc::new(RwLock::new(Subscribers::default()));
le... | {
if let Some(handler) = weak_handler.upgrade() {
handler.notify_syncing(status);
return Ok(())
}
} | conditional_block |
eth_pubsub.rs | RichHeader, Log};
use sync::{SyncState, Notification};
use client_traits::{BlockChainClient, ChainNotify};
use ethereum_types::H256;
use light::cache::Cache;
use light::client::{LightChainClient, LightChainNotify};
use light::on_demand::OnDemandRequester;
use parity_runtime::Executor;
use parking_lot::{RwLock, Mutex}... | (&self, id: BlockId) -> Option<encoded::Header> {
self.client.block_header(id)
}
fn logs(&self, filter: EthFilter) -> BoxFuture<Vec<Log>> {
Box::new(LightFetch::logs(self, filter)) as BoxFuture<_>
}
}
impl<C: LightClient> LightChainNotify for ChainNotificationHandler<C> {
fn new_headers(&self, enacted: &[H256... | block_header | identifier_name |
eth_pubsub.rs | RichHeader, Log};
use sync::{SyncState, Notification};
use client_traits::{BlockChainClient, ChainNotify};
use ethereum_types::H256;
use light::cache::Cache;
use light::client::{LightChainClient, LightChainNotify};
use light::on_demand::OnDemandRequester;
use parity_runtime::Executor;
use parking_lot::{RwLock, Mutex}... | Self::notify(&executor, &subscriber, pubsub::Result::Log(Box::new(log)))
}
})
.map_err(|e| warn!("Unable to fetch latest logs: {:?}", e))
);
}
}
/// Notify all subscribers about new transaction hashes.
fn notify_new_transactions(&self, hashes: &[H256]) {
for subscriber in self.transaction... | {
for &(ref subscriber, ref filter) in self.logs_subscribers.read().values() {
let logs = futures::future::join_all(enacted
.iter()
.map(|&(hash, ref ex)| {
let mut filter = filter.clone();
filter.from_block = BlockId::Hash(hash);
filter.to_block = filter.from_block;
logs(filter, ex).in... | identifier_body |
ext_modules.py | language governing permissions and
# limitations under the License.
import errno
import glob
import os
import shutil
import sys
from setuptools import Extension
class BadAutoconfSubstitutes(ValueError):
pass
def _get_ac_subst_bool(true_subst, false_subst):
"""
This function accepts arguments which ... |
return system
def _cond_extra_object(true_subst, false_subst, bundled, system):
return cond_multiple_extra_objects(true_subst, false_subst,
[bundled], [system])
def _create_module(module_name):
abs_top_srcdir = '/home/hanshenriksande/Master/mesos/build/..'
abs_top_b... | for obj in bundled:
if not os.path.exists(obj):
raise RuntimeError("{} does not exist.".format(obj))
return bundled | conditional_block |
ext_modules.py | language governing permissions and
# limitations under the License.
import errno
import glob
import os
import shutil
import sys
from setuptools import Extension
class BadAutoconfSubstitutes(ValueError):
pass
def _get_ac_subst_bool(true_subst, false_subst):
| BadAutoconfSubstitutes: ...
Inside workings - what is really going on in this example
after running the configure script:
>>> __get_ac_subst_bool('', '#')
>>> True
>>> __get_ac_subst_bool('#', '')
>>> False
>>> __get_ac_subst_bool(... | """
This function accepts arguments which are supposedly a result
of substitution by the code in the configure script that
was generated for a boolean flag.
It either returns the value of this flag, or fails if the
combination of these "substitution results" is not valid.
... | identifier_body |
ext_modules.py | language governing permissions and
# limitations under the License.
import errno
import glob
import os
import shutil
import sys
from setuptools import Extension
class BadAutoconfSubstitutes(ValueError):
pass
def _get_ac_subst_bool(true_subst, false_subst):
"""
This function accepts arguments which ... | "#",
os.path.join(abs_top_builddir, libev, '.libs', 'libev.a'),
'-lev'
)
else:
libevent_dir = os.path.join('3rdparty', 'libevent-2.0.22-stable')
libevent_dir = os.path.join(abs_top_builddir, libevent_dir, '.libs')
libevent_bundled = [
... | libev = os.path.join('3rdparty', 'libev-4.22')
EXTRA_OBJECTS += _cond_extra_object(
"", | random_line_split |
ext_modules.py | language governing permissions and
# limitations under the License.
import errno
import glob
import os
import shutil
import sys
from setuptools import Extension
class BadAutoconfSubstitutes(ValueError):
pass
def _get_ac_subst_bool(true_subst, false_subst):
"""
This function accepts arguments which ... | (module_name):
abs_top_srcdir = '/home/hanshenriksande/Master/mesos/build/..'
abs_top_builddir = '/home/hanshenriksande/Master/mesos/build'
ext_src_dir = os.path.join(
'src', 'python', module_name, 'src', 'mesos', module_name)
ext_common_dir = os.path.join(
'src', 'python', 'native_comm... | _create_module | identifier_name |
time_client.rs | }: {:?}",
unique_id,
packet
);
out.reserve(packet.encoded_len());
packet
.encode(out)
.expect("Error encoding packet for time request");
}
///Send a time request
///
///Resolve `peer_config.host` using `resolver`. Take keys and cookies
/// from `secret_store`. If they aren'... | toNakData {
| identifier_name | |
time_client.rs | map_err(RequestError::CoreDepartureError)?;
debug!("Sending time request to peer '{}'", peer_name);
socket
.send_to(send_buf.as_slice(), &peer_addr)
.await
.map_err(RequestError::UdpSocketError)?;
Ok(())
}
///Enumeration of errors that can occur when processing a time response
#[d... | let plaintext = aead_s2c
.decrypt( | random_line_split | |
time_client.rs | match self {
DestTimeError(e) => write!(f, "Getting destination timestamp: {}", e),
PacketDecodingError(e) => write!(f, "Decoding packet: {}", e),
NotAResponse => write!(f, "Not a response packet"),
AdDecodingError(e) => write!(f, "Decoding associated data: {}", e),
... | let mut recv_buf = [0; 65535];
loop {
let (recv_size, peer_addr) = socket.recv_from(&mut recv_buf).await?;
if let Err(e) = handle_time_response(&recv_buf[0..recv_size], core_state, secret_store) {
log!(
e.level(),
"Handling time response from {}: {}",
... | identifier_body | |
fst_builder.rs | inited: false,
}
}
// this should be call after new FstBuilder
pub fn init(&mut self) {
if self.do_share_suffix {
let reader = self.fst.bytes_store.get_reverse_reader();
let dedup_hash = NodeHash::new(&mut self.fst, reader);
self.dedup_hash =... | {
let no_output = outputs.empty();
let fst = FST::new(input_type, outputs, bytes_page_bits as usize);
FstBuilder {
dedup_hash: None,
fst,
no_output,
min_suffix_count1,
min_suffix_count2,
do_share_non_singleton_nodes,
... | identifier_body | |
fst_builder.rs | next_final_output,
is_final,
);
} else {
// replaceLast just to install
// next_final_output/is_final onto the arc
parent.replace_last(
self.last_input.... | fst | identifier_name | |
fst_builder.rs | Outputs`) then you cannot reuse across
/// calls.
pub fn add(&mut self, input: IntsRef, output: F::Value) -> Result<()> {
debug_assert!(self.inited);
assert!(self.last_input.length == 0 || input > self.last_input.get());
let mut output = output;
if self.frontier.len() < input.le... | {
return Ok(false);
} | conditional_block | |
fst_builder.rs | == 1 && parent.input_count == 1 && idx > 1)
{
// my parent, about to be compiled, doesn't make the cut, so
// I'm definitely pruned
// if minSuffixCount2 is 1, we keep only up
// until the 'distinguished edge', ie we keep ... | self.compile_node(0, tail_len)?
};
self.fst.finish(node)?; | random_line_split | |
furnace.rs | use web_sys::CanvasRenderingContext2d;
const FUEL_CAPACITY: usize = 10;
/// A list of fixed recipes, because dynamic get_recipes() can only return a Vec.
static RECIPES: Lazy<[Recipe; 2]> = Lazy::new(|| {
[
Recipe::new(
hash_map!(ItemType::IronOre => 1usize),
hash_map!(ItemType::Ir... | use wasm_bindgen::prelude::*; | random_line_split | |
furnace.rs | (position: &Position) -> Self {
Furnace {
position: *position,
input_inventory: Inventory::new(),
output_inventory: Inventory::new(),
progress: None,
power: 20.,
max_power: 20.,
recipe: None,
}
}
}
impl Structure fo... | {
&mut self.output_inventory
} | conditional_block | |
furnace.rs | usize),
20.,
50.,
),
]
});
#[derive(Serialize, Deserialize)]
pub(crate) struct Furnace {
position: Position,
input_inventory: Inventory,
output_inventory: Inventory,
progress: Option<f64>,
power: f64,
max_power: f64,
recipe: Option<Recipe>,
}
impl Furnac... | {
if self.output_inventory.remove_item(item_type) {
Ok(())
} else {
Err(())
}
} | identifier_body | |
furnace.rs | ,
progress: Option<f64>,
power: f64,
max_power: f64,
recipe: Option<Recipe>,
}
impl Furnace {
pub(crate) fn new(position: &Position) -> Self {
Furnace {
position: *position,
input_inventory: Inventory::new(),
output_inventory: Inventory::new(),
... | inventory_mut | identifier_name | |
config.go | ruconfig `json:"lru_config"`
Rebalance rebalanceconf `json:"rebalance_conf"`
Cksum cksumconfig `json:"cksum_config"`
Ver versionconfig `json:"version_config"`
FSpaths map[string]string `json:"fspaths"`
TestFSP testfspathconf `json:"test_fspaths"`
Net ... |
// StartupDelayTimeStr string `json:"startup_delay_time"`
// StartupDelayTime time.Duration `json:"-"` // omitempty
func validateconf() (err error) {
// durations
if ctx.config.Periodic.StatsTime, err = time.ParseDuration(ctx.config.Periodic.StatsTimeStr); err != nil {
return fmt.Errorf("Bad stats-time ... | {
versions := []string{VersionAll, VersionCloud, VersionLocal, VersionNone}
versionValid := false
for _, v := range versions {
if v == version {
versionValid = true
break
}
}
if !versionValid {
return fmt.Errorf("Invalid version: %s - expecting one of %s", version, strings.Join(versions, ", "))
}
ret... | identifier_body |
config.go | ruconfig `json:"lru_config"`
Rebalance rebalanceconf `json:"rebalance_conf"`
Cksum cksumconfig `json:"cksum_config"`
Ver versionconfig `json:"version_config"`
FSpaths map[string]string `json:"fspaths"`
TestFSP testfspathconf `json:"test_fspaths"`
Net ... |
}
func validateVersion(version string) error {
versions := []string{VersionAll, VersionCloud, VersionLocal, VersionNone}
versionValid := false
for _, v := range versions {
if v == version {
versionValid = true
break
}
}
if !versionValid {
return fmt.Errorf("Invalid version: %s - expecting one of %s",... | {
glog.Errorf("Failed to json-unmarshal config %q, err: %v", fpath, err)
os.Exit(1)
} | conditional_block |
config.go | `json:"proto"` // tcp, udp
Port string `json:"port"` // listening port
}
type httpcnf struct {
MaxNumTargets int `json:"max_num_targets"` // estimated max num targets (to count idle conns)
UseHTTPS bool `json:"use_https"` // use HTTPS instead of HTTP
Certificate string `json:"server_cert... | setloglevel | identifier_name | |
config.go | "github.com/golang/glog"
)
const (
KiB = 1024
MiB = 1024 * KiB
GiB = 1024 * MiB
)
// checksums: xattr, http header, and config
const (
xattrXXHashVal = "user.obj.dfchash"
xattrObjVersion = "user.obj.version"
ChecksumNone = "none"
ChecksumXXHash = "xxhash"
ChecksumMD5 = "md5"
VersionAll = "all"
Ve... | "os"
"strings"
"time"
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.