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 |
|---|---|---|---|---|
modes.go | /*
Copyright 2021 Sonobuoy Contributors
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 writing, so... | }
func genLiteSkips() string {
quoted := make([]string, len(liteSkips))
for i, v := range liteSkips {
quoted[i] = regexp.QuoteMeta(v)
// Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue.
quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".")
}
return strings.Join(q... | }, | random_line_split |
parser.py | #--------------------------------------------------------------------------------------------------#
# hsd-python: package for manipulating HSD-formatted data in Python #
# Copyright (C) 2011 - 2023 DFTB+ developers group #
# Licensed under... | (self, text):
stripped = text.strip()
if stripped:
if self._has_child:
self._error(SYNTAX_ERROR, (self._currline, self._currline))
self._eventhandler.add_text(stripped)
self._has_text = True
def _starttag(self, tagname, closeprev):
txt = ... | _text | identifier_name |
parser.py | #--------------------------------------------------------------------------------------------------#
# hsd-python: package for manipulating HSD-formatted data in Python #
# Copyright (C) 2011 - 2023 DFTB+ developers group #
# Licensed under... |
else:
self._error(SYNTAX_ERROR, (self._currline, self._currline))
line = after
def _text(self, text):
stripped = text.strip()
if stripped:
if self._has_child:
self._error(SYNTAX_ERROR, (self._currline, self._currline))
... | txtinc = after.startswith("<<")
hsdinc = after.startswith("<+")
if txtinc:
self._text("".join(self._buffer) + before)
self._buffer = []
self._eventhandler.add_text(self._include_txt(after[2:]))
break
... | conditional_block |
parser.py | #--------------------------------------------------------------------------------------------------#
# hsd-python: package for manipulating HSD-formatted data in Python #
# Copyright (C) 2011 - 2023 DFTB+ developers group #
# Licensed under... |
@staticmethod
def _include_txt(fname):
fname = common.unquote(fname.strip())
with open(fname, "r") as fp:
txt = fp.read()
return txt
def _error(self, errorcode, lines):
error_msg = (
"Parsing error ({}) between lines {} - {} in file '{}'.".format(... | fname = common.unquote(fname.strip())
parser = HsdParser(eventhandler=self._eventhandler)
parser.parse(fname) | identifier_body |
parser.py | #--------------------------------------------------------------------------------------------------#
# hsd-python: package for manipulating HSD-formatted data in Python #
# Copyright (C) 2011 - 2023 DFTB+ developers group #
# Licensed under... |
def __init__(self, eventhandler: Optional[HsdEventHandler] = None):
"""Initializes the parser.
Args:
eventhandler: Instance of the HsdEventHandler class or its children.
"""
if eventhandler is None:
self._eventhandler = HsdEventPrinter()
else:
... | {'Temperature': 100, 'Temperature.attrib': 'Kelvin'}}}}}
""" | random_line_split |
main.py | import gym
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch.nn.utils import clip_grad_norm_
from collections import deque
env_name = "CartPole-v0"
env = gy... | state2_batch = torch.cat(next_state_batch)
actions_batch = torch.cat(action_batch)
forward_pred_err, inverse_pred_err = ICM(state1_batch, actions_batch, state2_batch)
rewards = ((1. / ETA) * forward_pred_err).detach()
intrinsic_rewards.append(rewards.mean().numpy())
if EXTRINSIC_REWARD == True:... |
# Intrinsic Curiosity Calculation
state1_batch = torch.cat(state_batch) | random_line_split |
main.py | import gym
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch.nn.utils import clip_grad_norm_
from collections import deque
env_name = "CartPole-v0"
env = gy... | (state1, action, state2, forward_scale=1., inverse_scale=1e4):
"""
"""
state1_hat = encoder(state1)
state2_hat = encoder(state2)
state2_hat_pred = forwardM(state1_hat.detach(), action.detach())
forward_pred_err = forward_scale * forward_loss(state2_hat_pred, state2_hat.detach()).sum(dim=1).unsqueeze(dim=1... | ICM | identifier_name |
main.py | import gym
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch.nn.utils import clip_grad_norm_
from collections import deque
env_name = "CartPole-v0"
env = gy... |
return np.array(c_loss_batch).mean(), np.array(a_loss_batch).mean(), np.array(icm_loss_batch)
torch.manual_seed(42)
torch.cuda.manual_seed(42)
np.random.seed(42)
env.seed(42)
input_shape = env.observation_space.shape[0]
output_shape = env.action_space.n
actor = Actor(input_shape, output_shape).to(device)
crit... | for states_i, old_actions, old_logprobs, advantage_i, discounted_reward_i, cur_loss in ppo_iter(mini_batch_size, states, actions, log_probs, advantage, discounted_rewards, curiosity_loss):
optimizer.zero_grad()
#c_optimizer.zero_grad()
#tran critic
new_value = critic(states_i.to(device))
... | conditional_block |
main.py | import gym
import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch.nn.utils import clip_grad_norm_
from collections import deque
env_name = "CartPole-v0"
env = gy... |
def ICM(state1, action, state2, forward_scale=1., inverse_scale=1e4):
"""
"""
state1_hat = encoder(state1)
state2_hat = encoder(state2)
state2_hat_pred = forwardM(state1_hat.detach(), action.detach())
forward_pred_err = forward_scale * forward_loss(state2_hat_pred, state2_hat.detach()).sum(dim=1).unsqu... | """
Gets as inputs the aciton taken from the policy and the encoded state by the encoder in the inverse model.
The froward model trys to predict the encoded next state.
Returns the predicted encoded next state.
Gets optimized by the MSE between the actual encoded next state and the predi... | identifier_body |
TimeSlotGroup.js | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import cn from 'classnames'
import TimeSlot from './TimeSlot'
import date from './utils/dates.js'
import localizer from './header/localizer'
import { elementType, dateFormat } from './utils/propTypes'
import EventSlot from './EventSlot';
impor... | const { connectDropTarget, hovered, item} = this.props;
const backgroundColor= hovered ? '#e8f8fc ' : 'white';
const {intervals, value, freeTrainers, isAdmin} = this.props;
let valuetM = value.getTime();
const flag = Array.isArray(intervals) ? intervals.some(el => {
if(Array.isArray... | identifier_body | |
TimeSlotGroup.js | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import cn from 'classnames'
import TimeSlot from './TimeSlot'
import date from './utils/dates.js'
import localizer from './header/localizer'
import { elementType, dateFormat } from './utils/propTypes'
import EventSlot from './EventSlot';
impor... | (props) {
props.transferTraining(props.value); // drag and drop
console.log('DROP props :', props);
//moveKnight(props.x, props.y);
},
// hover(props, monitor, component) {
// // This is fired very often and lets you perform side effects
// // in response to the hover. You can't handle enter an... | drop | identifier_name |
TimeSlotGroup.js | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import cn from 'classnames'
import TimeSlot from './TimeSlot'
import date from './utils/dates.js'
import localizer from './header/localizer'
import { elementType, dateFormat } from './utils/propTypes'
import EventSlot from './EventSlot';
impor... | return connectDropTarget(
<div className={cellClass} style={{backgroundColor}} onClick={(e) => modalTransferEvent(value.getTime())}>
{this.renderSlices()}
{currentEvent}
</div>
)
}
return (
<div className={cellClass} style={{backgroundColor}} onClick={(e... |
if(flag && !isViewTrainer && !currentEvent){ | random_line_split |
semaphore.rs | use std::{fmt, mem};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::Ordering::{Relaxed, Acquire};
use crate::state::ReleaseState::Unlocked;
use crate::state::AcquireState::{Available, Queued};
use std::fmt::{Debug, Formatter};
use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt... |
}
}
}
}
/// Like [acquire](#method.acquire), but takes an [`Arc`] `<Semaphore>` and returns a guard that is `'static`, [`Send`] and [`Sync`].
/// # Examples
/// ```
/// # use async_weighted_semaphore::{Semaphore, PoisonError, SemaphoreGuardArc};
/// # use st... | {
return Ok(SemaphoreGuard::new(self, amount));
} | conditional_block |
semaphore.rs | use std::{fmt, mem};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::Ordering::{Relaxed, Acquire};
use crate::state::ReleaseState::Unlocked;
use crate::state::AcquireState::{Available, Queued};
use std::fmt::{Debug, Formatter};
use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt... | (&self, amount: usize) -> Result<SemaphoreGuard, TryAcquireError> {
let mut current = self.acquire.load(Acquire);
loop {
match current {
Queued(_) => return Err(TryAcquireError::WouldBlock),
Available(available) => {
let available = availab... | try_acquire | identifier_name |
semaphore.rs | use std::{fmt, mem};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::Ordering::{Relaxed, Acquire};
use crate::state::ReleaseState::Unlocked;
use crate::state::AcquireState::{Available, Queued};
use std::fmt::{Debug, Formatter};
use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt... |
}
impl Semaphore {
/// The maximum number of permits that can be made available. This is slightly smaller than
/// [`usize::MAX`]. If the number of available permits exceeds this number, it may poison the
/// semaphore.
/// # Examples
/// ```
/// # use async_weighted_semaphore::{Semaphore, Se... | {
match self.acquire.load(Relaxed) {
Available(available) => write!(f, "Semaphore::Ready({:?})", available)?,
Queued(_) => match self.release.load(Relaxed) {
Unlocked(available) => write!(f, "Semaphore::Blocked({:?})", available)?,
_ => write!(f, "Semaphor... | identifier_body |
semaphore.rs | use std::{fmt, mem};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::Ordering::{Relaxed, Acquire};
use crate::state::ReleaseState::Unlocked;
use crate::state::AcquireState::{Available, Queued};
use std::fmt::{Debug, Formatter};
use crate::state::{AcquireStep, Waiter, Permits, AcquireState, ReleaseSt... | pub fn acquire_arc(self: &Arc<Self>, amount: usize) -> AcquireFutureArc {
AcquireFutureArc {
arc: self.clone(),
inner: unsafe { mem::transmute::<AcquireFuture, AcquireFuture>(self.acquire(amount)) },
}
}
/// Like [try_acquire](#method.try_acquire), but takes an [`Ar... | /// ``` | random_line_split |
14.rs | // --- Day 14: Disk Defragmentation ---
// Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt... | (size: u32, occupied: &Vec<Vec<bool>>) {
for row in occupied.iter().take(size as usize) {
println!("\n{}", row.iter().take(size as usize).map(|c| match c {
&true => "#",
&false => ".",
})
.collect::<Vec<&str>>()
.join(" "));
}
}
/*
This algo... | print_small_grid | identifier_name |
14.rs | // --- Day 14: Disk Defragmentation ---
// Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt... |
}
else {
clusters.set_empty(Loc(i, j))
}
}
}
// clusters.print_small(10);
clusters.index.keys().len() as u32
}
fn part_two() {
let grid = make_grid("jxqlasbh");
let count = count_clusters(&grid);
println!("14-2: {} clust... | {
clusters.new_cluster(Loc(i, j));
} | conditional_block |
14.rs | // --- Day 14: Disk Defragmentation ---
// Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt... |
fn bitcount_hash(hash: &str) -> u32 {
let mut bitsum = 0;
for j in 0..32 {
let slice = &hash[j..j+1];
let num = u32::from_str_radix(slice, 16).unwrap();
bitsum += num.count_ones();
}
bitsum
}
fn count_hash_seed(s: &str) -> u32 {
let mut bitsum = 0;
for ha... | {
(0..128)
.map(|i| format!("{}-{}", seed, i))
.map(|plaintext| {
let mut knot = Knot::new();
knot.hash(Cursor::new(plaintext))
})
.collect()
} | identifier_body |
14.rs | // --- Day 14: Disk Defragmentation ---
// Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only opt... | }
fn new_cluster(&mut self, loc: Loc) {
let id = self.next_id;
self.next_id += 1;
self.add_to_cluster(loc, id);
}
fn add_to_cluster(&mut self, loc: Loc, id: ClusterId) {
self.add_grid(&loc, id);
match self.index.entry(id) {
Occupied(mut e) => ... | random_line_split | |
tsne2.js | // create main global object
const tsnejs = window.tsnejs || { REVISION: 'ALPHA' };
function assert(condition, message) {
if (!condition) { throw message || 'Assertion failed'; }
}
// utilitity that creates contiguous vector of zeros of size n
function zeros(n) {
if (typeof (n) === 'undefined' || isNaN(n)) { return... | / perform gradient step
const ymean = zeros(this.dim);
for (let i = 0; i < N; i++) {
for (let d = 0; d < this.dim; d++) {
const gid = grad[i][d];
const sid = this.ystep[i][d];
const gainid = this.gains[i][d];
// compute gain update
let newgain = sign(gid) === sign(sid) ? gainid * 0.8... | t solution
getSolution() {
return this.solution;
},
// perform a single step of optimization to improve the embedding
step() {
this.iter += 1;
const N = this.N;
const cg = this.costAndGradient(this.solution); // evaluate gradient
const cost = cg.cost;
const grad = cg.grad;
/ | identifier_body |
tsne2.js | // create main global object
const tsnejs = window.tsnejs || { REVISION: 'ALPHA' };
function assert(condition, message) {
if (!condition) { throw message || 'Assertion failed'; }
}
// utilitity that creates contiguous vector of zeros of size n
function zeros(n) {
if (typeof (n) === 'undefined' || isNaN(n)) { return... | (X) {
const N = X.length;
const dist = zeros(N * N); // allocate contiguous array
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
const d = computeVectorDistance(X[i], X[j]);
dist[(i * N) + j] = d;
dist[(j * N) + i] = d;
}
}
return dist;
}
// helper function
function sign(x) {
if (x ... | pairwiseDistances | identifier_name |
tsne2.js | // create main global object |
// utilitity that creates contiguous vector of zeros of size n
function zeros(n) {
if (typeof (n) === 'undefined' || isNaN(n)) { return []; }
if (typeof ArrayBuffer === 'undefined') {
// lacking browser support
const arr = new Array(n);
for (let i = 0; i < n; i++) { arr[i] = 0; }
return arr;
}
return new F... | const tsnejs = window.tsnejs || { REVISION: 'ALPHA' };
function assert(condition, message) {
if (!condition) { throw message || 'Assertion failed'; }
} | random_line_split |
tsne2.js | // create main global object
const tsnejs = window.tsnejs || { REVISION: 'ALPHA' };
function assert(condition, message) {
if (!condition) |
}
// utilitity that creates contiguous vector of zeros of size n
function zeros(n) {
if (typeof (n) === 'undefined' || isNaN(n)) { return []; }
if (typeof ArrayBuffer === 'undefined') {
// lacking browser support
const arr = new Array(n);
for (let i = 0; i < n; i++) { arr[i] = 0; }
return arr;
}
return ne... | { throw message || 'Assertion failed'; } | conditional_block |
fiUnam.py | # -*- coding: utf-8 -*-
import mmap
import os # para conocer los metadatos de archivos a ingresar con la fx cpin()
import math
import os.path, time
class SuperBlock :
"""
El superbloque para este sistema de archivos ocupa el primer cluster
del mismo, es decir, ocupa 2048
"""
f = open('fiuna... | def date_format(self,date):
months={'01':'Jan','02':'Feb','03':'March','04':'Apr','05':'May',
'06':'Jun','07':'Jul','08':'Aug','09':'Sept','10':'Oct','11':'Nov','12':'Dec'}
a=date[0:4]
m=months.get(date[4:6])
d=date[6:8]
hh=date[8:10]
mm=date[10:12]
... | = self.sb.size_cluster + self.sb.size_dentry*i.numdir
self.fs_map[prtb:prtb + i.offset_fname] = bytes(self.dentry_notused).encode('utf-8')
| conditional_block |
fiUnam.py | # -*- coding: utf-8 -*-
import mmap
import os # para conocer los metadatos de archivos a ingresar con la fx cpin()
import math
import os.path, time
class | :
"""
El superbloque para este sistema de archivos ocupa el primer cluster
del mismo, es decir, ocupa 2048
"""
f = open('fiunamfs.img','r+b')
fs_map = mmap.mmap(f.fileno(),0,access=mmap.ACCESS_READ)
# Información de superbloque
name = fs_map[0:8].decode('utf-8') ... | SuperBlock | identifier_name |
fiUnam.py | # -*- coding: utf-8 -*-
import mmap
import os # para conocer los metadatos de archivos a ingresar con la fx cpin()
import math
import os.path, time
class SuperBlock :
"""
El superbloque para este sistema de archivos ocupa el primer cluster
del mismo, es decir, ocupa 2048
"""
f = open('fiuna... | def defrag(self):
inodes=self.inodes()
if(len(inodes)!=0):
if inodes[0].finit_cluster != 5:
self.cpint(inodes[0],5)
self.over(inodes[0],5)
inodes[0].finit_cluster=5
for j in range(0,len(inodes)-1):
i_lastcluster... | s.path.isfile(fe):
if len(fe)<15:
if self.search(fe)!=None:
print('Ya existe un archivo con el mismo nombre, renombrar')
else:
self.cp(fe)
else:
print("cpin: " + fe + ": file name too large")
else:
... | identifier_body |
fiUnam.py | # -*- coding: utf-8 -*-
import mmap
import os # para conocer los metadatos de archivos a ingresar con la fx cpin()
import math
import os.path, time
class SuperBlock :
"""
El superbloque para este sistema de archivos ocupa el primer cluster
del mismo, es decir, ocupa 2048
"""
f = open('fiuna... | numdir_cluster = int(fs_map[47:49].decode('utf-8')) # 04
total_cluster = int(fs_map[52:60].decode('utf-8')) # 00000720
size_dentry = 64 # size dir entry
f.close()
fs_map.close()
class DIRENTRY :
"""
De hecho, estrictamente esta clase no es un i... | random_line_split | |
boilerplate.py | #-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... |
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += ... | current_win = self.__win_dict.get(metric_name, None)
train_values = self.__metrics['train'][metric_name]
val_values = self.__metrics['val'][metric_name]
epochs = max(len(train_values), len(val_values))
values_for_plot = np.column_stack((np.array(train_values), np.array(val_values)))
... | identifier_body |
boilerplate.py | #-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... | end = time.time()
logger.info('Test: [{0}/{0}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.avg:.5f}\t'
'F2: {f2s.avg}\t'.format(
len(val_loader), batch_time=batch_time, loss=losses, f2s=f2s))
return losses.avg
def get_outputs(loader, m... | batch_time.update(time.time() - end) | random_line_split |
boilerplate.py | #-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... |
logger.info('early_stop_counter: %d', self.__early_stop_counter)
if (self.warm_up_epochs and self.__descrease_times == 0 and self.__warm_up and epoch >= self.warm_up_epochs - 1 ) or \
(self.__lr_changed <= epoch - self.patience and \
(self.__early_stop_counter is not No... | logger.info('Early stopping, regress for %d iterations', self.__early_stop_counter)
to_break = True | conditional_block |
boilerplate.py | #-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... | (self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def adjust_learning_rate_by_sche... | __init__ | identifier_name |
hangman.py | # Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
WORDLIST_FILENAME = "Assignment2\words.txt"
def loadWords():
"""
Returns a list of ... | lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
count = 0 #Count method takes a single agument, element whose count is to be found. Starting a 0 letters, ... | '''
secretWord: string, the word the user is guessing | random_line_split |
hangman.py | # Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
WORDLIST_FILENAME = "Assignment2\words.txt"
def loadWords():
"""
Returns a list of ... |
return removeduplicate(lettersGuessed, alphabet2) #This will sshow what letters are available.
#Alphabet2 becomes L2. So the letter starts off from the alphabet and as each letter is guessed, it is removed from
#the list and then all the letters left are displayed.
# Hint: You might consider usin... | L1Start = L1[:]# Have to make sure to make a copy of the first list, to be able to modify the second.
for e in L1:#For an element, or letter in the first argument.
if e in L1Start:#If the leter in LIStart is there, which also implies it is in the first argument
L2.remove(e) #then the... | identifier_body |
hangman.py | # Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
WORDLIST_FILENAME = "Assignment2\words.txt"
def loadWords():
"""
Returns a list of ... |
else:
lettersGuessed.append(guess) #You would add the guessed letter into the guess [].
print(('Good guess: ') + getGuessedWord(secretWord, lettersGuessed))
print(('------------'))
else: #If the guess is not in the secretWord it would move to the nex... | print(("Oops! You've already guessed that letter: ") + getGuessedWord(secretWord, lettersGuessed))
print(('------------')) | conditional_block |
hangman.py | # Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
WORDLIST_FILENAME = "Assignment2\words.txt"
def | ():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = ... | loadWords | identifier_name |
mn-map.component.ts | /// <reference path="../../../typings/index.d.ts" />
import { ViewChild, ContentChildren,OnInit, Inject, forwardRef, Component,Directive, AfterViewInit, Input, Output, EventEmitter, QueryList, ElementRef } from '@angular/core';
import { Http, Response } from '@angular/http';
import { BackendManagerService } from '../... |
getLayer():Promise<L.Layer>{
return new Promise<L.Layer>((resolve, react) =>{
this.bms.setPaging(false).setActiveApp("spaces/"+this.mappingSpace+"/styles").getAll().then(s=>{
this.styles = s;
for(let style of this.styles){
this.int_styles[style.slug] = style;
}
co... | super();
}
| identifier_body |
mn-map.component.ts | /// <reference path="../../../typings/index.d.ts" />
import { ViewChild, ContentChildren,OnInit, Inject, forwardRef, Component,Directive, AfterViewInit, Input, Output, EventEmitter, QueryList, ElementRef } from '@angular/core';
import { Http, Response } from '@angular/http';
import { BackendManagerService } from '../... | export abstract class LeafLayerBase implements LeafLayer{
abstract getLayer():L.Layer|Promise<L.Layer>;
abstract isBase():boolean;
protected name:string;
getName():string{
return this.name;
}
addToMap(m, bls, dls){
let l = this.getLayer();
m.addLayer(l);
if(this.isBase())
bls[this.get... | random_line_split | |
mn-map.component.ts | /// <reference path="../../../typings/index.d.ts" />
import { ViewChild, ContentChildren,OnInit, Inject, forwardRef, Component,Directive, AfterViewInit, Input, Output, EventEmitter, QueryList, ElementRef } from '@angular/core';
import { Http, Response } from '@angular/http';
import { BackendManagerService } from '../... | {
return false;
}
addToMap(m, bls, dls){
this.getLayer().then(x=>{
m.addLayer(x);
dls["CityOS"] = x;
});
}
}
@Component({
selector: '[mn-map]',
templateUrl: './mn-map.component.html',
styleUrls: ['./mn-map.component.css'],
})
export class MnMapComponent {
private makeid() {
... | Base() | identifier_name |
world.py | """Define availible tiles and their actions, and build level from map file"""
import sys
import random
import decimal
import src.npc as npc
import src.enemies as enemies
class MapTile:
def __init__(self, x, y):
self.x = x
self.y = y
self.visited = 0
self.type = ''
def intro_... |
class TraderTile(MapTile):
def __init__(self, x, y):
self.trader = npc.Trader()
super().__init__(x, y)
def trade(self, buyer, seller):
if buyer.name == "Trader":
action = "sell"
buyer_char = "Trader"
else:
action = "buy"
buyer_c... | if self.enemy.is_alive():
dex_mod = decimal.Decimal(player.dex_stat / 100)
dodge_chance = decimal.Decimal(random.random()) * dex_mod
miss_chance = decimal.Decimal(random.random()) * dex_mod
if miss_chance > 0.98:
print("The {} missed!".format(self.enemy.n... | identifier_body |
world.py | """Define availible tiles and their actions, and build level from map file"""
import sys
import random
import decimal
import src.npc as npc
import src.enemies as enemies
class MapTile:
def __init__(self, x, y):
self.x = x
self.y = y
self.visited = 0
self.type = ''
def intro_... | (self):
print("\n v . ._, |_ .,")
print(" `-._\\/ . \\ / |/_")
print(" \\ _\\, y | \\//")
print(" _\\_.___\\, \\/ -.\\||")
print(" `7-,--.`._|| /... | intro_text | identifier_name |
world.py | """Define availible tiles and their actions, and build level from map file"""
import sys
import random
import decimal
import src.npc as npc
import src.enemies as enemies
class MapTile:
def __init__(self, x, y):
self.x = x
self.y = y
self.visited = 0
self.type = ''
def intro_... | tile_type = tile_type_dict[dsl_cell]
tile = None
if tile_type is not None:
tile = tile_type(x, y)
if tile_type == StartTile:
global start_tile_location
start_tile_location = x, y
row.append(tile)
worl... | break
| random_line_split |
world.py | """Define availible tiles and their actions, and build level from map file"""
import sys
import random
import decimal
import src.npc as npc
import src.enemies as enemies
class MapTile:
def __init__(self, x, y):
self.x = x
self.y = y
self.visited = 0
self.type = ''
def intro_... |
elif user_input in ['S', 's']:
print("Here's whats available to sell:\n")
self.trade(buyer=self.trader, seller=player)
else:
print("Invalid choice!")
def intro_text(self):
print("\n _________##")
print(" ... | print("Here's whats available to buy:\n")
self.trade(buyer=player, seller=self.trader) | conditional_block |
types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{
de::{Deserializer, Error},
Deserialize, Serialize,
};
use serde_repr::{Deserialize_repr, Serialize_repr};
use uuid::Uuid;
use crate::payment_command::Actor;
/// A header set with a unique UUID (according to RFC412... | : PaymentObject) -> Self {
Self {
object_type: ObjectType::PaymentCommand,
payment,
}
}
pub fn payment(&self) -> &PaymentObject {
&self.payment
}
pub fn into_payment(self) -> PaymentObject {
self.payment
}
}
/// A `PaymentActorObject` repres... | ent | identifier_name |
types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{
de::{Deserializer, Error},
Deserialize, Serialize,
};
use serde_repr::{Deserialize_repr, Serialize_repr};
use uuid::Uuid;
use crate::payment_command::Actor;
/// A header set with a unique UUID (according to RFC412... |
}
}
#[derive(Deserialize, Serialize)]
pub struct CommandRequestObject {
#[serde(deserialize_with = "ObjectType::deserialize_request")]
#[serde(rename = "_ObjectType")]
object_type: ObjectType,
#[serde(flatten)]
command: Command,
cid: Uuid,
}
impl CommandRequestObject {
pub fn new(comm... | {
Err(D::Error::custom(format_args!("expected {:?}", variant)))
} | conditional_block |
types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{
de::{Deserializer, Error},
Deserialize, Serialize,
};
use serde_repr::{Deserialize_repr, Serialize_repr};
use uuid::Uuid;
use crate::payment_command::Actor;
/// A header set with a unique UUID (according to RFC412... | b fn into_payment(self) -> PaymentObject {
self.payment
}
}
/// A `PaymentActorObject` represents a participant in a payment - either sender or receiver. It
/// also includes the status of the actor, indicates missing information or willingness to settle
/// or abort the payment, and the Know-Your-Customer... | &self.payment
}
pu | identifier_body |
types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{
de::{Deserializer, Error},
Deserialize, Serialize,
};
use serde_repr::{Deserialize_repr, Serialize_repr};
use uuid::Uuid;
use crate::payment_command::Actor;
/// A header set with a unique UUID (according to RFC412... |
/// Two-letter country code (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)
pub country: Option<String>,
/// Indicates the type of the ID
#[serde(rename = "type")]
pub id_type: Option<String>,
}
/// Represents a physical address
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize... | random_line_split | |
PhaseOne.js | import {
Badge,
Button,
Card,
CardMedia,
Divider,
Grid,
makeStyles,
Typography,
} from "@material-ui/core";
import { Alert, AlertTitle } from "@material-ui/lab";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import startSound from "../../assets/sound/start.wav";... | },
biddingStatus: {
border: "1px solid #aaa",
padding: theme.spacing(1),
backgroundColor: "#eee",
},
coinImage: {
width: "60px",
cursor: "pointer",
borderRadius: "100%",
"&.selected": {
border: "2px solid orange",
boxShadow: "0 0 10px orange",
},
},
coinStatusTable: {
borderTop: `1px solid... | },
activePlayerName: {
color: theme.palette.error.dark,
fontWeight: "bold", | random_line_split |
PhaseOne.js | import {
Badge,
Button,
Card,
CardMedia,
Divider,
Grid,
makeStyles,
Typography,
} from "@material-ui/core";
import { Alert, AlertTitle } from "@material-ui/lab";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import startSound from "../../assets/sound/start.wav";... |
if (
gameState &&
activePlayer &&
gameState.players.find((player) => player.userId === activePlayer.userId)
.bidding == null
) {
passAudio.currentTime = 0;
passAudio.play();
}
const active = gameState?.players.find((player) => player.isTurn);
const me = gameState?.players.find(
(player... | {
coinAudio.currentTime = 0;
coinAudio.play();
} | conditional_block |
main.go | package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Server str... |
nonceSize := gcm.NonceSize()
nonce, cipherText := encLastIdByteArray[:nonceSize], encLastIdByteArray[nonceSize:]
decryptedLastId, err := gcm.Open(nil, []byte(nonce), []byte(cipherText), nil)
if err != nil {
fmt.Println("Error in gcm.Open: ", err)
}
fmt.Println("Ending decryptLastId()")
return string(dec... | {
fmt.Println("Error in encryptLastId(): ", err)
} | conditional_block |
main.go | package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Server str... | (path string) string {
splitString := strings.SplitAfter(path, "/photos/")
return splitString[len(splitString)-1]
}
func stripGifPath(path string) string {
gifIndex := strings.Index(path, "/gifs/")
return path[gifIndex:]
}
func allMessagesBySender(s *Server) http.Handler {
return http.HandlerFunc(func(w http.Res... | stripPhotoPath | identifier_name |
main.go | package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Server str... |
func stripGifPath(path string) string {
gifIndex := strings.Index(path, "/gifs/")
return path[gifIndex:]
}
func allMessagesBySender(s *Server) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()["participant"]
sender := capitalizeName(q[0])
pipeline := ... | {
splitString := strings.SplitAfter(path, "/photos/")
return splitString[len(splitString)-1]
} | identifier_body |
main.go | package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Server str... | }
sender := senderQ[0]
if sender == "" {
responseObject := createEmptyServerResponseWithError(SenderEmpty)
return "", "", responseObject
}
startingIdQ := query["startAt"]
var startingId string
if len(startingIdQ) == 0 {
startingId = ""
} else {
startingId = startingIdQ[0]
}
return sender, starting... | if len(senderQ) == 0 {
responseObject := createEmptyServerResponseWithError(SenderEmpty)
return "", "", responseObject | random_line_split |
clientlib-promoengine.js | $(document).ready(function(){if($('[name="isauthor"]').val()=="true"){var b=window.location.href;
if(b.indexOf("preview=true")!=-1){if(b.indexOf("promoPath=")!=-1){var c=b.split("promoPath=")[1];
if(c.indexOf("&")!=-1&&b.indexOf("position=")!=-1){c=c.split("&")[0];
var a=b.split("position=")[1];
if($("body").find(".hco... | }s+='<div class="social-block">';
var Y="";
var K="";
var H="";
if(ac!=""||ac.includes("/content/dam/")){Y=ac;
K="redirect"
}else{if(B!=null&&B!=""){Y=B;
H="brightcove"
}else{Y=X
}}if(ad!=""){s+='<a data-share="twitter" href="javascript:void(0);" data-url="'+Y+'" data-redirect="'+K+'" data-brightcove="'+H+'" data-tit... | {s+='<div class="col-xs-1 col-md-1 col-sm-1 cntClk"><i class="fa fa-plus-square detail-toggle"></i></div>'
} | conditional_block |
clientlib-promoengine.js | $(document).ready(function(){if($('[name="isauthor"]').val()=="true"){var b=window.location.href;
if(b.indexOf("preview=true")!=-1){if(b.indexOf("promoPath=")!=-1){var c=b.split("promoPath=")[1];
if(c.indexOf("&")!=-1&&b.indexOf("position=")!=-1){c=c.split("&")[0];
var a=b.split("position=")[1];
if($("body").find(".hco... | if(!(y==="false")){var p=U=="true"?"_self":"_blank";
C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img src="/content/dam/digitalmarketing/vmware/global-icons/play_icon.png" alt="Video Play Icon" /></a>'
}else{var p=U=="true"?"_self":"_blank";
C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img sr... | }else{var p=U=="true"?"_self":"_blank";
C+="<a "+G+' class="learn_more" href='+ac+" target="+p+'><img src="/content/dam/digitalmarketing/vmware/global-icons/dark-play-icon.png" alt="Video Play Icon" /></a>'
}}else{if(aa==="fa fa-video-camera"){var C='<div class="thumb-img alt-background" id="'+x+'" style="background-i... | random_line_split |
clientlib-promoengine.js | $(document).ready(function(){if($('[name="isauthor"]').val()=="true"){var b=window.location.href;
if(b.indexOf("preview=true")!=-1){if(b.indexOf("promoPath=")!=-1){var c=b.split("promoPath=")[1];
if(c.indexOf("&")!=-1&&b.indexOf("position=")!=-1){c=c.split("&")[0];
var a=b.split("position=")[1];
if($("body").find(".hco... | (b,e,f){function a(){var l=new Date();
var k=l.getTimezoneOffset();
k=(k/60)*-1;
var j=l.getTime();
if(k!==0){return(j+(3600000*k))
}return j
}var d=$('[name="resolvedPath"]').val();
var h=$('[name="pagePath"]').attr("content");
var g=[];
$("body").find(".hcontentcard.parbase").each(function(){var j=$(this).find("input... | hcontentCarddisplay | identifier_name |
clientlib-promoengine.js | $(document).ready(function(){if($('[name="isauthor"]').val()=="true"){var b=window.location.href;
if(b.indexOf("preview=true")!=-1){if(b.indexOf("promoPath=")!=-1){var c=b.split("promoPath=")[1];
if(c.indexOf("&")!=-1&&b.indexOf("position=")!=-1){c=c.split("&")[0];
var a=b.split("position=")[1];
if($("body").find(".hco... | var d=$('[name="resolvedPath"]').val();
var h=$('[name="pagePath"]').attr("content");
var g=[];
$("body").find(".hcontentcard.parbase").each(function(){var j=$(this).find("input#promotionalContent").val();
var l=$(this).find("input#promoposition").val();
var k=$(this).find("input#IsMbox").val();
if(j==="true"&&l!=""&&l... | {var l=new Date();
var k=l.getTimezoneOffset();
k=(k/60)*-1;
var j=l.getTime();
if(k!==0){return(j+(3600000*k))
}return j
} | identifier_body |
image_pyramid.py |
import numpy as np
from matplotlib import pyplot as plt
import math
import cv2
import os
import shutil
import sys
from skimage.measure import compare_ssim
# from scipy.misc import imfilter
from skimage import color, data, restoration
from scipy.signal import convolve2d
from skimage.exposure import rescale_intensity
... |
def get_transmission(self,img, atmosphere, *, size, omega, radius, epsilon):
"""Estimate transmission map of an image.
@param img: The source image.
@param atmosphere: The atmospheric light for the image.
@param omega: Factor to preserve minor amounts of haze [1].
@param rad... | """Estimate atmospheric light for an image.
@param img: the source image.
@param size: Patch size for calculating the dark channel.
@param percent: Percentage of brightest pixels in the dark channel
considered for the estimation.
@return The estimated atmospheric light.
"... | identifier_body |
image_pyramid.py | import numpy as np
from matplotlib import pyplot as plt
import math
import cv2
import os
import shutil
import sys
from skimage.measure import compare_ssim
# from scipy.misc import imfilter
from skimage import color, data, restoration
from scipy.signal import convolve2d
from skimage.exposure import rescale_intensity
i... |
flat_img = img.reshape(m * n, 3)
flat_dark = self.get_dark_channel(img, size=size).ravel()
count = math.ceil(m * n * percent / 100)
indices = np.argpartition(flat_dark, -count)[:-count]
return np.amax(np.take(flat_img, indices, axis=0), axis=0)
def get_transmission(self,img... | random_line_split | |
image_pyramid.py |
import numpy as np
from matplotlib import pyplot as plt
import math
import cv2
import os
import shutil
import sys
from skimage.measure import compare_ssim
# from scipy.misc import imfilter
from skimage import color, data, restoration
from scipy.signal import convolve2d
from skimage.exposure import rescale_intensity
... | (self,img, atmosphere, *, size, omega, radius, epsilon):
"""Estimate transmission map of an image.
@param img: The source image.
@param atmosphere: The atmospheric light for the image.
@param omega: Factor to preserve minor amounts of haze [1].
@param radius: (default: 40) Radius... | get_transmission | identifier_name |
image_pyramid.py |
import numpy as np
from matplotlib import pyplot as plt
import math
import cv2
import os
import shutil
import sys
from skimage.measure import compare_ssim
# from scipy.misc import imfilter
from skimage import color, data, restoration
from scipy.signal import convolve2d
from skimage.exposure import rescale_intensity
... |
else:
sys.stderr.write('Skipping %s, not RGB' % basename)
continue
#Extract haze from the scene and then save the image
dehazed = self.get_scene_radiance(image)
cv2.imwrite(os.path.join(resultdir, basename), dehazed... | print('Processing %s ...' % basename) | conditional_block |
node.py | # Copyright 2018 IBM. 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 law or agreed t... |
def clear_attrs(self):
"""
Remove any attributes that are attached to this node.
"""
self._attributes.clear()
def _attr_names(self):
return [a[0] for a in self._attributes]
@Node.inputs.getter
def inputs(self) -> Tuple[tensor.Tensor]:
return tuple(self._inputs)
def set_inputs(self... | return tuple([p[0] for p in self._attributes]) | identifier_body |
node.py | # Copyright 2018 IBM. 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 law or agreed t... | (self):
ret = tf.NodeDef()
ret.name = self.name
ret.op = self.op_name
for input_tensor in self.inputs:
ret.input.append(input_tensor.name)
for control_input_node in self.control_inputs:
ret.input.append("^" + control_input_node.name)
ret.device = self.device
for (attr_name, attr_... | to_node_def | identifier_name |
node.py | # Copyright 2018 IBM. 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 law or agreed t... |
elif attr_value.HasField("shape"): # TensorShape
# Undocumented behavior of public API: tf.TensorShape constructor accepts
# a TensorShapeProto.
return tf.TensorShape(attr_value.shape)
elif attr_value.HasField("tensor"): # TensorProto
return tf.make_ndarray(attr_value.tensor)
# TODO(frreiss)... | return tf.DType(attr_value.type) | conditional_block |
node.py | # Copyright 2018 IBM. 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 law or agreed t... | "tf.AttrValue".format(type(value)))
def _attr_value_to_python_type(attr_value: tf.AttrValue) -> Any:
"""
Inverse of _python_type_to_attr_value().
Args:
attr_value: Protocol buffer version of a node's attribute value
Returns:
A Python object or built-in type corresponding to the ... | else:
raise ValueError("Don't know how to convert a {} to " | random_line_split |
goto_definition.rs | use super::NavigationTarget;
use crate::def::{AstPtr, Expr, Literal, ResolveResult};
use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath};
use nix_interop::FLAKE_FILE;
use syntax::ast::{self, AstNode};
use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken};
#[derive(Debug, Clone, PartialEq, E... |
#[track_caller]
fn check(fixture: &str, expect: Expect) {
let (db, f) = TestDB::from_fixture(fixture).unwrap();
assert_eq!(f.markers().len(), 1, "Missing markers");
let mut got = match goto_definition(&db, f[0]).expect("No definition") {
GotoDefinitionResult::Path(path) => ... | {
let (db, f) = TestDB::from_fixture(fixture).unwrap();
assert_eq!(f.markers().len(), 1, "Missing markers");
assert_eq!(goto_definition(&db, f[0]), None);
} | identifier_body |
goto_definition.rs | use super::NavigationTarget;
use crate::def::{AstPtr, Expr, Literal, ResolveResult};
use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath};
use nix_interop::FLAKE_FILE;
use syntax::ast::{self, AstNode};
use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken};
#[derive(Debug, Clone, PartialEq, E... |
// Currently builtin names cannot "goto-definition".
ResolveResult::Builtin(_) => return None,
};
Some(GotoDefinitionResult::Targets(targets))
}
fn goto_flake_input(
db: &dyn DefDatabase,
file: FileId,
tok: SyntaxToken,
) -> Option<GotoDefinitionResult> {
let module_kind = db.... | {
withs
.iter()
.filter_map(|&with_expr| {
// with expr; body
// ^--^ focus
// ^--------^ full
let with_node = source_map
.node_for_expr(with_expr)
... | conditional_block |
goto_definition.rs | use super::NavigationTarget;
use crate::def::{AstPtr, Expr, Literal, ResolveResult};
use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath};
use nix_interop::FLAKE_FILE;
use syntax::ast::{self, AstNode};
use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken};
#[derive(Debug, Clone, PartialEq, E... | (fixture: &str, expect: Expect) {
let (db, f) = TestDB::from_fixture(fixture).unwrap();
assert_eq!(f.markers().len(), 1, "Missing markers");
let mut got = match goto_definition(&db, f[0]).expect("No definition") {
GotoDefinitionResult::Path(path) => format!("file://{}", path.display(... | check | identifier_name |
goto_definition.rs | use super::NavigationTarget;
use crate::def::{AstPtr, Expr, Literal, ResolveResult};
use crate::{DefDatabase, FileId, FilePos, ModuleKind, VfsPath};
use nix_interop::FLAKE_FILE;
use syntax::ast::{self, AstNode};
use syntax::{best_token_at_offset, match_ast, SyntaxKind, SyntaxToken};
#[derive(Debug, Clone, PartialEq, E... | expect!["<a> = a;"],
);
check(
"let a = $0a; in rec { inherit a; b = a; }",
expect!["<a> = a;"],
);
}
#[test]
fn left_and_right() {
check("let a = 1; in $0a ", expect!["<a> = 1;"]);
check("let a = 1; in a$0 ", expect!["<a> = 1;"]);... | expect!["inherit <a>;"],
);
check(
"let a = a; in rec { inherit $0a; b = a; }", | random_line_split |
sink_test.go | // Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/li... | require.NoError(t, sink.Flush(ctx))
sqlDB.CheckQueryResults(t, `SELECT topic, key, value FROM sink ORDER BY PRIMARY KEY sink`,
[][]string{{`bar`, `kbar`, `v0`}, {`foo`, `kfoo`, `v0`}, {`foo`, `kfoo`, `v1`}},
)
sqlDB.Exec(t, `TRUNCATE sink`)
// Multiple keys interleaved in time. Use sqlSinkNumPartitions+1 keys t... | require.NoError(t, sink.EmitRow(ctx, barTopic, []byte(`kbar`), []byte(`v0`), zeroTS))
require.NoError(t, sink.EmitRow(ctx, fooTopic, []byte(`kfoo`), []byte(`v1`), zeroTS)) | random_line_split |
sink_test.go | // Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/li... |
func (p *asyncProducerMock) Close() error {
close(p.inputCh)
close(p.successesCh)
close(p.errorsCh)
return nil
}
// consumeAndSucceed consumes input messages and sends them to successes channel.
// Returns function that must be called to stop this consumer
// to clean up. The cleanup function must be called befor... | { panic(`unimplemented`) } | identifier_body |
sink_test.go | // Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/li... |
n -= len(outstanding)
}
}
// outstanding returns the number of un-acknowledged messages.
func (p *asyncProducerMock) outstanding() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.mu.outstanding)
}
func topic(name string) tableDescriptorTopic {
return tableDescriptorTopic{tabledesc.NewBuilder(&descpb.TableD... | {
ch <- m
} | conditional_block |
sink_test.go | // Copyright 2018 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/li... | () int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.mu.outstanding)
}
func topic(name string) tableDescriptorTopic {
return tableDescriptorTopic{tabledesc.NewBuilder(&descpb.TableDescriptor{Name: name}).BuildImmutableTable()}
}
const memoryUnlimited int64 = math.MaxInt64
const noTopicPrefix = ""
const defaultTo... | outstanding | identifier_name |
amqp.rs | // Copyright 2020-2021, The Tremor Team
//
// 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 agr... | (&mut self, _signal: Event) -> ResultVec {
//self.drain_fatal_errors()?;
Ok(Vec::new())
}
fn is_active(&self) -> bool {
true
}
fn auto_ack(&self) -> bool {
false
}
async fn terminate(&mut self) {
if let Some(channel) = self.channel.as_ref() {
i... | on_signal | identifier_name |
amqp.rs | // Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
impl ConfigImpl for Config {}
/// Amqp offramp connector
pub(crate) struct Amqp {
sink_url: TremorUrl,
config: Config,
postprocessors: Postprocessors,
reply_channel: Sender<sink::Reply>,
channel: Option<Channel>,
error_rx: Receiver<()>,
error_tx: Sender<()>,
}
impl fmt::Debug for Amqp {
... | }
}
} | random_line_split |
amqp.rs | // Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
}
#[async_trait::async_trait]
impl Sink for Amqp {
async fn on_event(
&mut self,
_input: &str,
codec: &mut dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
event: Event,
) -> ResultVec {
self.handle_channel().await?;
let ingest_ns = event.ingest_... | {
while let Ok(()) = self.error_rx.try_recv() {
self.channel = None;
}
if self.channel.is_none() {
match self.config.channel().await.await {
Ok(channel) => self.channel = Some(channel),
Err(error) => return Err(error.into()),
}
... | identifier_body |
amqp.rs | // Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
Confirmation::Nack(err) => {
if let Some(e) = err {
error!(
"[Sink::{}] failed to send message: {} {}",
&self.sink_url, e.reply_code, e.reply_text
... | {
if event.transactional {
let mut insight = insight_event.clone();
insight.cb = CbAction::Ack;
// we hopefully enver wait more then u64 ... if we do we got
// bigg... | conditional_block |
mod.rs | // src/io/mod.rs -- input/output interfaces for Tectonic.
// Copyright 2016-2018 the Tectonic Project
// Licensed under the MIT License.
//! Tectonic’s pluggable I/O backend.
use flate2::read::GzDecoder;
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{self, Cursor, Read, Seek, ... | /// Open the "primary" input file, which in the context of TeX is the main
/// input that it's given. When the build is being done using the
/// filesystem and the input is a file on the filesystem, this function
/// isn't necesssarily that important, but those conditions don't always
/// hold.
... | OpenResult::NotAvailable
}
| identifier_body |
mod.rs | // src/io/mod.rs -- input/output interfaces for Tectonic.
// Copyright 2016-2018 the Tectonic Project
// Licensed under the MIT License.
//! Tectonic’s pluggable I/O backend.
use flate2::read::GzDecoder;
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{self, Cursor, Read, Seek, ... | _ => r.push(c),
}
}
let r = repeat("..")
.take(parent_level)
.chain(r.into_iter())
// No `join` on `Iterator`.
.collect::<Vec<_>>()
.join("/");
if r.is_empty() {
if has_root {
Some("/".into())
} else {
Some... | _ => {}
}
} | random_line_split |
mod.rs | // src/io/mod.rs -- input/output interfaces for Tectonic.
// Copyright 2016-2018 the Tectonic Project
// Licensed under the MIT License.
//! Tectonic’s pluggable I/O backend.
use flate2::read::GzDecoder;
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{self, Cursor, Read, Seek, ... |
}
}
/// Normalize a TeX path in a system independent™ way by stripping any `.`, `..`,
/// or extra separators '/' so that it is of the form
///
/// ```text
/// path/to/my/file.txt
/// ../../path/to/parent/dir/file.txt
/// /absolute/path/to/file.txt
/// ```
///
/// Does not strip whitespace.
///
/// Returns `None`... | OpenResult::Err(e.into())
}
} | conditional_block |
mod.rs | // src/io/mod.rs -- input/output interfaces for Tectonic.
// Copyright 2016-2018 the Tectonic Project
// Licensed under the MIT License.
//! Tectonic’s pluggable I/O backend.
use flate2::read::GzDecoder;
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{self, Cursor, Read, Seek, ... | : 'static + Write>(name: &OsStr, inner: T) -> OutputHandle {
OutputHandle {
name: name.to_os_string(),
inner: Box::new(inner),
digest: digest::create(),
}
}
pub fn name(&self) -> &OsStr {
self.name.as_os_str()
}
/// Consumes the object and re... | w<T | identifier_name |
backend_helper.go | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. 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.... | (claim xuanwuv1.StorageBackendClaim) *BackendShowWide {
b.Namespace = claim.Namespace
b.Name = claim.Name
if claim.Status != nil {
b.StorageType = claim.Status.StorageType
b.Protocol = claim.Status.Protocol
b.Status = string(claim.Status.Phase)
}
return b
}
// ToBackendShow convert BackendShowWide to Backen... | ShowWithClaimOption | identifier_name |
backend_helper.go | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. 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.... | else {
backends, err = LoadSingleBackendFromConfigmap(jsonStr)
}
if err != nil {
return nil, err
}
for _, backend := range backends {
result[backend.Name] = backend
}
return result, nil
}
//AnalyseBackendExist analyse backend,an error is returned if backends not exist
func AnalyseBackendExist(jsonStr str... | {
backends, err = LoadMultipleBackendFromConfigmap(jsonStr)
} | conditional_block |
backend_helper.go | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. 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.... |
// LoadBackendsFromYaml load backend from yaml
func LoadBackendsFromYaml(yamlData []byte) (map[string]*BackendConfiguration, error) {
cleanYamlData := strings.Trim(strings.TrimSpace(string(yamlData)), YamlSeparator)
decoder := yaml.NewDecoder(bytes.NewReader([]byte(cleanYamlData)))
var backends = map[string]*Back... | {
config := struct {
Backends []*BackendConfiguration `json:"backends"`
}{}
if err := json.Unmarshal([]byte(jsonStr), &config); err != nil {
return nil, err
}
return config.Backends, nil
} | identifier_body |
backend_helper.go | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. 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.... | }
// BackendShow the content echoed by executing the oceanctl get backend
type BackendShow struct {
Namespace string `show:"NAMESPACE"`
Name string `show:"NAME"`
Protocol string `show:"PROTOCOL"`
StorageType string `show:"STORAGETYPE"`
Sn string `show:"SN"`
Status string `show:"STATUS"`... | Url string `show:"Url"`
VendorName string `show:"VENDORNAME"`
StorageBackendContentName string `show:"STORAGEBACKENDCONTENTNAME"` | random_line_split |
drawing_support.py | """
Functions used to support drawing. No Pyglet/OpenGL here.
"""
import math
import pymunk
from PIL import Image
from pymunk import autogeometry
from typing import List, Tuple, cast
from arcade import Color
from arcade import RGBA
def get_points_for_thick_line(start_x: float, start_y: float,
... |
if min_x is None or max_x is None or min_y is None or max_y is None:
raise ValueError("No points in bounding box.")
my_range = max_x - min_x + max_y + min_y
if selected_range is None or my_range > selected_range:
selected_range = my_range
... | max_y = point.y | conditional_block |
drawing_support.py | """
Functions used to support drawing. No Pyglet/OpenGL here.
"""
import math
import pymunk
from PIL import Image
from pymunk import autogeometry
from typing import List, Tuple, cast
from arcade import Color
from arcade import RGBA
def get_points_for_thick_line(start_x: float, start_y: float,
... | points = (r1_x, r1_y), (r2_x, r2_y), (r4_x, r4_y), (r3_x, r3_y)
return points
def get_four_byte_color(color: Color) -> RGBA:
"""
Given a RGB list, it will return RGBA.
Given a RGBA list, it will return the same RGBA.
:param Color color: Three or four byte tuple
:returns: retu... | r2_y = start_y - normal_y * line_width / 2
r3_x = end_x + normal_x * line_width / 2
r3_y = end_y + normal_y * line_width / 2
r4_x = end_x - normal_x * line_width / 2
r4_y = end_y - normal_y * line_width / 2
| random_line_split |
drawing_support.py | """
Functions used to support drawing. No Pyglet/OpenGL here.
"""
import math
import pymunk
from PIL import Image
from pymunk import autogeometry
from typing import List, Tuple, cast
from arcade import Color
from arcade import RGBA
def get_points_for_thick_line(start_x: float, start_y: float,
... |
def rotate_point(x: float, y: float, cx: float, cy: float,
angle_degrees: float) -> List[float]:
"""
Rotate a point around a center.
:param x: x value of the point you want to rotate
:param y: y value of the point you want to rotate
:param cx: x value of the center poi... | """
Given a RGB color, along with an alpha, returns a RGBA color tuple.
:param Color color: Three or four byte RGBA color
:param float transparency: Transparency
"""
return color[0], color[1], color[2], transparency | identifier_body |
drawing_support.py | """
Functions used to support drawing. No Pyglet/OpenGL here.
"""
import math
import pymunk
from PIL import Image
from pymunk import autogeometry
from typing import List, Tuple, cast
from arcade import Color
from arcade import RGBA
def get_points_for_thick_line(start_x: float, start_y: float,
... | (image: Image, hit_box_detail: float = 4.5):
"""
Given an image, this returns points that make up a hit box around it. Attempts
to trim out transparent pixels.
:param Image image: Image get hit box from.
:param int hit_box_detail: How detailed to make the hit box. There's a
... | calculate_hit_box_points_detailed | identifier_name |
groupspec.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: akash/deployment/v1beta2/groupspec.proto
package v1beta2
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
v1beta2 "github.com/ovrclk/akash/types/v1beta2"
io "io"
math "math"
math_bits "math/bits"
)
//... |
func init() {
proto.RegisterFile("akash/deployment/v1beta2/groupspec.proto", fileDescriptor_8afb9070f2e843b2)
}
var fileDescriptor_8afb9070f2e843b2 = []byte{
// 351 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xbf, 0x4e, 0xc3, 0x30,
0x10, 0xc6, 0... | {
proto.RegisterType((*GroupSpec)(nil), "akash.deployment.v1beta2.GroupSpec")
} | identifier_body |
groupspec.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: akash/deployment/v1beta2/groupspec.proto
package v1beta2
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
v1beta2 "github.com/ovrclk/akash/types/v1beta2"
io "io"
math "math"
math_bits "math/bits"
)
//... | }
m.Name = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Requirements", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowGroupspec
}
if iN... | return ErrInvalidLengthGroupspec
}
if postIndex > l {
return io.ErrUnexpectedEOF | random_line_split |
groupspec.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: akash/deployment/v1beta2/groupspec.proto
package v1beta2
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
v1beta2 "github.com/ovrclk/akash/types/v1beta2"
io "io"
math "math"
math_bits "math/bits"
)
//... |
return len(dAtA) - i, nil
}
func encodeVarintGroupspec(dAtA []byte, offset int, v uint64) int {
offset -= sovGroupspec(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *GroupSpec) Size() (n int) {
if m == nil {
retur... | {
i -= len(m.Name)
copy(dAtA[i:], m.Name)
i = encodeVarintGroupspec(dAtA, i, uint64(len(m.Name)))
i--
dAtA[i] = 0xa
} | conditional_block |
groupspec.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: akash/deployment/v1beta2/groupspec.proto
package v1beta2
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/gogo/protobuf/proto"
v1beta2 "github.com/ovrclk/akash/types/v1beta2"
io "io"
math "math"
math_bits "math/bits"
)
//... | () {
proto.RegisterFile("akash/deployment/v1beta2/groupspec.proto", fileDescriptor_8afb9070f2e843b2)
}
var fileDescriptor_8afb9070f2e843b2 = []byte{
// 351 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xbf, 0x4e, 0xc3, 0x30,
0x10, 0xc6, 0x93, 0x16, ... | init | identifier_name |
main.go | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var validAttrs = []string{
"strength", "defense", "speed", "accuracy", "vitality", "resistance", "willpower",
}
func main() {
rand.Seed(time.Now().UnixNano())
Play()
}
type Unit struct {
Name string
Ty... |
type order struct {
Name string
Speed int
}
func getPlayOrder(units []Unit) []string {
var orders []order
for _, u := range units {
orders = append(orders, order{u.Name, u.Speed()})
}
return handleOrders(orders)
}
func handleOrders(orders []order) []string {
ordered := []string{}
for {
if allAcco... | {
teams := make(map[int]bool)
for _, cbt := range cbts {
if cbt.Hp > 0 {
teams[cbt.Team] = true
}
}
if len(teams) < 2 {
return true
}
return false
} | identifier_body |
main.go | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var validAttrs = []string{
"strength", "defense", "speed", "accuracy", "vitality", "resistance", "willpower",
}
func main() {
rand.Seed(time.Now().UnixNano())
Play()
}
type Unit struct {
Name string
Ty... | (i int) Unit {
u.combatAttrMods.Accuracy += i
return u
}
func (u Unit) ModVitality(i int) Unit {
u.combatAttrMods.Vitality += i
return u
}
func (u Unit) ModSpeed(i int) Unit {
u.combatAttrMods.Speed += i
return u
}
func (u Unit) ModWillpower(i int) Unit {
u.combatAttrMods.Willpower += i
return u
}
func (u Unit)... | ModAccuracy | identifier_name |
main.go | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var validAttrs = []string{
"strength", "defense", "speed", "accuracy", "vitality", "resistance", "willpower",
}
func main() {
rand.Seed(time.Now().UnixNano())
Play()
}
type Unit struct {
Name string
Ty... |
}
}
units[i] = unit
}
activeIndex := -1
for i, unit := range units {
if unit.Name == active.Name {
active = unit
activeIndex = i
break
}
}
active.Fatigue += atk.FatigueCost
active = active.Crunch()
units[activeIndex] = active
return units
}
func resolveAttack(attack Attack, unit Unit... | {
switch result.Attr {
case "strength":
unit = unit.ModStrength(result.Damange)
case "defense":
unit = unit.ModDefense(result.Damange)
case "speed":
unit = unit.ModSpeed(result.Damange)
case "accuracy":
unit = unit.ModAccuracy(result.Damange)
case "fatigue":
u... | conditional_block |
main.go | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
)
var validAttrs = []string{
"strength", "defense", "speed", "accuracy", "vitality", "resistance", "willpower",
}
func main() {
rand.Seed(time.Now().UnixNano())
Play()
}
type Unit struct {
Name string
Ty... | if atk.Name == "" {
fmt.Println("Ivalid attack")
return pickPlayerAttack(atks)
}
return atk
}
func randomInt(min, max int) int {
max++
return min + rand.Intn(max-min)
}
func read(msg string) string {
reader := bufio.NewReader(os.Stdin)
fmt.Println(msg)
text, _ := reader.ReadString('\n')
text = strings.R... | }
} | random_line_split |
execution.rs | // Copyright 2018-2021 Parity Technologies (UK) Ltd.
//
// 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 applicab... |
}
/// Trait used to convert return types of contract initializer routines.
///
/// Only `()` and `Result<(), E>` are allowed contract initializer return types.
/// For `WrapReturnType<C>` where `C` is the contract type the trait converts
/// `()` into `C` and `Result<(), E>` into `Result<C, E>`.
pub trait Initializer... | {
&self.0
} | identifier_body |
execution.rs | // Copyright 2018-2021 Parity Technologies (UK) Ltd.
//
// 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 applicab... |
if TypeId::of::<R>() != TypeId::of::<()>() {
// In case the return type is `()` we do not return a value.
ink_env::return_value::<R>(ReturnFlags::default(), result)
}
Ok(())
}
#[inline]
fn finalize_fallible_message<R>(result: &R) -> !
where
R: scale::Encode + 'static,
{
// There is... | {
alloc::finalize();
} | conditional_block |
execution.rs | // Copyright 2018-2021 Parity Technologies (UK) Ltd.
//
// 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 applicab... | <Contract, F, R>(
initializer: F,
) -> <R as InitializerReturnType<Contract>>::Wrapped
where
Contract: ContractRootKey + SpreadAllocate,
F: FnOnce(&mut Contract) -> R,
R: InitializerReturnType<Contract>,
{
let mut key_ptr = KeyPtr::from(<Contract as ContractRootKey>::ROOT_KEY);
let mut instance ... | initialize_contract | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.