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 |
|---|---|---|---|---|
web_8_ReduceMemory.py | (SMILES_CHARS))
def | (smiles, maxlen=34):
#print(smiles)
#smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
#print(smiles)
X = np.zeros((maxlen, len(SMILES_CHARS)))
for i, c in enumerate(smiles):
#print(i)
#print(c)
X[i, smi2index[c]] = 1
return X
def smiles_decoder( X ):
smi = ''
... | smiles_encoder | identifier_name |
web_8_ReduceMemory.py | (SMILES_CHARS))
def smiles_encoder(smiles, maxlen=34):
#print(smiles)
#smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
#print(smiles)
X = np.zeros((maxlen, len(SMILES_CHARS)))
for i, c in enumerate(smiles):
#print(i)
#print(c)
X[i, smi2index[c]] = 1
return X
def ... |
outt = np.delete(outt, 0, 0)
return(outt)
########webbbbbb
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1
model = None
@app.route("/")
def index():
#name = request.args['name']
return render_template("request_holu.html");
@app.route('/result/',methods = ['POST', 'GET']... | u = np.random.normal(0,1,dim) # an array of d normally distributed random variables
norm=np.sum(u**2) **(0.5)
r = random.random()**(1/dim)
x= dis*r*u/norm
x = x + pos
outt = np.vstack((outt, x)) | conditional_block |
web_8_ReduceMemory.py | (SMILES_CHARS))
def smiles_encoder(smiles, maxlen=34):
#print(smiles)
#smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
#print(smiles)
X = np.zeros((maxlen, len(SMILES_CHARS)))
for i, c in enumerate(smiles):
#print(i)
#print(c)
X[i, smi2index[c]] = 1
return X
def ... | y_homo = y_homo,
y_lumo = y_lumo
)
#@app.route("/calculation/<float(signed=True):homo_desire>/<float(signed=True):lumo_desire>/<int:ramdom_sample_value>/<int:dis>/<float:std>")
def calculation(homo_desire, lumo_desire, ramdom_sample_value, dis, std):
#pd_desire: prediction of ... | if request.method == 'POST':
homo_desire = float(request.form['homo_desire'])
lumo_desire = float(request.form['lumo_desire'])
ramdom_sample_value = int(request.form['ramdom_sample_value'])
dis = int(request.form['dis'])
std = float(request.form['std'])
pd_desire, predi... | identifier_body |
web_8_ReduceMemory.py | _loss, 'homo_loss': mse_loss, 'lumo_loss': mse_loss})
encoder = keras.models.load_model("./keras_model/holu_retrain/ep100_holu_encoder_retrain_Weipp1.h5", custom_objects={'x_pred': reconstruct_error, 'kl_loss': kl_loss, 'homo_loss': mse_loss, 'lumo_loss': mse_loss})
decoder = keras.models.load_model("./keras_mo... | random_line_split | ||
sync-server.js | before returning the response for the sync request. Default is true. */
syncReqWaitForAck: true,
/** @type {Number} Specify the max number of ack items will be processed for a single request. Default is -1 (unlimited).*/
syncReqAckLimit: -1,
/** @type {Function} Provide your own cuid generator. It should be a ... | interceptRequest | identifier_name | |
sync-server.js | Number} specify the minimum gap between each retry of applying a pending change.
* Please note that this is just a minimum value as the worker interval value will also affect when a pending change will actually be retried.
* For example, if the worker is scheduled to run the next job in 20 seconds, then the pe... |
syncStorage.updateManyDatasetClients({datasetId: dataset_id}, {stopped: false}, cb);
});
}
function setClients(mongo, redis) {
mongoDbClient = mongo;
redisClient = redis;
defaultDataHandlers.setMongoDB(mongoDbClient);
cacheClient = cacheClientModule(syncConfig, redisClient);
syncStorage = storageModul... | {
return cb(err);
} | conditional_block |
sync-server.js | * `params.__fh.cuid`: the cuid generated on the client.
*
* This function should not be overidden in most cases. This should *ONLY* be provided if there is a chance that the clients may have duplicated cuids.
*/
cuidProducer: syncUtil.getCuid
};
var syncConfig = _.extend({}, DEFAULT_SYNC_CONF);
var syncSt... | {
debug('[%s] removeCollision');
dataHandlers.removeCollision(datasetId, params.hash, params.meta_data, cb);
} | identifier_body | |
sync-server.js | Number} specify the minimum gap between each retry of applying a pending change.
* Please note that this is just a minimum value as the worker interval value will also affect when a pending change will actually be retried.
* For example, if the worker is scheduled to run the next job in 20 seconds, then the pe... | /**@type {Number} the concurrency value for the component metrics. Default is 10. This value should be increased if there are many concurrent workers. Otherwise the memory useage of the app could go up.*/
metricsReportConcurrency: 10,
/**@type {Boolean} if cache the dataset client records using redis. This can he... | /**@type {Number} the port of the influxdb server. It should be a UDP port. */
metricsInfluxdbPort: null, | random_line_split |
docker.go | error {
if d.cli != nil {
return nil
}
cli, err := getDockerClient()
if err != nil {
return fmt.Errorf("Unable to init docker client: %v", err)
}
d.cli = cli
return nil
}
func (d *docker) checkBackingImage() error {
glog.Infof("Checking backing docker image %s", d.cfg.DockerImage)
args := filters.NewArg... | }
glog.Infof("%s successfully unmounted", vol.UUID)
}
}
func (d *docker) unmapVolumes() {
for _, vol := range d.cfg.Volumes {
if err := d.storageDriver.UnmapVolumeFromNode(vol.UUID); err != nil {
glog.Warningf("Unable to unmap %s: %v", vol.UUID, err)
continue
}
glog.Infof("Unmapping volume %s", vol.U... | random_line_split | |
docker.go | 0 {
// CFS quota period - default to 100ms.
hostConfig.CPUPeriod = 100 * 1000
hostConfig.CPUQuota = hostConfig.CPUPeriod * int64(d.cfg.Cpus)
}
networkConfig = &network.NetworkingConfig{}
if bridge != "" {
config.MacAddress = d.cfg.VnicMAC
hostConfig.NetworkMode = container.NetworkMode(bridge)
networkCon... | {
return -1
} | conditional_block | |
docker.go | {
if d.cli != nil {
return nil
}
cli, err := getDockerClient()
if err != nil {
return fmt.Errorf("Unable to init docker client: %v", err)
}
d.cli = cli
return nil
}
func (d *docker) checkBackingImage() error {
glog.Infof("Checking backing docker image %s", d.cfg.DockerImage)
args := filters.NewArgs()
i... |
idPath := path.Join(d.instanceDir, "docker-id")
err = ioutil.WriteFile(idPath, []byte(resp.ID), 0600)
if err != nil {
glog.Errorf("Unable to store docker container ID %v", err)
_ = dockerDeleteContainer(d.cli, resp.ID, d.cfg.Instance)
return err
}
d.dockerID = resp.ID
// This value is configurable. Need... | {
err := d.initDockerClient()
if err != nil {
return err
}
volumes, err := d.prepareVolumes()
if err != nil {
glog.Errorf("Unable to mount container volumes %v", err)
return err
}
config, hostConfig, networkConfig := d.createConfigs(bridge, userData, metaData, volumes)
resp, err := d.cli.ContainerCreat... | identifier_body |
docker.go | cmd []string
md := &struct {
Hostname string `json:"hostname"`
}{}
err := json.Unmarshal(metaData, md)
if err != nil {
glog.Info("Start command does not contain hostname. Setting to instance UUID")
hostname = d.cfg.Instance
} else {
glog.Infof("Found hostname %s", md.Hostname)
hostname = md.Hostname
}
... | monitorVM | identifier_name | |
computation.go | limitSize asyncMetadata[int]
matchedNoTimeseriesQuery asyncMetadata[string]
groupByMissingProperties asyncMetadata[[]string]
tsidMetadata map[idtool.ID]*asyncMetadata[*messages.MetadataProperties]
}
// ComputationError exposes the underlying metadata of a computation error
type ComputationError str... | }
return err
}
func newComputation(channel <-chan messages.Message, name string, client *Client) *Computation {
comp := &Computation{
channel: channel,
name: name,
client: client,
dataCh: make(chan *messages.DataMessage),
dataChBuffer: make(chan *mess... | }
if e.Message != "" {
err = fmt.Sprintf("%v: %v", err, e.Message) | random_line_split |
computation.go | limitSize asyncMetadata[int]
matchedNoTimeseriesQuery asyncMetadata[string]
groupByMissingProperties asyncMetadata[[]string]
tsidMetadata map[idtool.ID]*asyncMetadata[*messages.MetadataProperties]
}
// ComputationError exposes the underlying metadata of a computation error
type ComputationError str... | c.maxDelayMS.Set(v.MessageBlock.Contents.(messages.JobInitialMaxDelayContents).MaxDelayMS())
case messages.FindLimitedResultSet:
c.matchedSize.Set(v.MessageBlock.Contents.(messages.FindLimitedResultSetContents).MatchedSize())
c.limitSize.Set(v.MessageBlock.Contents.(messages.FindLimitedResultSetContents).Lim... | {
switch v := m.(type) {
case *messages.JobStartControlMessage:
c.handle.Set(v.Handle)
case *messages.EndOfChannelControlMessage, *messages.ChannelAbortControlMessage:
return errChannelClosed
case *messages.DataMessage:
c.dataChBuffer <- v
case *messages.ExpiredTSIDMessage:
c.Lock()
delete(c.tsidMetadata... | identifier_body |
computation.go | imitSize asyncMetadata[int]
matchedNoTimeseriesQuery asyncMetadata[string]
groupByMissingProperties asyncMetadata[[]string]
tsidMetadata map[idtool.ID]*asyncMetadata[*messages.MetadataProperties]
}
// ComputationError exposes the underlying metadata of a computation error
type ComputationError struc... |
c.tsidMetadata[v.TSID].Set(&v.Properties)
c.Unlock()
case *messages.EventMessage:
c.eventChBuffer <- v
}
return nil
}
func bufferMessages[T any](in chan *T, out chan *T) {
buffer := make([]*T, 0)
var nextMessage *T
defer func() {
if nextMessage != nil {
out <- nextMessage
}
for i := range buffer... | {
c.tsidMetadata[v.TSID] = &asyncMetadata[*messages.MetadataProperties]{}
} | conditional_block |
computation.go | limitSize asyncMetadata[int]
matchedNoTimeseriesQuery asyncMetadata[string]
groupByMissingProperties asyncMetadata[[]string]
tsidMetadata map[idtool.ID]*asyncMetadata[*messages.MetadataProperties]
}
// ComputationError exposes the underlying metadata of a computation error
type ComputationError str... | (ctx context.Context) (time.Duration, error) {
maxDelayMS, err := c.maxDelayMS.Get(ctx)
return time.Duration(maxDelayMS) * time.Millisecond, err
}
// MatchedSize detected of the job. Will wait as long as the given ctx is not closed. If ctx is closed an
// error will be returned.
func (c *Computation) MatchedSize(ctx... | MaxDelay | identifier_name |
ffmpeg_video_splitter.py | Command(self,ffmpeg_cmd):
ffmpeg_cmd = ffmpeg_cmd.replace("'", "\"")
self.ffmpeg_cmd_line.append(ffmpeg_cmd)
def AddFFMpegFilterComplex(self,filter_complex_option):
self.filter_complex_list.append(filter_complex_option)
def GetTimeDiff(dt_start, dt_end):
time_... | # and what if there is more than one video?
time_stamp = ConvertToDateTime(input_video_block.value)
video_file.time = time_stamp
elif input_video_block.key == "$ffmpeg_cmd":
video_file.global_ffmpeg_cmd.append(input_video_block.value)
crc_list.... | # you might not be able to get a date modified due to no input videos being added, oof
| random_line_split |
ffmpeg_video_splitter.py | Command(self,ffmpeg_cmd):
ffmpeg_cmd = ffmpeg_cmd.replace("'", "\"")
self.ffmpeg_cmd_line.append(ffmpeg_cmd)
def AddFFMpegFilterComplex(self,filter_complex_option):
self.filter_complex_list.append(filter_complex_option)
def GetTimeDiff(dt_start, dt_end):
time_... | (directory):
if not os.path.exists(directory):
os.makedirs(directory)
def RemoveDirectory(directory):
if os.path.isdir(directory):
shutil.rmtree(directory)
def DeleteFile( path ):
try:
os.remove(path)
except FileNotFoundError:
pass
def ParseConfig( ... | CreateDirectory | identifier_name |
ffmpeg_video_splitter.py |
def FindCommand( arg, short_arg ):
found = FindItemInList(sys.argv, arg, False)
if not found:
found = FindItemInList(sys.argv, short_arg, False)
return found
def FindCommandValue( arg, short_arg ):
value = FindItemInList(sys.argv, arg, True)
if not value:
value = Fi... | if item in search_list:
if return_value:
return search_list[search_list.index(item) + 1]
else:
return True
else:
return False | identifier_body | |
ffmpeg_video_splitter.py | 8")
ffmpeg_command.append("-preset slow")
else:
ffmpeg_command.append("-c:v libx264")
ffmpeg_command.append("-crf 24")
ffmpeg_command.append("-preset ultrafast")
# TODO: make sure the output colors are not messed up with this
# shadowplay color range: Limited
... | rn True
| conditional_block | |
test_malloc.py |
check_malloc_removed = classmethod(check_malloc_removed)
def check(self, fn, signature, args, expected_result, must_be_removed=True,
inline=None):
remover = self.MallocRemover()
t = TranslationContext()
t.buildannotator().build_types(fn, signature)
t.buildrtyper()... | (self):
T = lltype.GcStruct('T', ('z', lltype.Signed))
S = lltype.GcStruct('S', ('t', T),
('x', lltype.Signed),
('y', lltype.Signed))
def fn():
s = lltype.malloc(S)
s.x = 10
s.t.z = 1
... | test_direct_fieldptr_2 | identifier_name |
test_malloc.py |
check_malloc_removed = classmethod(check_malloc_removed)
def check(self, fn, signature, args, expected_result, must_be_removed=True,
inline=None):
remover = self.MallocRemover()
t = TranslationContext()
t.buildannotator().build_types(fn, signature)
t.buildrtyper()... |
class B(A):
pass
def fn4(i):
a = A()
b = B()
a.b = b
b.i = i
return a.b.i
self.check(fn4, [int], [42], 42)
def test_fn5(self):
class A:
attr = 666
class B(A):
attr = 42
d... | pass | identifier_body |
test_malloc.py | from rpython.conftest import option
class TestMallocRemoval(object):
MallocRemover = LLTypeMallocRemover
def check_malloc_removed(cls, graph):
remover = cls.MallocRemover()
checkgraph(graph)
count1 = count2 = 0
for node in graph.iterblocks():
for op in node.oper... | random_line_split | ||
test_malloc.py |
check_malloc_removed = classmethod(check_malloc_removed)
def check(self, fn, signature, args, expected_result, must_be_removed=True,
inline=None):
remover = self.MallocRemover()
t = TranslationContext()
t.buildannotator().build_types(fn, signature)
t.buildrtyper()... |
s, d = t
return s*d
self.check(fn1, [int, int], [15, 10], 125)
def test_fn2(self):
class T:
pass
def fn2(x, y):
t = T()
t.x = x
t.y = y
if x > 0:
return t.x + t.y
else:
... | t = x-y, x+y | conditional_block |
core.rs | Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSink, SplitStream};
use f... | (&self, uri: &str) -> TSWebsocketStream {
let ws_stream = match websocket::Connection::new(uri).connect().await {
Ok(ws_stream) => {
info!("* connected to local websocket server at {}", uri);
ws_stream
}
Err(WebsocketConnectionError::Connection... | connect_websocket | identifier_name |
core.rs | Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSink, SplitStream};
use f... | return_address,
),
Request::Send(conn_id, data, closed) => {
self.handle_proxy_send(controller_sender, conn_id, data, closed)
}
}
}
/// Start all subsystems
pub async fn run(&mut self) {
let websocket_stream = self.connect... | {
// try to treat each received mix message as a service provider request
let deserialized_request = match Request::try_from_bytes(raw_request) {
Ok(request) => request,
Err(err) => {
error!("Failed to deserialized received request! - {}", err);
re... | identifier_body |
core.rs | Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::allowed_hosts::{HostsStore, OutboundRequestFilter};
use crate::connection::Connection;
use crate::websocket;
use crate::websocket::TSWebsocketStream;
use futures::channel::mpsc;
use futures::stream::{SplitSink, SplitStream};
use f... | mut mix_reader: mpsc::UnboundedReceiver<(Response, Recipient)>,
) {
// TODO: wire SURBs in here once they're available
while let Some((response, return_address)) = mix_reader.next().await {
// make 'request' to native-websocket client
let response_message = ClientRequ... | mut websocket_writer: SplitSink<TSWebsocketStream, Message>, | random_line_split |
App.js | from '@material-ui/icons/ChevronLeft';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import AccountCircle from '@material-ui/icons/AccountCircle';
import NotificationsIcon from '@material-ui/icons/Notifications';
import ArrowDropDownIcon from '@material-ui/icons/Ar... |
let theme = createMuiTheme({
palette: {
primary: {
light: '#63ccff',
main: '#009be5',
dark: '#006db3',
},
},
typography: {
h5: {
fontWeight: 500,
fontSize: 26,
letterSpacing: 0.5,
},
},
shape: {
borderRadius: 8,
},
props: {
MuiTab: {
disab... | import Registro_Operador from './components/formularios/Registro_Operador.js';
import Registro_Cosechadora from './components/formularios/Registro_Cosechadora.js'; | random_line_split |
App.js | '@material-ui/icons/ChevronLeft';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import AccountCircle from '@material-ui/icons/AccountCircle';
import NotificationsIcon from '@material-ui/icons/Notifications';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDr... |
return (
<ThemeProvider theme={theme}>
<Router>
<div className={classes.root}>
<CssBaseline />
<AppBar position="absolute" color ="#fafafa" className={clsx(classes.appBar, open && classes.appBarShift)}>
<Toolbar className={classes.toolbar}>
<IconButton
... |
const classes = useStyles();
const [auth] = React.useState(true);
const [open,setOpen]= React.useState(true);
const [anchorEl,setAnchorEl] = React.useState(null);
const op = Boolean(anchorEl);
const handleMenu = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
se... | identifier_body |
App.js | '@material-ui/icons/ChevronLeft';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import AccountCircle from '@material-ui/icons/AccountCircle';
import NotificationsIcon from '@material-ui/icons/Notifications';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDr... | props) {
const classes = useStyles();
const [auth] = React.useState(true);
const [open,setOpen]= React.useState(true);
const [anchorEl,setAnchorEl] = React.useState(null);
const op = Boolean(anchorEl);
const handleMenu = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => ... | pp( | identifier_name |
sound.go | loop := int((ch.SndCnt.Value >> 27) & 3)
if ch.SndCnt.Value&(1<<15) != 0 {
panic("hold")
}
v.on = false // will put true at the end of the function, if no error
v.mem = ptr[:length]
v.pos = 0
v.delay = 3
v.tmr = uint32(ch.SndTmr.Value)
v.mode = mode
v.loop = loop
var sum uint64
switch v.mode {
case kM... | idx int, old, new uint8) {
if (old^new)&(1<<7) != 0 {
if new&(1<<7) != 0 {
snd.startCapture(idx, new)
} else {
snd.stopCapture(idx, new)
}
}
}
func (snd *HwSound) startCapture(idx int, cnt uint8) {
cap := &snd.capture[idx]
cap.on = true
cap.loop = cnt&(1<<2) == 0
cap.bit8 = cnt&(1<<3) != 0
cap.singl... | riteSNDCAPCNT( | identifier_name |
sound.go |
snd.capture[0].regdad = &snd.SndCap0Dad.Value
snd.capture[1].regdad = &snd.SndCap1Dad.Value
snd.capture[0].reglen = &snd.SndCap0Len.Value
snd.capture[1].reglen = &snd.SndCap1Len.Value
hwio.MustInitRegs(snd)
return snd
}
func (ch *HwSoundChannel) WriteSNDCNT(old, new uint32) {
if (old^new)&(1<<31) != 0 {
if n... | {
hwio.MustInitRegs(&snd.Ch[i])
snd.Ch[i].snd = snd
snd.Ch[i].idx = i
} | conditional_block | |
sound.go | 0x003C, 0x0042,
0x0049, 0x0050, 0x0058, 0x0061, 0x006B, 0x0076, 0x0082, 0x008F, 0x009D, 0x00AD, 0x00BE, 0x00D1,
0x00E6, 0x00FD, 0x0117, 0x0133, 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE, 0x0220, 0x0256, 0x0292,
0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E, 0x0502, 0x0583, 0x0610, 0x06AB, 0x0756, 0x0812,
0x08E0,... | hw.SCANCODE_3,
hw.SCANCODE_4,
hw.SCANCODE_5,
hw.SCANCODE_6, | random_line_split | |
sound.go | 8]int16{-1, -1, -1, -1, 2, 4, 6, 8}
adpcmTable = [89]uint16{
0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x0010, 0x0011, 0x0013, 0x0015,
0x0017, 0x0019, 0x001C, 0x001F, 0x0022, 0x0025, 0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042,
0x0049, 0x0050, 0x0058, 0x0061, 0x006B, 0x0076, 0x0082,... |
for i := 0; i < len(buf); i += 2 {
l, r := snd.step()
// Extend to 16-bit range
l = l<<6 | l>>4
r = r<<6 | r>>4
buf[i] = int16(l - 0x8000)
buf[i+1] = int16(r - 0x8000)
}
}
| identifier_body | |
nav_loc_vqa_rl_loader.py | start, len(self.all_houses)))
# Load envs
start = time.time()
self.env_loaded = {}
for i in range(len(self.all_houses)):
print('[%02d/%d][split:%s][gpu:%d][house:%s]' %
(i + 1, len(self.all_houses), self.split, self.gpu_id, self.all_houses[i].house['id']))
env = Environment(self.a... | spawn_agent | identifier_name | |
nav_loc_vqa_rl_loader.py | gpu_id,
max_threads_per_gpu,
cfg,
to_cache,
target_obj_conn_map_dir,
map_resolution,
pretrained_cnn_path,
requires_imgs=False,
question_types=['all'],
ratio=None,
... | def __init__(self, data_json, data_h5,
path_feats_dir,
path_images_dir,
split, | random_line_split | |
nav_loc_vqa_rl_loader.py | %d houses' % (time.time() - start, len(self.all_houses)))
# Load envs
start = time.time()
self.env_loaded = {}
for i in range(len(self.all_houses)):
print('[%02d/%d][split:%s][gpu:%d][house:%s]' %
(i + 1, len(self.all_houses), self.split, self.gpu_id, self.all_houses[i].house['id']))
... | data['nav_ego_imgs'] = nav_ego_imgs | conditional_block | |
nav_loc_vqa_rl_loader.py | print('%s questions loaded for type%s under split[%s].' % (len(self.questions), question_types, split))
# hid_tid_to_best_iou
self.hid_tid_to_best_iou = self.infos['hid_tid_to_best_iou'] # hid_tid --> best_iou
# load data.h5
encoded = h5py.File(data_h5, 'r')
self.encoded_questions = encoded['... |
def _check_if_all_targets_loaded(self):
print('[CHECK][Visited:%d targets][Total:%d targets]' % (len(self.img_data_cache), len(self.env_list)))
if len(self.img_data_cache) == len(self.env_list):
self.available_idx = [i for i, v in enumerate(self.env_list)]
return True
else:
return Fals... | print('[CHECK][Visited:%d envs][Total:%d envs]' % (len(self.visited_envs), len(self.env_set)))
return True if len(self.visited_envs) == len(self.env_set) else False | identifier_body |
config.rs | ared_doc: false,
span,
})
} else {
None
}
}
// Determine if a node with the given attributes should be included in this configuration.
pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
attrs.iter().all(|attr| {
// When n... | {
attr.check_name("cfg")
} | identifier_body | |
config.rs | ::OpenDelim(token::Paren))?;
let cfg = parser.parse_meta_item()?;
parser.expect(&token::Comma)?;
let lo = parser.span.lo();
let (path, tokens) = parser.parse_path_and_tokens()?;
parser.expect(&token::CloseDelim(token::Paren))?;
Ok((cfg, path, token... | fold_trait_item | identifier_name | |
config.rs | rate, sess: &ParseSess, should_test: bool, edition: Edition)
-> (ast::Crate, Features) {
let features;
{
let mut strip_unconfigured = StripUnconfigured {
should_test,
sess,
features: None,
};
let unconfigured_attrs = krate.attrs.clone(... |
pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
ast::ForeignMod {
abi: foreign_mod.abi,
items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
}
}
fn configure_variant_data(&mut self, vdata:... | } | random_line_split |
navtreeindex32.js | 2027acb372a1300":[2,0,367,1,8],
"struct_ui_transform_interface_1_1_rect_points.html#a15903c70e62a24d7a1191e8d75a8f779":[2,0,367,1,2],
"struct_ui_transform_interface_1_1_rect_points.html#a19297746a907c54dd19d40177567e7ae":[2,0,367,1,4],
"struct_ui_transform_interface_1_1_rect_points.html#a483b7c8841920a46241bd6192a6d428... | "struct_viewport_helpers_1_1_element_edges.html#a972c7643a8ed0c49d05c0b789322338b":[2,0,9,0,7],
"struct_viewport_helpers_1_1_element_edges.html#a98be7c1a5536e868337c72dce24c59d4":[2,0,9,0,12],
"struct_viewport_helpers_1_1_element_edges.html#aa258e044d2dd1fa6fc74b11242953918":[2,0,9,0,0], | random_line_split | |
proxyDetect.go | config file
}
// minion has combined auth key "proxyAuth".
var minionProxyKeys = ProxyConfig{
proxyHost: "proxy",
proxyUser: "proxyAuth",
}
var phpProxyKeys = ProxyConfig{
proxyHost: "newrelic.daemon.proxy",
}
var httpsProxyKeys = []string{
"HTTP_PROXY",
"HTTPS_PROXY",
}
// BaseConfigProxyDetect - Primary tas... |
func getProxyConfig(validations []ValidateElement, options tasks.Options, upstream map[string]tasks.Result) (ProxyConfig, error) {
proxyConfig := findProxyValuesFromEnvVars(upstream)
for _, validation := range validations { // Go through each config file validation to see if the proxy is configured anywhere in th... | {
for _, httpsProxyKey := range httpsProxyKeys {
httpsProxyVal := os.Getenv(httpsProxyKey)
if httpsProxyVal != "" {
return httpsProxyKey, httpsProxyVal
}
}
return "", ""
} | identifier_body |
proxyDetect.go | config file
}
// minion has combined auth key "proxyAuth".
var minionProxyKeys = ProxyConfig{
proxyHost: "proxy",
proxyUser: "proxyAuth",
}
var phpProxyKeys = ProxyConfig{
proxyHost: "newrelic.daemon.proxy",
}
var httpsProxyKeys = []string{
"HTTP_PROXY",
"HTTPS_PROXY",
}
// BaseConfigProxyDetect - Primary tas... | (options tasks.Options, upstream map[string]tasks.Result) tasks.Result {
//check if the customer has http_proxy or https_proxy in their environment. If they don't, later we'll set the env var using the proxy values found via newrelic proxy settings; this is env var will allow us to connect nrdiag to newrelic and uplo... | Execute | identifier_name |
proxyDetect.go | config file
}
// minion has combined auth key "proxyAuth".
var minionProxyKeys = ProxyConfig{
proxyHost: "proxy",
proxyUser: "proxyAuth",
}
var phpProxyKeys = ProxyConfig{
proxyHost: "newrelic.daemon.proxy",
}
var httpsProxyKeys = []string{
"HTTP_PROXY",
"HTTPS_PROXY",
}
// BaseConfigProxyDetect - Primary tas... |
//build the URL by putting together all the proxy setting values they have used
var proxyURL string
if proxy.proxyUser != "" {
proxyURL += proxy.proxyUser
//No password found case for combined auth in single key (e.g. private minion's proxyAuth)
if proxy.proxyPassword != "" {
proxyURL += ":" + proxy.proxyP... | {
return proxy.proxyURL
} | conditional_block |
proxyDetect.go | auth key "proxyAuth".
var minionProxyKeys = ProxyConfig{
proxyHost: "proxy",
proxyUser: "proxyAuth",
}
var phpProxyKeys = ProxyConfig{
proxyHost: "newrelic.daemon.proxy",
}
var httpsProxyKeys = []string{
"HTTP_PROXY",
"HTTPS_PROXY",
}
// BaseConfigProxyDetect - Primary task to search for and find config file. ... | random_line_split | ||
login.rs | 003,
/// 2012, 2014, 2016
SqlServerN = 0x74000004,
}
}
bitflags! {
pub struct LoginOptionFlags1: u8 {
const BIG_ENDIAN = 0b00000001;
/// Charset_EBDDIC, default/bit not set = Charset_ASCII
const CHARSET_EBDDIC = 0b00000010;
/// default float is IE... |
}
/// the login packet
pub struct LoginMessage<'a> {
/// the highest TDS version the client supports
pub tds_version: FeatureLevel,
/// the requested packet size
pub packet_size: u32,
/// the version of the interface library
pub client_prog_ver: u32,
/// the process id of the client applic... | {
if self as u8 >= FeatureLevel::SqlServer2005 as u8 {
8
} else {
4
}
} | identifier_body |
login.rs | 00000010;
/// default float is IEEE_754
const FLOAT_VAX = 0b00000100;
const FLOAT_ND5000 = 0b00001000;
const DUMPLOAD_ON = 0b00010000;
/// Set if the client requires warning messages on execution of the USE SQL
/// statement. If this flag is NO... | {
0
} | conditional_block | |
login.rs | 003,
/// 2012, 2014, 2016
SqlServerN = 0x74000004,
}
}
bitflags! {
pub struct LoginOptionFlags1: u8 {
const BIG_ENDIAN = 0b00000001;
/// Charset_EBDDIC, default/bit not set = Charset_ASCII
const CHARSET_EBDDIC = 0b00000010;
/// default float is IE... | (self) -> u8 {
if self as u8 >= FeatureLevel::SqlServer2005 as u8 {
8
} else {
4
}
}
}
/// the login packet
pub struct LoginMessage<'a> {
/// the highest TDS version the client supports
pub tds_version: FeatureLevel,
/// the requested packet size
pub ... | done_row_count_bytes | identifier_name |
login.rs | 6
SqlServerN = 0x74000004,
}
}
bitflags! {
pub struct LoginOptionFlags1: u8 {
const BIG_ENDIAN = 0b00000001;
/// Charset_EBDDIC, default/bit not set = Charset_ASCII
const CHARSET_EBDDIC = 0b00000010;
/// default float is IEEE_754
const FLOAT_VAX ... | cursor.write_u16::<LittleEndian>(data_offset as u16)?;
| random_line_split | |
vdpa.rs | Vdpa {
fd: OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_CLOEXEC | libc::O_NONBLOCK)
.open(path)
.map_err(Error::VhostOpen)?,
mem,
backend_features_acked: 0,
})
}
}
impl<A... | (&self) -> u64 {
self.backend_features_acked
}
fn set_backend_features_acked(&mut self, features: u64) {
self.backend_features_acked = features;
}
}
#[cfg(test)]
mod tests {
const VHOST_VDPA_PATH: &str = "/dev/vhost-vdpa-0";
use std::alloc::{alloc, dealloc, Layout};
use vm_mem... | get_backend_features_acked | identifier_name |
vdpa.rs | fn set_config(&self, offset: u32, buffer: &[u8]) -> Result<()> {
let mut config = VhostVdpaConfig::new(buffer.len())
.map_err(|_| Error::IoctlError(IOError::from_raw_os_error(libc::ENOMEM)))?;
config.as_mut_fam_struct().off = offset;
config.as_mut_slice().copy_from_slice(buffer);
... | random_line_split | ||
vdpa.rs | Vdpa {
fd: OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_CLOEXEC | libc::O_NONBLOCK)
.open(path)
.map_err(Error::VhostOpen)?,
mem,
backend_features_acked: 0,
})
}
}
impl<A... |
}
impl<AS: GuestAddressSpace> AsRawFd for VhostKernVdpa<AS> {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}
impl<AS: GuestAddressSpace> VhostKernFeatures for VhostKernVdpa<AS> {
fn get_backend_features_acked(&self) -> u64 {
self.backend_features_acked
}
fn set_backend_fe... | {
&self.mem
} | identifier_body |
functions.py | Initializer(im_ref, im_mov, sitk.ScaleSkewVersor3DTransform(),
sitk.CenteredTransformInitializerFilter.MOMENTS)
# Initialize registration
lin_transformation = sitk.ImageRegistrationMethod()
# Set metrics
lin_transformation.SetMetricAsMea... | (im_ref, im_mov, trafo, show_parameters=False):
# Perform registration (Executes it)
transf = trafo.Execute(sitk.Cast(im_ref, sitk.sitkFloat32), sitk.Cast(im_mov, sitk.sitkFloat32))
if show_parameters:
print(transf)
print("--------")
print("Optimizer stop condition: {0}".form... | apply_transf | identifier_name |
functions.py | Initializer(im_ref, im_mov, sitk.ScaleSkewVersor3DTransform(),
sitk.CenteredTransformInitializerFilter.MOMENTS)
# Initialize registration
lin_transformation = sitk.ImageRegistrationMethod()
# Set metrics
lin_transformation.SetMetricAsMea... |
# Creating a list which contains the indexes of intersecting voxels
intersection_list = list(set(image_list[0]) | set(image_list[1]) | set(image_list[2]))
# Sorting the list
intersection_list.sort()
# Fetches array from image
image_array = sitk.GetArrayFromImage(common_img)
# C... | for j in range(i + 1, len(seg)):
arr1 = np.transpose(np.nonzero(seg[i]))
arr2 = np.transpose(np.nonzero(seg[j]))
# Filling two lists
arr1list = [tuple(e) for e in arr1.tolist()]
arr2list = [tuple(e) for e in arr2.tolist()]
# Sorting both ... | conditional_block |
functions.py | Initializer(im_ref, im_mov, sitk.ScaleSkewVersor3DTransform(),
sitk.CenteredTransformInitializerFilter.MOMENTS)
# Initialize registration
lin_transformation = sitk.ImageRegistrationMethod()
# Set metrics
lin_transformation.SetMetricAsMea... | # # MAJORITY VOTING # #
for i in range(len(seg)):
for j in range(i + 1, len(seg)):
arr1 = np.transpose(np.nonzero(seg[i]))
arr2 = np.transpose(np.nonzero(seg[j]))
# Filling two lists
arr1list = [tuple(e) for e in arr1.tolist()]
arr2lis... | seg = []
image_list = []
# # REGISTRATION # #
for i in range(len(ct_list)):
# Adjusting the settings and applying
trafo_settings = est_lin_transf(common_img, ct_list[i], mov_mask=seg_list[i], show_parameters=False)
final_trafo = apply_transf(common_img, ct_list[i], trafo_sett... | identifier_body |
functions.py | Initializer(im_ref, im_mov, sitk.ScaleSkewVersor3DTransform(),
sitk.CenteredTransformInitializerFilter.MOMENTS)
# Initialize registration
lin_transformation = sitk.ImageRegistrationMethod()
# Set metrics
lin_transformation.SetMetricAsMea... | # Fetching the distances and appending to distance list
# Jaccard coef.
jaccard = overlap.GetJaccardCoefficient()
# Dice coef.
dice = overlap.GetDiceCoefficient()
# Hausdorff distance
hausdorff_distance = hausdorff.GetHausdorffDistance()
# Printing out the distances for user... |
# Execute filters
hausdorff.Execute(mask_img, seg_img)
overlap.Execute(mask_img, seg_img)
| random_line_split |
sqlite.go | // Ensure every transaction returns its connection via Commit() or Rollback()
// Note that Rows.Close() can be called multiple times safely,
// so do not fear calling it where it might not be necessary.
const (
backupDB = iota
rotateDB
)
const (
// create directory for sqlite db file due to sqlite sync by director... | // To prevent this:
// Ensure you Scan() every Row object
// Ensure you either Close() or fully-iterate via Next() every Rows object | random_line_split | |
sqlite.go | message) ;`
)
var (
ErrDbPathIsAFile = "%s is an existing file"
ErrDbClosed = errors.New("DB is closed")
)
var actor_schema = `
CREATE TABLE if not exists actor(
uuid text PRIMARY KEY,
name text,
start_time text,
end_time text
);
`
var log_schema = `
CREATE TABLE if not exists log(
seq INTE... |
rating := make(chan struct{}, 1)
selectSql := `SELECT seq, time, message FROM log ORDER BY seq LIMIT ? ;`
deleteSql := `DELETE FROM log WHERE seq <= ? ;`
selectCnt := `SELECT COUNT(*) FROM log ;`
runner := func() {
defer func() {
<-rating
}()
var rowCnt int
tx, err := db.BeginTxx(ctx, nil)
if er... | {
l.Logger.Error(
"rotate error",
zap.String("service", serviceName),
zap.String("actor", name),
zap.String("uuid", uuid),
zap.String("error", fmt.Sprintf(
"rotate period is invalid: %d", period)),
)
return
} | conditional_block |
sqlite.go | message) ;`
)
var (
ErrDbPathIsAFile = "%s is an existing file"
ErrDbClosed = errors.New("DB is closed")
)
var actor_schema = `
CREATE TABLE if not exists actor(
uuid text PRIMARY KEY,
name text,
start_time text,
end_time text
);
`
var log_schema = `
CREATE TABLE if not exists log(
seq INTE... | return nil, fmt.Errorf(ErrDbPathIsAFile, dbPath)
}
var dbFile string
gpattern := `%s_%s_*.db`
rpattern := `%s_%s_(?P<SEQ>\d+).db`
switch dbType {
case backupDB:
dbFile = path.Join(dbPath, fmt.Sprintf("%s_%s.db", name, uuid))
case rotateDB:
dbFiles := path.Join(dbPath, fmt.Sprintf(gpattern, name, uuid))
... | {
var dbPath string
currentDir, _ := os.Getwd()
switch dbType {
case backupDB:
dbPath = path.Join(currentDir, backupDir)
case rotateDB:
dbPath = path.Join(currentDir, rotateDir)
default:
dbPath = path.Join(currentDir, backupDir)
}
if fi, err := os.Stat(dbPath); err != nil {
if err := os.Mkdir(dbPath,... | identifier_body |
sqlite.go | seq INTEGER PRIMARY KEY ASC,
time text,
message text
);
`
// database ORM types
type (
message struct {
Msg string `json:"message"`
}
actor struct {
Uuid string `db:"uuid"`
Name string `db:"name"`
Stime string `db:"start_time"`
Etime string `db:"end_time"`
}
log struct {
Seq int `db:"... | Insert | identifier_name | |
lib.rs | {
#[wasm_bindgen(skip)]
pub prefix: String,
pub version: NoteVersion,
#[wasm_bindgen(skip)]
pub token_symbol: String,
pub group_id: u32,
pub block_number: Option<u32>,
#[wasm_bindgen(skip)]
pub r: Scalar,
#[wasm_bindgen(skip)]
pub nullifier: Scalar,
}
#[wasm_bindgen]
pub struct ZkProof {
#[wasm_bindgen(sk... |
};
if note_val.len() != 128 {
return Err(OpStatusCode::InvalidNoteSecrets);
}
let r = hex::decode(¬e_val[..64])
.map(|v| v.try_into())
.map(|r| r.map(Scalar::from_bytes_mod_order))
.map_err(|_| OpStatusCode::InvalidHexLength)?
.map_err(|_| OpStatusCode::HexParsingFailed)?;
let nullifier = ... | {
let bn = parts[4].parse().map_err(|_| OpStatusCode::InvalidNoteBlockNumber)?;
(Some(bn), parts[5])
} | conditional_block |
lib.rs | {
#[wasm_bindgen(skip)]
pub prefix: String,
pub version: NoteVersion,
#[wasm_bindgen(skip)]
pub token_symbol: String,
pub group_id: u32,
pub block_number: Option<u32>,
#[wasm_bindgen(skip)]
pub r: Scalar,
#[wasm_bindgen(skip)]
pub nullifier: Scalar,
}
#[wasm_bindgen]
pub struct ZkProof {
#[wasm_bindgen(sk... | (opts: PoseidonHasherOptions) -> Self {
let pc_gens = PedersenGens::default();
let bp_gens = opts
.bp_gens
.clone()
.unwrap_or_else(|| BulletproofGens::new(BULLETPROOF_GENS_SIZE, 1));
let inner = PoseidonBuilder::new(opts.width)
.sbox(PoseidonSbox::Exponentiation3)
.bulletproof_gens(bp_gens)
.p... | with_options | identifier_name |
lib.rs | {
#[wasm_bindgen(skip)]
pub prefix: String,
pub version: NoteVersion,
#[wasm_bindgen(skip)]
pub token_symbol: String,
pub group_id: u32,
pub block_number: Option<u32>,
#[wasm_bindgen(skip)]
pub r: Scalar,
#[wasm_bindgen(skip)]
pub nullifier: Scalar,
}
#[wasm_bindgen]
pub struct ZkProof {
#[wasm_bindgen(sk... |
pub fn hash(&self, left: Uint8Array, right: Uint8Array) -> Result<Uint8Array, JsValue> {
let xl = ScalarWrapper::try_from(left)?;
let xr = ScalarWrapper::try_from(right)?;
let hash = Poseidon_hash_2(*xl, *xr, &self.inner);
Ok(ScalarWrapper(hash).into())
}
}
#[wasm_bind | {
let pc_gens = PedersenGens::default();
let bp_gens = opts
.bp_gens
.clone()
.unwrap_or_else(|| BulletproofGens::new(BULLETPROOF_GENS_SIZE, 1));
let inner = PoseidonBuilder::new(opts.width)
.sbox(PoseidonSbox::Exponentiation3)
.bulletproof_gens(bp_gens)
.pedersen_gens(pc_gens)
.build();
S... | identifier_body |
lib.rs | {
#[wasm_bindgen(skip)]
pub prefix: String,
pub version: NoteVersion,
#[wasm_bindgen(skip)]
pub token_symbol: String,
pub group_id: u32,
pub block_number: Option<u32>,
#[wasm_bindgen(skip)]
pub r: Scalar,
#[wasm_bindgen(skip)]
pub nullifier: Scalar,
}
#[wasm_bindgen]
pub struct ZkProof {
#[wasm_bindgen(sk... | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NoteVersion::V1 => write!(f, "v1"),
}
}
}
impl FromStr for NoteVersion {
type Err = OpStatusCode;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"v1" => Ok(NoteVersion::V1),
_ => Err(OpStatusCode::InvalidNoteVersio... |
impl fmt::Display for NoteVersion { | random_line_split |
aggr.rs | , argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::Printer;
use crossbeam::{Receiver, bounded, unbounded, Sender};
use crate::util::thread::{handle, build};
struct Aggregation {
idx: usize,
name: String,
command: Closure,
}
pub str... | (config: Config, printer: &Printer, env: &Env, mut input: impl Readable, uninitialized_output: ValueSender) -> JobResult<()> {
let (writer_output, writer_input) = bounded::<Row>(16);
let mut output_names = input.get_type().iter().map(|t| t.name.clone()).collect::<Vec<Option<String>>>();
output_names.remove... | run | identifier_name |
aggr.rs | , argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::Printer;
use crossbeam::{Receiver, bounded, unbounded, Sender};
use crate::util::thread::{handle, build};
struct Aggregation {
idx: usize,
name: String,
command: Closure,
}
pub str... | }))
}
pub fn pump_table(
job_output: &mut impl Readable,
outputs: Vec<OutputStream>,
output_definition: &Vec<(String, usize, Closure)>) -> JobResult<()> {
let stream_to_column_mapping = output_definition.iter().map(|(_, off, _)| *off).collect::<Vec<usize>>();
loop {
match job_outpu... | Ok(()) | random_line_split |
obj_io_tracing_on.go | traces;
// they maintain internal buffers of events which get flushed to the buffered
// channel when they get full. This allows for minimal synchronization per IO
// (as for most of these structures, an instance only allows a single IO at a
// time).
type Tracer struct {
fs vfs.FS
fsDir string
handleID atomic.... | (ctx context.Context, offset, size int64) {
rh.g.add(ctx, Event{
Op: RecordCacheHitOp,
FileNum: rh.fileNum,
HandleID: rh.handleID,
Offset: offset,
Size: size,
})
rh.rh.RecordCacheHit(ctx, offset, size)
}
type ctxInfo struct {
reason Reason
blockType BlockType
levelPlusOne uint8
}
... | RecordCacheHit | identifier_name |
obj_io_tracing_on.go | traces;
// they maintain internal buffers of events which get flushed to the buffered
// channel when they get full. This allows for minimal synchronization per IO
// (as for most of these structures, an instance only allows a single IO at a
// time).
type Tracer struct {
fs vfs.FS
fsDir string
handleID atomic.... | w: w,
fileNum: fileNum,
g: makeEventGenerator(ctx, t),
}
}
type writable struct {
w objstorage.Writable
fileNum base.FileNum
curOffset int64
g eventGenerator
}
var _ objstorage.Writable = (*writable)(nil)
// Write is part of the objstorage.Writable interface.
func (w *writabl... | // events.
func (t *Tracer) WrapWritable(
ctx context.Context, w objstorage.Writable, fileNum base.FileNum,
) objstorage.Writable {
return &writable{ | random_line_split |
obj_io_tracing_on.go | .fileNum,
Offset: w.curOffset,
Size: int64(len(p)),
})
// If w.w.Write(p) returns an error, a new writable
// will be used, so even tho all of p may not have
// been written to the underlying "file", it is okay
// to add len(p) to curOffset.
w.curOffset += int64(len(p))
return w.w.Write(p)
}
// Finish i... | {
panic(err)
} | conditional_block | |
obj_io_tracing_on.go | ;
// they maintain internal buffers of events which get flushed to the buffered
// channel when they get full. This allows for minimal synchronization per IO
// (as for most of these structures, an instance only allows a single IO at a
// time).
type Tracer struct {
fs vfs.FS
fsDir string
handleID atomic.Uint64
... |
// Size is part of the objstorage.Readable interface.
func (r *readable) Size() int64 {
return r.r.Size()
}
// NewReadHandle is part of the objstorage.Readable interface.
func (r *readable) NewReadHandle(ctx context.Context) objstorage.ReadHandle {
// It's safe to get the tracer from the generator without the mute... | {
r.mu.g.flush()
return r.r.Close()
} | identifier_body |
process.py | err = ''
sys.__stdout__.write("({}) {} {}".format(os.getpid(), msg, err)+'\n')
sys.__stdout__.flush()
class ProcessLogger(object):
"""
I am used by LoggingDaemonlessPool to get crash output out to the logger,
instead of having process crashes be silent
"""
def __init__(self, callable):
... |
def _repopulate_pool(self):
"""
Bring the number of pool processes up to the specified number, for use
after reaping workers which have exited.
"""
for i in range(self._processes - len(self._pool)):
w = self.Process(target=worker,
ar... | self._finalizer = finalizer
self._finalargs = finalargs
super(LoggingDaemonlessPool, self).__init__(processes, initializer,
initargs, maxtasksperchild) | identifier_body |
process.py | err = ''
sys.__stdout__.write("({}) {} {}".format(os.getpid(), msg, err)+'\n')
sys.__stdout__.flush()
class ProcessLogger(object):
"""
I am used by LoggingDaemonlessPool to get crash output out to the logger,
instead of having process crashes be silent
"""
def __init__(self, callable):
... | (Exception): # pragma: no cover
def __init__(self, tb):
self.tb = tb
def __str__(self):
return self.tb
# Unmodified (see above)
class ExceptionWithTraceback: # pragma: no cover
def __init__(self, exc, tb):
tb = traceback.format_exception(type(exc), exc, tb)
tb = ''.join(... | RemoteTraceback | identifier_name |
process.py | err = ''
sys.__stdout__.write("({}) {} {}".format(os.getpid(), msg, err)+'\n')
sys.__stdout__.flush()
class ProcessLogger(object):
"""
I am used by LoggingDaemonlessPool to get crash output out to the logger,
instead of having process crashes be silent
"""
def __init__(self, callable):
... | self.exc = exc
self.tb = '\n"""\n%s"""' % tb
def __reduce__(self):
return rebuild_exc, (self.exc, self.tb)
# Unmodified (see above)
def rebuild_exc(exc, tb): # pragma: no cover
exc.__cause__ = RemoteTraceback(tb)
return exc
multiprocessing.pool.worker = worker
# END of Worker Fi... | tb = traceback.format_exception(type(exc), exc, tb)
tb = ''.join(tb) | random_line_split |
process.py | # Re-raise the original exception so the Pool worker can
# clean up
raise
# It was fine, give a normal answer
return result
class DaemonlessProcess(multiprocessing.Process):
"""
I am used by LoggingDaemonlessPool to make pool workers NOT run in
daemon m... | try:
test.run(result)
# If your class setUpClass(self) method crashes, the test doesn't
# raise an exception, but it does add an entry to errors. Some
# other things add entries to errors as well, but they all call the
# finalize callback.
if resu... | conditional_block | |
disp_surf_calc.py | np.conj(e_x) + e_y * np.conj(e_y))
e_tot = np.sqrt(e_x * np.conj(e_x) + e_y * np.conj(e_y) + e_z ** 2)
e_pol = -2 * np.imag(e_x * np.conj(e_y)) / e_per ** 2
return e_x, e_y, e_z, e_per, e_tot, e_pol
def _calc_b(kc_x_mat, kc_z_mat, w_final, e_x, e_y, e_z):
b_x = -kc_z_mat * e_y / w_final
b_y = (k... | (kc_x_mat, kc_z_mat, w_final, v_ex, v_ez, v_ix, v_iz):
dn_e_n = (kc_x_mat * v_ex + kc_z_mat * v_ez) / w_final
dn_e_n = np.sqrt(dn_e_n * np.conj(dn_e_n))
dn_i_n = (kc_x_mat * v_ix + kc_z_mat * v_iz) / w_final
dn_i_n = np.sqrt(dn_i_n * np.conj(dn_i_n))
dne_dni = dn_e_n / dn_i_n
return dn_e_n, dn_... | _calc_continuity | identifier_name |
disp_surf_calc.py | * np.conj(e_x) + e_y * np.conj(e_y))
e_tot = np.sqrt(e_x * np.conj(e_x) + e_y * np.conj(e_y) + e_z ** 2)
e_pol = -2 * np.imag(e_x * np.conj(e_y)) / e_per ** 2
return e_x, e_y, e_z, e_per, e_tot, e_pol
def _calc_b(kc_x_mat, kc_z_mat, w_final, e_x, e_y, e_z):
b_x = -kc_z_mat * e_y / w_final
b_y = ... | s_y = e_z * np.conj(b_x) - e_x * np.conj(b_z)
s_z = e_x * np.conj(b_y) - e_y * np.conj(b_x)
s_par = np.abs(s_z)
s_tot = np.sqrt(s_x * np.conj(s_x) + s_y * np.conj(s_y)
+ s_z * np.conj(s_z))
return s_par, s_tot
def _calc_part2fields(wp_e, en_e, en_i, e_tot, b_tot):
n_e = wp... | # Poynting flux
s_x = e_y * np.conj(b_z) - e_z * np.conj(b_y) | random_line_split |
disp_surf_calc.py | * np.conj(e_x) + e_y * np.conj(e_y))
e_tot = np.sqrt(e_x * np.conj(e_x) + e_y * np.conj(e_y) + e_z ** 2)
e_pol = -2 * np.imag(e_x * np.conj(e_y)) / e_per ** 2
return e_x, e_y, e_z, e_per, e_tot, e_pol
def _calc_b(kc_x_mat, kc_z_mat, w_final, e_x, e_y, e_z):
b_x = -kc_z_mat * e_y / w_final
b_y = ... | wf_ : ndarray
Dispersion surfaces.
extra_param : dict
Extra parameters to plot.
"""
# Make vectors of the wave numbers
kc_z = np.linspace(1e-6, kc_z_max, 35)
kc_x = np.linspace(1e-6, kc_x_max, 35)
# Turn those vectors into matrices
kc_x_mat, kc_z_mat = np.meshgrid(kc_x,... | r"""Calculate the cold plasma dispersion surfaces according to equation
2.64 in Plasma Waves by Swanson (2nd ed.)
Parameters
----------
kc_x_max : float
Max value of k_perpendicular*c/w_c.
kc_z_max : float
Max value of k_parallel*c/w_c.
m_i : float
Ion mass in terms of e... | identifier_body |
disp_surf_calc.py | wf_ : ndarray
Dispersion surfaces.
extra_param : dict
Extra parameters to plot.
"""
# Make vectors of the wave numbers
kc_z = np.linspace(1e-6, kc_z_max, 35)
kc_x = np.linspace(1e-6, kc_x_max, 35)
# Turn those vectors into matrices
kc_x_mat, kc_z_mat = np.meshgrid(kc_x,... | extra_param[k] = np.transpose(np.real(v), [0, 2, 1]) | conditional_block | |
app.py | self.checkOutBtn = QtWidgets.QPushButton(self.itemBox)
self.checkOutBtn.setGeometry(QtCore.QRect(290, 140, 75, 23))
self.checkOutBtn.setObjectName("checkOutBtn")
self.checkOutBtn.clicked.connect(self.checkOutFunction)
self.noteBtn = QtWidgets.QPushButton(self.itemBox)
self.note... |
self.passLbl = QtWidgets.QLabel(self.loginBox)
self.passLbl.setGeometry(QtCore.QRect(10, 50, 47, 21))
font = QtGui.QFont()
font.setPointSize(14)
self.passLbl.setFont(font)
self.passLbl.setObjectName("passLbl")
self.msgWrong = QMessageBox()
self.msgWrong... | random_line_split | |
app.py | .noteBtn.setEnabled(False)
self.addItemBtn = QtWidgets.QPushButton(self.itemBox)
self.addItemBtn.setGeometry(QtCore.QRect(290, 50, 75, 23))
self.addItemBtn.setObjectName("addItemBtn")
self.addItemBtn.clicked.connect(self.addItemFunction)
self.tableList = [i for i in range(21)]
... | filename = os.fsdecode(file)
if filename.endswith('.json') and filename[4:6] != currentMonthStr:
os.remove("backup/"+filename) | conditional_block | |
app.py | self.userLbl.setText(_translate("Dialog", "User:"))
self.loginBtn.setText(_translate("Dialog", "Login"))
self.passLbl.setText(_translate("Dialog", "Pass:"))
self.orderButton.setText(_translate("Dialog", "Order"))
self.loadBackupFile.setText(_translate("Dialog", "Load Backup"))
... | QApp | identifier_name | |
app.py | self.checkOutBtn = QtWidgets.QPushButton(self.itemBox)
self.checkOutBtn.setGeometry(QtCore.QRect(290, 140, 75, 23))
self.checkOutBtn.setObjectName("checkOutBtn")
self.checkOutBtn.clicked.connect(self.checkOutFunction)
self.noteBtn = QtWidgets.QPushButton(self.itemBox)
self.note... | self.orderButton.setText(_translate("Dialog", "Order"))
self.loadBackupFile.setText(_translate("Dialog", "Load Backup"))
def addItemFunction(self):
self.addItemWindow = Ui_MainWindow()
self.itemWindow = QtWidgets.QMainWindow()
self.addItemWindow.setupUi(self.itemWindow)
... | _translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.itemBox.setTitle(_translate("Dialog", "GroupBox"))
self.checkOutBtn.setText(_translate("Dialog", "Check out"))
self.noteBtn.setText(_translate("Dialog", "Note"))
self.addItem... | identifier_body |
sqlzooHack.py | the charList (wildCards is True), _ will be substituted in since it matches every single character.
otherwise, if no characters match, that character will be skipped, and it's index is printed (e.g. Missing: 6)
Raises:
TypeError: exception
raised with ValueErrors when findChar ... | if(characterInTableName(ch, url)):
charList.append(ch)
for ch in numbers:
ch = str(ch)
if(characterInTableName(ch, url)):
charList.append(ch)
for ch in special:
ch = str(ch)
if(characterInTableName(ch, url)):
charList.append(ch)
for ch in other:
ch... | """ List of characters in table names
Args:
url: String
form url
caseSensitive: Boolean
default False
true if case sentitivity matters
wildCards: Boolean
default True
true if wildcards should be placed where no other characters match
Returns:
... | identifier_body |
sqlzooHack.py | the charList (wildCards is True), _ will be substituted in since it matches every single character.
otherwise, if no characters match, that character will be skipped, and it's index is printed (e.g. Missing: 6)
Raises:
TypeError: exception
raised with ValueErrors when findChar ... |
return name
def makeDatabaseNamesList(n, ):
""" List of database names
Args:
n: integer
max number of table names to return
Returns:
lst: list
list of up to n database names
"""
def makeListF(f, url, *argsf, caseSensitive = False, wildCards = True):
"""makeL... | for ch in lst:
if(characterInTableName(ch, url, i)):
name += ch
else:
name += "" #should only be reached if wildcards are false | conditional_block |
sqlzooHack.py | otherwise, if no characters match, that character will be skipped, and it's index is printed (e.g. Missing: 6)
Raises:
TypeError: exception
raised with ValueErrors when findChar returns i instead of an element of CharList
ValueError: exception
raised when n... | prints i iff there is no character in charList that matches at position i. also raises type and value error after printing i -- printing is handled by findChar
password: string
correct password or, if len(password) = n, first n characters of password
if no characters match a... | random_line_split | |
sqlzooHack.py | charList (wildCards is True), _ will be substituted in since it matches every single character.
otherwise, if no characters match, that character will be skipped, and it's index is printed (e.g. Missing: 6)
Raises:
TypeError: exception
raised with ValueErrors when findChar retu... | (lst, ):
name = ""
for i in range(0, n):
for ch in lst:
if(characterInTableName(ch, url, i)):
name += ch
else:
name += "" #should only be reached if wildcards are false
return name
def makeDatabaseNamesList(n, ):
""" List of database names
Args:
... | tableName | identifier_name |
bpf.rs | 32 = 0x8000_0000;
const __AUDIT_ARCH_LE: u32 = 0x4000_0000;
// These are defined in `/include/uapi/linux/audit.h`.
pub const AUDIT_ARCH_X86: u32 = EM_386 | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_X86_64: u32 = EM_X86_64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_ARM: u32 = EM_ARM | __AUDIT_ARCH_LE;
pub... |
let prog = libc::sock_fprog {
// Note: length is guaranteed to be less than `u16::MAX` because of
// the above check.
len: len as u16,
filter: self.filter.as_ptr() as *mut _,
};
let ptr = &prog as *const libc::sock_fprog;
let value = Er... | {
return Err(Errno::EINVAL);
} | conditional_block |
bpf.rs | 32 = 0x8000_0000;
const __AUDIT_ARCH_LE: u32 = 0x4000_0000;
// These are defined in `/include/uapi/linux/audit.h`.
pub const AUDIT_ARCH_X86: u32 = EM_386 | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_X86_64: u32 = EM_X86_64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_ARM: u32 = EM_ARM | __AUDIT_ARCH_LE;
pub... | (&self) -> bool {
self.filter.is_empty()
}
fn install(&self, flags: FilterFlags) -> Result<i32, Errno> {
let len = self.filter.len();
if len == 0 || len > BPF_MAXINSNS {
return Err(Errno::EINVAL);
}
let prog = libc::sock_fprog {
// Note: length ... | is_empty | identifier_name |
bpf.rs | 32 = 0x8000_0000;
const __AUDIT_ARCH_LE: u32 = 0x4000_0000;
// These are defined in `/include/uapi/linux/audit.h`.
pub const AUDIT_ARCH_X86: u32 = EM_386 | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_X86_64: u32 = EM_X86_64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_ARM: u32 = EM_ARM | __AUDIT_ARCH_LE;
pub... |
}
/// Returns a seccomp-bpf filter containing the given list of instructions.
///
/// This can be concatenated with other seccomp-BPF programs.
///
/// Note that this is not a true BPF program. Seccomp-bpf is a subset of BPF and
/// so many instructions are not available.
///
/// When executing instructions, the BPF ... | {
filter.push(self)
} | identifier_body |
bpf.rs | pub const AUDIT_ARCH_X86_64: u32 = EM_X86_64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_ARM: u32 = EM_ARM | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_AARCH64: u32 = EM_AARCH64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
pub const AUDIT_ARCH_MIPS: u32 = EM_MIPS;
pub const AUDIT_ARCH_PPC: u32 = EM_PPC;
pub cons... | const __AUDIT_ARCH_64BIT: u32 = 0x8000_0000;
const __AUDIT_ARCH_LE: u32 = 0x4000_0000;
// These are defined in `/include/uapi/linux/audit.h`.
pub const AUDIT_ARCH_X86: u32 = EM_386 | __AUDIT_ARCH_LE; | random_line_split | |
vec.rs | borrowed VarZeroVec, requiring no allocations.
///
/// If a mutating operation is invoked on VarZeroVec, the Borrowed is converted to Owned.
///
/// # Examples
///
/// ```
/// use zerovec::VarZeroVec;
///
/// let bytes = &[
/// 4, 0, 0, 0, 0, 0, 1, 0, 3, 0, 6, 0, 119, 207, 1... | es(self) - | identifier_name | |
vec.rs | "文", "𑄃"];
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Data<'a> {
/// #[serde(borrow)]
/// strings: VarZeroVec<'a, str>,
/// }
///
/// let data = Data {
/// strings: VarZeroVec::from(&strings),
/// };
///
/// let bincode_bytes =
/// bincode::serialize(&data).expect("Serializatio... | <'a, T: ?Sized, F> From<VarZeroVecOwned<T, F>> for VarZeroVec<'a, T, F> {
#[inline]
fn from(other: VarZeroVecOwned<T, F>) -> Self {
VarZeroVec::Owned(other)
}
}
impl<'a, T: ?Sized, F> From<&'a VarZeroSlice<T, F>> for VarZeroVec<'a, T, F> {
fn from(other: &'a VarZeroSlice<T, F>) -> Self {
... | VarZeroSlice::fmt(self, f)
}
}
impl | identifier_body |
vec.rs | "文", "𑄃"];
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Data<'a> {
/// #[serde(borrow)]
/// strings: VarZeroVec<'a, str>,
/// }
///
/// let data = Data {
/// strings: VarZeroVec::from(&strings),
/// };
///
/// let bincode_bytes =
/// bincode::serialize(&data).expect("Serializatio... | /// # use zerovec::ule::ZeroVecError;
/// use zerovec::ule::*;
/// use zerovec::VarZeroVec;
/// use zerovec::ZeroSlice;
/// use zerovec::ZeroVec;
///
/// // The structured list correspond to the list of integers.
/// let numbers: &[&[u32]] = &[
/// &[12, 25, 38],
/// &[39179, 100],
/// &[42, 55555],
/// ... | /// # use std::str::Utf8Error; | random_line_split |
mod.rs | mut self) -> Option<&mut dyn OwnerSolicitor<Request>>;
/// Determine the required scopes for a request.
///
/// The client must fulfill any one scope, so returning an empty slice will always deny the
/// request.
fn scopes(&mut self) -> Option<&mut dyn Scopes<Request>>;
/// Generate a prototyp... | {
self
} | identifier_body | |
mod.rs | this endpoint can access one.
///
/// Returning `None` will implicate failing any flow that requires an authorizer but does not
/// have any effect on flows that do not require one.
fn authorizer_mut(&mut self) -> Option<&mut dyn Authorizer>;
/// An issuer if this endpoint can access one.
///
... | check_consent | identifier_name | |
mod.rs | mod query;
#[cfg(test)]
mod tests;
use std::borrow::Cow;
use std::marker::PhantomData;
pub use crate::primitives::authorizer::Authorizer;
pub use crate::primitives::issuer::Issuer;
pub use crate::primitives::registrar::Registrar;
pub use crate::primitives::scope::Scope;
use crate::code_grant::resource::{Error as Re... | random_line_split | ||
lib.rs | Layer1,
/// mpeg layer-2 decoder enabled
DecodeLayer2,
/// mpeg layer-3 decoder enabled
DecodeLayer3,
/// accurate decoder rounding
DecodeAccurate,
/// downsample (sample omit)
DecodeDownsample,
/// flexible rate decoding
DecodeNtoM,
... | size | identifier_name | |
lib.rs |
// Decoder selection
pub fn mpg123_decoders() -> *const *const c_char;
pub fn mpg123_supported_decoders() -> *const *const c_char;
pub fn mpg123_decoder(handle: *mut Mpg123Handle) -> c_int;
pub fn mpg123_current_decoder(handle: *mut Mpg123Handle) -> *const c_char;
// Output format
pub fn m... | pub fn mpg123_strerror(handle: *mut Mpg123Handle) -> *const c_char;
pub fn mpg123_errcode(handle: *mut Mpg123Handle) -> Mpg123Error; | random_line_split | |
combat.rs | .
pub fn target_tile(tcod: &mut Tcod,
objects: &[Object], game: &mut Game,
max_range: Option<f32>)
-> Option<(i32, i32)> {
use tcod::input::KeyCode::Escape;
loop {
// render the screen. this erases the inventory and shows the names of
// objects ... | game.log.add(format!("The eyes of {} look vacant, as he starts to stumble around!",
objects[monster_id].name),
colors::LIGHT_GREEN);
UseResult::UsedUp
} else { // no enemy fonud within maximum range
game.log.add("No enemy is close en... | objects[monster_id].ai = Some(Ai::Confused {
previous_ai: Box::new(old_ai),
num_turns: CONFUSE_NUM_TURNS,
}); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.