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 |
|---|---|---|---|---|
index.js | import Head from 'next/head';
import Portfolio from '../components/Portfolio';
import Link from 'next/link';
export default function Home() {
return (
<div>
<Head>
<title>PublicTrades</title>
<link rel="icon" href="/favicon.ico" />
<script src="https://cdnjs.cloudflare.com/ajax/li... | </a>
</div>
<div className="mt-3 sm:mt-0 sm:ml-3">
<a href="#" className="w-full flex items-center justify-center px-8 py-3 border border-transparent text-base font-medium rounded-md text-white bg-green-700 hover:bg-green-400 md:py-4 md:text-lg md:px-10">
... | random_line_split | |
web_8_ReduceMemory.py | from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
import io
import os
import sys
import random
import pandas as pd
import numpy as np
#from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
from matplotlib.backends... | (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 | from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
import io
import os
import sys
import random
import pandas as pd
import numpy as np
#from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
from matplotlib.backends... |
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 | from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
import io
import os
import sys
import random
import pandas as pd
import numpy as np
#from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
from matplotlib.backends... |
#@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 desired space. contain ['PCA1', 'PCA2', 'desire_homo_prediction', 'desi... | 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 | from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
import io
import os
import sys
import random
import pandas as pd
import numpy as np
#from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response
from matplotlib.backends... | return (pd_desire, predict_list, opti, nei_t5, highest_desire_value_index);
@app.route("/plot_smiles/<string:smile_name>")
def plot_smiles(smile_name):
DrawingOptions.atomLabelFontSize = 5
mnm = Chem.MolFromSmiles(smile_name, sanitize=False)
fig1 = Draw.MolToMPL(mnm, fitImage=True)
#, fit... | random_line_split | |
sync-server.js | var metricsModule = require('./sync-metrics');
var ackProcessor = require('./ack-processor');
var async = require('async');
var dataHandlersModule = require('./dataHandlers');
var datasets = require('./datasets');
var defaultDataHandlersModule = require('./default-dataHandlers');
var interceptorsModule = require('./int... | (datasetId, fn) {
interceptors.setRequestInterceptor(datasetId, fn);
}
function interceptResponse(datasetId, fn) {
interceptors.setResponseInterceptor(datasetId, fn);
}
function listCollisions(datasetId, params, cb) {
debug('[%s] listCollisions', datasetId);
dataHandlers.listCollisions(datasetId, params.meta_d... | interceptRequest | identifier_name |
sync-server.js | var metricsModule = require('./sync-metrics');
var ackProcessor = require('./ack-processor');
var async = require('async');
var dataHandlersModule = require('./dataHandlers');
var datasets = require('./datasets');
var defaultDataHandlersModule = require('./default-dataHandlers');
var interceptorsModule = require('./int... |
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 | var metricsModule = require('./sync-metrics');
var ackProcessor = require('./ack-processor');
var async = require('async');
var dataHandlersModule = require('./dataHandlers');
var datasets = require('./datasets');
var defaultDataHandlersModule = require('./default-dataHandlers');
var interceptorsModule = require('./int... |
function callHandler(handlerName, args) {
dataHandlers[handlerName].apply(null, args);
}
function getStats(cb) {
metricsModule.getStats(cb);
}
module.exports = {
sync: sync,
syncRecords: syncRecords,
setClients: setClients,
api: {
init: init,
// Memoize the start function so it will only get cal... | {
debug('[%s] removeCollision');
dataHandlers.removeCollision(datasetId, params.hash, params.meta_data, cb);
} | identifier_body |
sync-server.js | var metricsModule = require('./sync-metrics');
var ackProcessor = require('./ack-processor');
var async = require('async');
var dataHandlersModule = require('./dataHandlers');
var datasets = require('./datasets');
var defaultDataHandlersModule = require('./default-dataHandlers');
var interceptorsModule = require('./int... | /**@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 | /*
// Copyright (c) 2016 Intel Corporation
//
// 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... | }
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 | /*
// Copyright (c) 2016 Intel Corporation
//
// 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... |
return int(*con.SizeRootFs / (1024 * 1024))
}
func (d *docker) stats() (disk, memory, cpu int) {
disk = d.computeInstanceDiskspace()
memory = -1
cpu = -1
if d.cfg == nil {
return
}
err := d.initDockerClient()
if err != nil {
glog.Errorf("Unable to get docker client: %v", err)
return
}
ctx, cancelF... | {
return -1
} | conditional_block |
docker.go | /*
// Copyright (c) 2016 Intel Corporation
//
// 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... |
func dockerDeleteContainer(cli containerManager, dockerID, instanceUUID string) error {
err := cli.ContainerRemove(context.Background(),
types.ContainerRemoveOptions{
ContainerID: dockerID,
Force: true})
if err != nil {
glog.Warningf("Unable to delete docker instance %s:%s err %v",
instanceUUID, ... | {
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 | /*
// Copyright (c) 2016 Intel Corporation
//
// 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... | (closedCh chan struct{}, connectedCh chan struct{},
wg *sync.WaitGroup, boot bool) chan interface{} {
if d.dockerID == "" {
idPath := path.Join(d.instanceDir, "docker-id")
data, err := ioutil.ReadFile(idPath)
if err != nil {
// We'll return an error later on in dockerConnect
glog.Errorf("Unable to read d... | monitorVM | identifier_name |
computation.go | package signalflow
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/signalfx/signalfx-go/idtool"
"github.com/signalfx/signalfx-go/signalflow/v2/messages"
)
// Computation is a single running SignalFlow job
type Computation struct {
sync.Mutex
channel <-chan messages.Message
name string
clien... | }
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 | package signalflow
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/signalfx/signalfx-go/idtool"
"github.com/signalfx/signalfx-go/signalflow/v2/messages"
)
// Computation is a single running SignalFlow job
type Computation struct {
sync.Mutex
channel <-chan messages.Message
name string
clien... |
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 {
out <- buffer[i]
}
close(out)
}()
for {
if len(buffer) > 0 {
if nextMessage == nil {
nextMessage, buffer ... | {
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 | package signalflow
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/signalfx/signalfx-go/idtool"
"github.com/signalfx/signalfx-go/signalflow/v2/messages"
)
// Computation is a single running SignalFlow job
type Computation struct {
sync.Mutex
channel <-chan messages.Message
name string
clien... |
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 | package signalflow
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/signalfx/signalfx-go/idtool"
"github.com/signalfx/signalfx-go/signalflow/v2/messages"
)
// Computation is a single running SignalFlow job
type Computation struct {
sync.Mutex
channel <-chan messages.Message
name string
clien... | (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 | import os
import sys
import re
import subprocess
import datetime
import shutil
import hashlib
# screw this old lexer
import kv_lexer as lexer
# how the awful crc checking works:
# it makes a crc for every time range, input video name, output video name, verbose, and final encode
# and dumps it all to a... | # 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 | import os
import sys
import re
import subprocess
import datetime
import shutil
import hashlib
# screw this old lexer
import kv_lexer as lexer
# how the awful crc checking works:
# it makes a crc for every time range, input video name, output video name, verbose, and final encode
# and dumps it all to a... | (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 | import os
import sys
import re
import subprocess
import datetime
import shutil
import hashlib
# screw this old lexer
import kv_lexer as lexer
# how the awful crc checking works:
# it makes a crc for every time range, input video name, output video name, verbose, and final encode
# and dumps it all to a... |
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 | import os
import sys
import re
import subprocess
import datetime
import shutil
import hashlib
# screw this old lexer
import kv_lexer as lexer
# how the awful crc checking works:
# it makes a crc for every time range, input video name, output video name, verbose, and final encode
# and dumps it all to a... | else:
valid_crcs.append( video_crc )
else:
if valid_crcs != crc_list:
if verbose:
print( " Not all Hash's validated" )
return True
return False
else:
# print("Hash File does not exist:... | rn True
| conditional_block |
test_malloc.py | import py
from rpython.translator.backendopt.malloc import LLTypeMallocRemover
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof
from rpython.translator import simplify
from rpython.flowspace.model import checkgraph, Block, mkentrym... | (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 | import py
from rpython.translator.backendopt.malloc import LLTypeMallocRemover
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof
from rpython.translator import simplify
from rpython.flowspace.model import checkgraph, Block, mkentrym... |
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 | import py
from rpython.translator.backendopt.malloc import LLTypeMallocRemover
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof
from rpython.translator import simplify
from rpython.flowspace.model import checkgraph, Block, mkentrym... | 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 | import py
from rpython.translator.backendopt.malloc import LLTypeMallocRemover
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof
from rpython.translator import simplify
from rpython.flowspace.model import checkgraph, Block, mkentrym... |
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 | // Copyright 2020 - Nym 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::{SplitSi... | (&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 | // Copyright 2020 - Nym 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::{SplitSi... |
/// Start all subsystems
pub async fn run(&mut self) {
let websocket_stream = self.connect_websocket(&self.listening_address).await;
// split the websocket so that we could read and write from separate threads
let (websocket_writer, mut websocket_reader) = websocket_stream.split();
... | {
// 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 | // Copyright 2020 - Nym 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::{SplitSi... | 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 | import './App.css';
import React from 'react';
import clsx from 'clsx';
import {grey} from '@material-ui/core/colors';
import {fade, makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Box from '@material-ui/core/Bo... |
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 | import './App.css';
import React from 'react';
import clsx from 'clsx';
import {grey} from '@material-ui/core/colors';
import {fade, makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Box from '@material-ui/core/Bo... | port default App;
|
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 | import './App.css';
import React from 'react';
import clsx from 'clsx';
import {grey} from '@material-ui/core/colors';
import {fade, makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Box from '@material-ui/core/Bo... | 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 | package main
import (
"encoding/binary"
"hash/crc64"
"ndsemu/emu"
"ndsemu/emu/hw"
"ndsemu/emu/hwio"
log "ndsemu/emu/logger"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
kLoopManual = 0
kLoopInfinite = 1
kLoopOneShot = 2
kMode8bit = 0
kMode16bit = 1
kModeAdpcm = 2
kModePsgNoise = ... | 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 | package main
import (
"encoding/binary"
"hash/crc64"
"ndsemu/emu"
"ndsemu/emu/hw"
"ndsemu/emu/hwio"
log "ndsemu/emu/logger"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
kLoopManual = 0
kLoopInfinite = 1
kLoopOneShot = 2
kMode8bit = 0
kMode16bit = 1
kModeAdpcm = 2
kModePsgNoise = ... |
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 | package main
import (
"encoding/binary"
"hash/crc64"
"ndsemu/emu"
"ndsemu/emu/hw"
"ndsemu/emu/hwio"
log "ndsemu/emu/logger"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
kLoopManual = 0
kLoopInfinite = 1
kLoopOneShot = 2
kMode8bit = 0
kMode16bit = 1
kModeAdpcm = 2
kModePsgNoise = ... | hw.SCANCODE_7,
hw.SCANCODE_8,
hw.SCANCODE_9,
}
keys := hw.GetKeyboardState()
mask := 0xFFFF
pressed := 0
for i := 0; i < len(scans); i++ {
if keys[scans[i]] != 0 {
pressed |= 1 << uint(i)
}
}
if pressed != 0 {
mask = pressed
}
for i := 0; i < 16; i++ {
var sample int64
cntrl := snd.Ch[i].... | hw.SCANCODE_3,
hw.SCANCODE_4,
hw.SCANCODE_5,
hw.SCANCODE_6, | random_line_split |
sound.go | package main
import (
"encoding/binary"
"hash/crc64"
"ndsemu/emu"
"ndsemu/emu/hw"
"ndsemu/emu/hwio"
log "ndsemu/emu/logger"
"github.com/hashicorp/golang-lru/simplelru"
)
const (
kLoopManual = 0
kLoopInfinite = 1
kLoopOneShot = 2
kMode8bit = 0
kMode16bit = 1
kModeAdpcm = 2
kModePsgNoise = ... |
func mulvol64(s int64, vol int64) int64 {
if vol == 127 {
return s
}
return (s * vol) >> 7
}
// Emulate one tick of audio, producing a couple of (unsigned) 16-bit audio samples
func (snd *HwSound) step() (uint16, uint16) {
var lmix, rmix int64
var chbuf [4]int64
// Master enable
if snd.SndGCnt.Value&(1<<15)... |
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 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import time
import h5py
import argparse
import numpy as np
import os, sys, json
import os.path as osp
import rand... | (self, min_dist, max_dist, split):
"""
Run set_target_object/room before calling this function!
Inputs:
- min_dist/max_dist: distance between target and spawned location (in connMap)
Return:
- position
- distance
"""
conn_map = self.episode_house.env.house.connMap
point_cands = ... | spawn_agent | identifier_name |
nav_loc_vqa_rl_loader.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import time
import h5py
import argparse
import numpy as np
import os, sys, json
import os.path as osp
import rand... | 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 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import time
import h5py
import argparse
import numpy as np
import os, sys, json
import os.path as osp
import rand... |
return data
def spawn_agent(self, min_dist, max_dist, split):
"""
Run set_target_object/room before calling this function!
Inputs:
- min_dist/max_dist: distance between target and spawned location (in connMap)
Return:
- position
- distance
"""
conn_map = self.episode_house.e... | data['nav_ego_imgs'] = nav_ego_imgs | conditional_block |
nav_loc_vqa_rl_loader.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import time
import h5py
import argparse
import numpy as np
import os, sys, json
import os.path as osp
import rand... |
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 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
attr.check_name("test") || attr.check_name("bench")
}
| {
attr.check_name("cfg")
} | identifier_body |
config.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
fold::noop_fold_trait_item(configure!(self, item), self)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
// Don't configure interpolated AST (c.f. #34171).
// Interpolated AST will get configured once the surroundi... | fold_trait_item | identifier_name |
config.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
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 | var NAVTREEINDEX32 =
{
"struct_ui_transform2d_interface_1_1_anchors.html#a467aa5dc8db219e4705bfd3ebfb74b9b":[2,0,365,0,6],
"struct_ui_transform2d_interface_1_1_anchors.html#a5f198bbcfd3d2472d7914065f4e22040":[2,0,365,0,0],
"struct_ui_transform2d_interface_1_1_anchors.html#a7cbc96d376a3b18d760989c04585b160":[2,0,365,0,5... | "struct_viewport_helpers_1_1_element_edges.html#ab2c76faee378c275ad1780751b797335":[2,0,9,0,8],
"struct_viewport_helpers_1_1_element_edges.html#ab30c7cf980db13a0128d228d66b37fa0":[2,0,9,0,1],
"struct_viewport_helpers_1_1_element_edges.html#abfb590c8a42ba9593ab756e27e3d5fba":[2,0,9,0,4],
"struct_viewport_helpers_1_1_ele... | "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 | package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
log "github.com/newrelic/newrelic-diagnostics-cli/logger"
"github.com/newrelic/newrelic-diagnostics-cli/tasks"
)
//ProxyConfig represents an specific proxy server settings/configuration. The processID field mostly serves a purpose for agent... |
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 | package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
log "github.com/newrelic/newrelic-diagnostics-cli/logger"
"github.com/newrelic/newrelic-diagnostics-cli/tasks"
)
//ProxyConfig represents an specific proxy server settings/configuration. The processID field mostly serves a purpose for agent... | (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 | package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
log "github.com/newrelic/newrelic-diagnostics-cli/logger"
"github.com/newrelic/newrelic-diagnostics-cli/tasks"
)
//ProxyConfig represents an specific proxy server settings/configuration. The processID field mostly serves a purpose for agent... |
//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 | package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
log "github.com/newrelic/newrelic-diagnostics-cli/logger"
"github.com/newrelic/newrelic-diagnostics-cli/tasks"
)
//ProxyConfig represents an specific proxy server settings/configuration. The processID field mostly serves a purpose for agent... | if ok {
for _, process := range processes {
for _, proxySysPropKey := range proxySysPropsKeys {
proxySysPropVal, isPresent := process.SysPropsKeyToVal[proxySysPropKey]
if isPresent {
if strings.Contains(proxySysPropKey, "host") {
proxyConfig.proxyHost = proxySysPropVal
} else if st... | random_line_split | |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... |
}
/// 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 | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | ;
cursor.write_u16::<LittleEndian>(length as u16)?;
continue;
}
// jump into the data portion of the output
let bak = cursor.position();
cursor.set_position(data_offset as u64);
for codepoint in value.encode_utf16() {
... | {
0
} | conditional_block |
login.rs | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | (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 | use super::Encode;
use bitflags::bitflags;
use byteorder::{LittleEndian, WriteBytesExt};
use bytes::BytesMut;
use io::{Cursor, Write};
use std::{borrow::Cow, io};
uint_enum! {
#[repr(u32)]
#[derive(PartialOrd)]
pub enum FeatureLevel {
SqlServerV7 = 0x70000000,
SqlServer2000 = 0x71000000,
... | // ibSSPI
if i == 10 {
let length = if let Some(ref bytes) = self.integrated_security {
let bak = cursor.position();
cursor.set_position(data_offset as u64);
cursor.write_all(bytes)?;
data_offset +=... | cursor.write_u16::<LittleEndian>(data_offset as u16)?;
| random_line_split |
vdpa.rs | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... | (&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 | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... | let config = VringConfigData {
queue_max_size: 32,
queue_size: 32,
flags: 0,
desc_table_addr: 0x1000,
used_ring_addr: 0x2000,
avail_ring_addr: 0x3000,
log_addr: None,
};
vdpa.set_vring_addr(0, &config).unwrap();
... | random_line_split | |
vdpa.rs | // Copyright (C) 2021 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//! Kernel-based vhost-vdpa backend.
use std::fs::{File, OpenOptions};
use std::io::Error as IOError;
use std::os::raw::{c_uchar, c_uint};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRa... |
}
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 | import SimpleITK as sitk
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# # Estimation function # #
# --------------------------- #
# Linear registration function
# --------------------------- #
# --- Input --- #
# im_ref : The common image [numpy.ndarray]
# im_mov : The group ima... | (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 | import SimpleITK as sitk
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# # Estimation function # #
# --------------------------- #
# Linear registration function
# --------------------------- #
# --- Input --- #
# im_ref : The common image [numpy.ndarray]
# im_mov : The group ima... |
# 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 | import SimpleITK as sitk
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# # Estimation function # #
# --------------------------- #
# Linear registration function
# --------------------------- #
# --- Input --- #
# im_ref : The common image [numpy.ndarray]
# im_mov : The group ima... |
# # Similarity function # #
# --------------------------- #
# Calculates the following distances between images:
# 1. Jaccard coef.
# 2. Dice coef.
# 3. Hausdorff distance
# --------------------------- #
# --- Input --- #
# mask_img : The mask image [sikt-image]
# seg_img: The segmented image [sikt-ima... | 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 | import SimpleITK as sitk
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# # Estimation function # #
# --------------------------- #
# Linear registration function
# --------------------------- #
# --- Input --- #
# im_ref : The common image [numpy.ndarray]
# im_mov : The group ima... | # 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 | // +build database
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"time"
l "github.com/vsdmars/actor/internal/logger"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
)
// It is easy to get into trouble by acciden... | // 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 | // +build database
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"time"
l "github.com/vsdmars/actor/internal/logger"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
)
// It is easy to get into trouble by acciden... |
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 | // +build database
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"time"
l "github.com/vsdmars/actor/internal/logger"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
)
// It is easy to get into trouble by acciden... |
func max(x, y int) int {
if x < y {
return y
}
return x
}
func rotate(
ctx context.Context,
name, uuid string,
db *sqlx.DB,
rcnt, period int) {
c := time.Tick(time.Duration(period) * time.Second)
if c == nil {
l.Logger.Error(
"rotate error",
zap.String("service", serviceName),
zap.String("acto... | {
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 | // +build database
package db
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"time"
l "github.com/vsdmars/actor/internal/logger"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"go.uber.org/zap"
)
// It is easy to get into trouble by acciden... | (msg string) error {
b, err := json.Marshal(message{Msg: msg})
if err != nil {
l.Logger.Error(
"backup db insert error",
zap.String("service", serviceName),
zap.String("actor", s.name),
zap.String("uuid", s.uuid),
zap.String("error", err.Error()),
)
return err
}
_, err = s.db.NamedExecContext... | Insert | identifier_name |
lib.rs | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... |
};
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 | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... | (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 | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... |
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_bindgen]
pub struct NoteGenerator {
hashe... | {
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 | use core::fmt;
use std::convert::{TryFrom, TryInto};
use std::ops::Deref;
use std::str::FromStr;
use bulletproofs::r1cs::Prover;
use bulletproofs::{BulletproofGens, PedersenGens};
use bulletproofs_gadgets::fixed_deposit_tree::builder::{FixedDepositTree, FixedDepositTreeBuilder};
use bulletproofs_gadgets::poseidon::bui... | 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 | use crate::lang::{Closure, Argument, ExecutionContext, Value, ColumnType, RowsReader, Row, JobJoinHandle};
use crate::lang::stream::{Readable, ValueSender};
use crate::lang::errors::{CrushResult, argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::... | (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 | use crate::lang::{Closure, Argument, ExecutionContext, Value, ColumnType, RowsReader, Row, JobJoinHandle};
use crate::lang::stream::{Readable, ValueSender};
use crate::lang::errors::{CrushResult, argument_error, mandate, error};
use crate::lib::command_util::{find_field, find_field_from_str};
use crate::lang::printer::... | }))
}
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 | // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//go:build pebble_obj_io_tracing
// +build pebble_obj_io_tracing
package objiotracing
import (
"bufio"
"context"
"fmt"
"math/rand"
"sy... | (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 | // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//go:build pebble_obj_io_tracing
// +build pebble_obj_io_tracing
package objiotracing
import (
"bufio"
"context"
"fmt"
"math/rand"
"sy... | 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 | // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//go:build pebble_obj_io_tracing
// +build pebble_obj_io_tracing
package objiotracing
import (
"bufio"
"context"
"fmt"
"math/rand"
"sy... |
if err := state.curFile.Sync(); err != nil {
panic(err)
}
if err := state.curFile.Close(); err != nil {
panic(err)
}
state.curFile = nil
state.curBW = nil
}
}
| {
panic(err)
} | conditional_block |
obj_io_tracing_on.go | // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//go:build pebble_obj_io_tracing
// +build pebble_obj_io_tracing
package objiotracing
import (
"bufio"
"context"
"fmt"
"math/rand"
"sy... |
// 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 | from __future__ import unicode_literals
import logging
import multiprocessing
from multiprocessing.pool import Pool
import random
import shutil
import sys
import tempfile
import traceback
try: # pragma: no cover
import coverage
except: # pragma: no cover
coverage = None
from green.exceptions import Initiali... |
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 | from __future__ import unicode_literals
import logging
import multiprocessing
from multiprocessing.pool import Pool
import random
import shutil
import sys
import tempfile
import traceback
try: # pragma: no cover
import coverage
except: # pragma: no cover
coverage = None
from green.exceptions import Initiali... | (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 | from __future__ import unicode_literals
import logging
import multiprocessing
from multiprocessing.pool import Pool
import random
import shutil
import sys
import tempfile
import traceback
try: # pragma: no cover
import coverage
except: # pragma: no cover
coverage = None
from green.exceptions import Initiali... | 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 | from __future__ import unicode_literals
import logging
import multiprocessing
from multiprocessing.pool import Pool
import random
import shutil
import sys
import tempfile
import traceback
try: # pragma: no cover
import coverage
except: # pragma: no cover
coverage = None
from green.exceptions import Initiali... |
else:
# loadTargets() returned an object without a run() method, probably
# None
description = ('Test loader returned an un-runnable object. Is "{}" '
'importable from your current location? Maybe you '
'forgot an __init__.py in your directory... | 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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2020 - 2021 Louis Richard
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including with... | (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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2020 - 2021 Louis Richard
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including with... | 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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2020 - 2021 Louis Richard
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including with... | 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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2020 - 2021 Louis Richard
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including with... |
kx_ = np.transpose(kc_x_mat)
kz_ = np.transpose(kc_z_mat)
wf_ = np.transpose(w_final, [0, 2, 1])
return kx_, kz_, wf_, extra_param
| extra_param[k] = np.transpose(np.real(v), [0, 2, 1]) | conditional_block |
app.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox,QFileDialog,QAction
from PyQt5 import QtCore, QtGui, QtWidgets
import ... |
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 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox,QFileDialog,QAction
from PyQt5 import QtCore, QtGui, QtWidgets
import ... |
except:
print("Missing Backup Folder !")
print("Creating Backup Folder ...")
os.mkdir("backup")
def showNotAuthorize(self):
notAdmin = QMessageBox()
notAdmin.setWindowTitle("Login Check")
notAdmin.setText("Not Authorized! Please L... | filename = os.fsdecode(file)
if filename.endswith('.json') and filename[4:6] != currentMonthStr:
os.remove("backup/"+filename) | conditional_block |
app.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox,QFileDialog,QAction
from PyQt5 import QtCore, QtGui, QtWidgets
import ... | lication(sys.argv)
ui = mainWindow()
window = QDialog()
window.setWindowIcon(QtGui.QIcon('sushi.jpg'))
ui.setupUi(window)
window.keyPressEvent =keyPressEvent
window.show()
app.exec_()
def keyPressEvent(event):
event.ignore()
if __name__ == '__main__':
main() | QApp | identifier_name |
app.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5.QtWidgets import QApplication,QDialog,QMessageBox,QFileDialog,QAction
from PyQt5 import QtCore, QtGui, QtWidgets
import ... |
def addItemFunction(self):
self.addItemWindow = Ui_MainWindow()
self.itemWindow = QtWidgets.QMainWindow()
self.addItemWindow.setupUi(self.itemWindow)
self.itemWindow.setWindowIcon(QtGui.QIcon('sushi.jpg'))
self.buttonBox = QtWidgets.QDialogButtonBox(self.addItemWindow.centr... | _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 | import itertools
import re
# https://stackoverflow.com/questions/54621596/include-both-single-quote-and-double-quote-in-python-string-variable
# https://stackoverflow.com/questions/54620287/how-to-include-both-single-and-double-quotes-in-the-same-string-variable-in-pyth
# special = {|}~[\]^_`!"#$%&'()*+,-./:;<=>?@)
# ... |
def makeDatabaseList():
""" List of characters in database 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 cha... | """ 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 | import itertools
import re
# https://stackoverflow.com/questions/54621596/include-both-single-quote-and-double-quote-in-python-string-variable
# https://stackoverflow.com/questions/54620287/how-to-include-both-single-and-double-quotes-in-the-same-string-variable-in-pyth
# special = {|}~[\]^_`!"#$%&'()*+,-./:;<=>?@)
# ... |
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 | import itertools
import re
# https://stackoverflow.com/questions/54621596/include-both-single-quote-and-double-quote-in-python-string-variable
# https://stackoverflow.com/questions/54620287/how-to-include-both-single-and-double-quotes-in-the-same-string-variable-in-pyth
# special = {|}~[\]^_`!"#$%&'()*+,-./:;<=>?@)
# ... | 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 | import itertools
import re
# https://stackoverflow.com/questions/54621596/include-both-single-quote-and-double-quote-in-python-string-variable
# https://stackoverflow.com/questions/54620287/how-to-include-both-single-and-double-quotes-in-the-same-string-variable-in-pyth
# special = {|}~[\]^_`!"#$%&'()*+,-./:;<=>?@)
# ... | (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 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... |
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 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... | (&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 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... |
}
/// 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 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#![allow(non_snake_case)]
pub use libc::sock_filter;
use syscalls::Errno;
use syscalls::Sysno;
us... | 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 | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | > Vec<u8> {
match self {
VarZeroVec::Owned(vec) => vec.into_bytes(),
VarZeroVec::Borrowed(vec) => vec.as_bytes().to_vec(),
}
}
/// Return whether the [`VarZeroVec`] is operating on owned or borrowed
/// data. [`VarZeroVec::into_owned()`] and [`VarZeroVec::make_mut()`... | es(self) - | identifier_name |
vec.rs | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | <'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 | // This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use crate::ule::*;
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering, PartialOrd};
use core::fmt;
use core::ops::De... | /// # 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 | //! Polymorphic HTTP wrappers for code grant authorization and other flows.
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or opti... |
}
impl<'a, W: WebRequest, S: Scopes<W> + 'a + ?Sized> Scopes<W> for &'a mut S {
fn scopes(&mut self, request: &mut W) -> &[Scope] {
(**self).scopes(request)
}
}
impl<'a, W: WebRequest, S: Scopes<W> + 'a + ?Sized> Scopes<W> for Box<S> {
fn scopes(&mut self, request: &mut W) -> &[Scope] {
(... | {
self
} | identifier_body |
mod.rs | //! Polymorphic HTTP wrappers for code grant authorization and other flows.
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or opti... | (
&mut self, request: &mut W, solicitation: Solicitation,
) -> OwnerConsent<W::Response> {
(**self).check_consent(request, solicitation)
}
}
impl<W: WebRequest> Scopes<W> for [Scope] {
fn scopes(&mut self, _: &mut W) -> &[Scope] {
self
}
}
impl<W: WebRequest> Scopes<W> for Vec<... | check_consent | identifier_name |
mod.rs | //! Polymorphic HTTP wrappers for code grant authorization and other flows.
//!
//! An endpoint is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the endpoint types. This means translating Redirect errors to the correct
//! Redirect http response for example or opti... | 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 | #[macro_use] extern crate bitflags;
#[macro_use] extern crate enum_primitive;
extern crate libc;
pub use libc::{c_void, c_char, c_int, c_long, c_ulong, size_t, c_double, off_t};
use std::convert::From;
#[link(name = "mpg123")]
extern {
pub fn mpg123_init() -> c_int;
pub fn mpg123_exit();
pub fn mpg123_ne... | (&self) -> usize {
unsafe {
mpg123_encsize(self.bits()) as usize
}
}
}
bitflags!{
pub flags ChannelCount : i32 {
const CHAN_MONO = 1,
const CHAN_STEREO = 2,
}
}
| size | identifier_name |
lib.rs | #[macro_use] extern crate bitflags;
#[macro_use] extern crate enum_primitive;
extern crate libc;
pub use libc::{c_void, c_char, c_int, c_long, c_ulong, size_t, c_double, off_t};
use std::convert::From;
#[link(name = "mpg123")]
extern {
pub fn mpg123_init() -> c_int;
pub fn mpg123_exit();
pub fn mpg123_ne... |
// 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.