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 |
|---|---|---|---|---|
klogd.rs | ;
#[no_mangle]
fn bb_simple_perror_msg(s: *const libc::c_char);
#[no_mangle]
static bb_banner: [libc::c_char; 0];
#[no_mangle]
static mut bb_common_bufsiz1: [libc::c_char; 0];
}
use crate::librb::signal::__sighandler_t;
use crate::librb::smallint;
pub type C2RustUnnamed = libc::c_uint;
pub const BB_FATAL_... | (
mut _argc: libc::c_int,
mut argv: *mut *mut libc::c_char,
) -> libc::c_int {
let mut i: libc::c_int = 0i32;
let mut opt_c: *mut libc::c_char = 0 as *mut libc::c_char;
let mut opt: libc::c_int = 0;
let mut used: libc::c_int = 0;
opt = getopt32(
argv,
b"c:n\x00" as *const u8 as *const libc::c_char... | klogd_main | identifier_name |
klogd.rs | fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _: ...) -> u32;
#[no_mangle]
fn write_pidfile_std_path_and_ext(path: *const libc::c_char);
#[no_mangle]
fn remove_pidfile_std_path_and_ext(path: *const libc::c_char);
#[no_mangle]
static mut logmode: smallint;
#[no_mangle]
fn ... | random_line_split | ||
klogd.rs | ;
#[no_mangle]
fn bb_simple_perror_msg(s: *const libc::c_char);
#[no_mangle]
static bb_banner: [libc::c_char; 0];
#[no_mangle]
static mut bb_common_bufsiz1: [libc::c_char; 0];
}
use crate::librb::signal::__sighandler_t;
use crate::librb::smallint;
pub type C2RustUnnamed = libc::c_uint;
pub const BB_FATAL_... |
unsafe extern "C" fn klogd_close() {
/* FYI: cmd 7 is equivalent to setting console_loglevel to 7
* via klogctl(8, NULL, 7). */
klogctl(7i32, 0 as *mut libc::c_char, 0i32); /* "7 -- Enable printk's to console" */
klogctl(0i32, 0 as *mut libc::c_char, 0i32);
/* "0 -- Close the log. Currently a NOP" */
}
/* T... | {
/* "2 -- Read from the log." */
return klogctl(2i32, bufp, len);
} | identifier_body |
klogd.rs | dependently from the file system.
//config:
//config: If you answer 'N' here, klogd will use the more portable
//config: approach of reading them from /proc or a device node.
//config: However, this method requires the file to be available.
//config:
//config: If in doubt, say 'Y'.
//applet:IF_KLOGD(APPLET(klogd, BB_DI... | {
*start.offset(n as isize) = '\u{0}' as i32 as libc::c_char;
/* Process each newline-terminated line in the buffer */
start = bb_common_bufsiz1.as_mut_ptr();
loop {
let mut newline: *mut libc::c_char = strchrnul(start, '\n' as i32);
if *newline as libc::c_int == '\u{0}' as i32 {... | conditional_block | |
sandbox.go | x*y, and x^y. !Wow! :-)
}
}
return outer
}
//maps
type LocationCoordinate struct {
Lat, Long float64
}
var map1 map[string]LocationCoordinate
var map2 = map[string]LocationCoordinate{
"Bell Labs": LocationCoordinate{
40.68433, -74.39967,
},
"Google": LocationCoordinate{
37.42202, -122.08408,
},
"Apple... | () func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
var (
previous, current int
)
func fibonacci() func() int {
return func() int {
sum := previous + current
if sum == 0 {
previous = 0
current = 1
return previous + current
} else {
previous = current
current = su... | adder | identifier_name |
sandbox.go | *y, and x^y. !Wow! :-)
}
}
return outer
}
//maps
type LocationCoordinate struct {
Lat, Long float64
}
var map1 map[string]LocationCoordinate
var map2 = map[string]LocationCoordinate{
"Bell Labs": LocationCoordinate{
40.68433, -74.39967,
},
"Google": LocationCoordinate{
37.42202, -122.08408,
},
"Apple":... |
}
map4[v] = count
}
return map4
}
//closure
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
var (
previous, current int
)
func fibonacci() func() int {
return func() int {
sum := previous + current
if sum == 0 {
previous = 0
current = 1
return previ... | {
count++
} | conditional_block |
sandbox.go | x*y, and x^y. !Wow! :-)
}
}
return outer
}
//maps
type LocationCoordinate struct {
Lat, Long float64
}
var map1 map[string]LocationCoordinate
var map2 = map[string]LocationCoordinate{
"Bell Labs": LocationCoordinate{
40.68433, -74.39967,
},
"Google": LocationCoordinate{
37.42202, -122.08408,
},
"Apple... | func runGoRoutine() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from channel c and assign value to x and y
fmt.Println(x, y, x+y)
}
func runBufferedChannel() {
c := make(chan int, 2)
c <- 1
c <- 2
fmt.Println(<-c)
fmt.Prin... | random_line_split | |
sandbox.go |
func swap(x, y string) (string, string) {
return y, x
}
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return //naked return
}
//1
var c1, python1, java1 bool
//2
var i2, j2 int = 1, 2
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z4 complex128 = cmplx.Sqrt(-5 + 12i)
)
co... | {
return x + y
} | identifier_body | |
_train_bot_with_prepared.py | best_action = -1
best_score = -1e9
for action in range(n_actions):
for _ in range(action_range): # random.randint(1,100)
bbox.do_action(action)
if bbox.get_score() > best_score:
best_score = bbox.get_score()
best_action = action
bbox... | replay_memory_size=200000
print('replay_memory_size ', replay_memory_size)
sample_fit_size = 128 # Размер минибатча, по которому будет делаться выборка из буфера
print_step = 10
n_features = bbox.get_num_of_features() # учесть что мы сдесь получаем шайп
print('n_features=', n_features)
n_actions = bbox.get_nu... | #replay_memory_size = np.minimum(int(bbox.total_steps / float(action_repeat)), 500000 ) # размер памяти, буфера
| random_line_split |
_train_bot_with_prepared.py | best_action = -1
best_score = -1e9
for action in range(n_actions):
for _ in range(action_range): # random.randint(1,100)
bbox.do_action(action)
if bbox.get_score() > best_score:
best_score = bbox.get_score()
best_action = action
bbox... | model_prim.fit(old_state_s, y, batch_size=batchSize, nb_epoch=1, verbose=0)
return
def run_bbox(verbose=False, epsilon=0.1, gamma=0.99, action_repeat=5, update_frequency=4, sample_fit_size=32,
replay_memory_size=100000,
load_weights=False, save_weights=False):
global pgi... | action_s[i]] = update_s[i]
| conditional_block |
_train_bot_with_prepared.py | val.append(qval)
action = (np.argmax(qval))
actions[action] += 1
# Choose an action to perform at current step
if random.random() < epsilon: # choose random action or best action
action = np.random.randint(0, n_actions) # assumes 4 different actions
else: #... | = model.predict(state.reshape(1, n_features), batch_size=1)
action = (np.argmax(qval))
actions[action] += 1
for a in range(action_repeat):
has_next = bbox.do_action(action)
bbox.finish(verbose=0)
print(" test ", i, " score: ", bbox.get_scor... | identifier_body | |
_train_bot_with_prepared.py | best_action = -1
best_score = -1e9
for action in range(n_actions):
for _ in range(action_range): # random.randint(1,100)
bbox.do_action(action)
if bbox.get_score() > best_score:
best_score = bbox.get_score()
best_action = action
bbox... | ibatch):
old_state_s = np.array([row[0] for row in minibatch])
action_s = np.array([row[1] for row in minibatch])
reward_s = np.array([row[2] for row in minibatch])
new_state_s = np.array([row[3] for row in minibatch])
old_qwal_s = model.predict(old_state_s, batch_size=32)
newQ_s = model.p... | n_minibatch(min | identifier_name |
gitstore.go | }
/*
// map poolname => []nodeUuid, only the blobs that have a key set are going to be changed
func (s *Store) SaveNodeBlobs(uuid string, blobs map[string]io.Reader) error {
for blobPath, blob := range blobs {
path := filepath.Join(s.Git.Dir, s.BlobPath(uuid, blobPath))
if err := s.saveBlobToFile(path, blob); er... | {
// fmt.Printf("trying to remove node: uuid %#v shard %#v\n", uuid, shard)
// fmt.Println("proppath is ", g.propPath(uuid))
paths := []string{
fmt.Sprintf("text/%s/%s/%s", g.shard, uuid[:2], uuid[2:]),
fmt.Sprintf("blob/%s/%s/%s", g.shard, uuid[:2], uuid[2:]),
}
files, err := g.LsFiles(fmt.Sprintf("refs/*/%s... | identifier_body | |
gitstore.go | , err := tx.WriteHashObject(strings.NewReader("ZOOM DATABASE\nThis is a zoom database.\nDon't write into this directory manually.\nUse the zoom database library instead.\n"))
if err != nil {
return err
}
err = tx.AddIndexCache(sha1, "README")
if err != nil {
return err
}
sha1, err = tx.Write... |
return fn(blobPath, file)
}
return nil
}
*/
/*
func (s *Store) GetIndex(indexpath string, shard string, fn func(io.Reader) error) error {
path := filepath.Join(s.Git.Dir, s.indexPath(shard, indexpath))
if FileExists(path) {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
... | }
defer file.Close() | random_line_split |
gitstore.go | err := tx.WriteHashObject(strings.NewReader("ZOOM DATABASE\nThis is a zoom database.\nDon't write into this directory manually.\nUse the zoom database library instead.\n"))
if err != nil {
return err
}
err = tx.AddIndexCache(sha1, "README")
if err != nil {
return err
}
sha1, err = tx.WriteT... |
// fmt.Println("result", buf.String())
var sha1 string
sha1, err = g.Transaction.WriteHashObject(&buf)
if err != nil {
return err
}
if isNew {
err = g.Transaction.AddIndexCache(sha1, path)
} else {
err = g.Transaction.UpdateIndexCache(sha1, path)
}
if err != nil {
return err
}
return nil
}
func (... | {
return err
} | conditional_block |
gitstore.go | (name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
type Git struct {
*gitlib.Git
shard string
}
func Open(baseDir string, shard string) (g Git, err error) {
// fmt.Println("opening")
//gitBase := filepath.Join(baseDir, ".git")
gitBase :... | FileExists | identifier_name | |
_wx.py | .WXK_F5: keys.F5,
wx.WXK_F6: keys.F6,
wx.WXK_F7: keys.F7,
wx.WXK_F8: keys.F8,
wx.WXK_F9: keys.F9,
wx.WXK_F10: keys.F10,
wx.WXK_F11: keys.F11,
wx.WXK_F12: keys.F12,
wx.WXK_SPACE: keys.SPACE,
wx.WXK_RETURN: keys.ENTER, # == pyglet.window.key.RETURN... |
class DummySize(object):
def __init__(self, size):
self.size = size
def GetSize(self):
return self.size
def Skip(self):
pass
class CanvasBackend(GLCanvas, BaseCanvasBackend):
""" wxPython backend for Canvas abstract class."""
# args are for BaseCanvasBackend, kwargs ... | """Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode()
if key in KEYMAP:
return KEYMAP[key], ''
if 97 <= key <= 122:
key -= 32
if key >= 32 and key <= 127:
return keys.Key(chr(key)), chr(key)
else:
return None, None | identifier_body |
_wx.py | 5: keys.F5,
wx.WXK_F6: keys.F6,
wx.WXK_F7: keys.F7,
wx.WXK_F8: keys.F8,
wx.WXK_F9: keys.F9,
wx.WXK_F10: keys.F10,
wx.WXK_F11: keys.F11,
wx.WXK_F12: keys.F12,
wx.WXK_SPACE: keys.SPACE,
wx.WXK_RETURN: keys.ENTER, # == pyglet.window.key.RETURN
... | _vispy_get_fullscreen | identifier_name | |
_wx.py | .WXK_F5: keys.F5,
wx.WXK_F6: keys.F6,
wx.WXK_F7: keys.F7,
wx.WXK_F8: keys.F8,
wx.WXK_F9: keys.F9,
wx.WXK_F10: keys.F10,
wx.WXK_F11: keys.F11,
wx.WXK_F12: keys.F12,
wx.WXK_SPACE: keys.SPACE,
wx.WXK_RETURN: keys.ENTER, # == pyglet.window.key.RETURN... | """Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode()
if key in KEYMAP:
return KEYMAP[key], ''
if 97 <= key <= 122:
key -= 32
if key >= 32 and key <= 127:
return keys.Key(chr(key)), chr(key)
else:
return None, None
class DummySize(objec... |
def _process_key(evt): | random_line_split |
_wx.py | ApplicationBackend.__init__(self)
self._event_loop = wx.EventLoop()
wx.EventLoop.SetActive(self._event_loop)
def _vispy_get_backend_name(self):
return 'wx'
def _vispy_process_events(self):
# inpsired by https://github.com/wxWidgets/wxPython/blob/master/
# sa... | if evt.LeftDown():
button = 0
elif evt.MiddleDown():
button = 1
elif evt.RightDown():
button = 2
else:
evt.Skip()
self._vispy_mouse_press(pos=pos, button=button, modifiers=mods) | conditional_block | |
protocol_adapter.rs | decimal::{BigDecimal, FromPrimitive};
use graphql_parser::query::{
Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value,
};
use query_core::query_document::*;
/// Protocol adapter for GraphQL -> Query Document.
///
/// GraphQL is mapped as following:
/// - Every field of a `que... |
fn convert_query(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> {
Self::convert_selection_set(selection_set).map(|fields| fields.into_iter().map(Operation::Read).collect())
}
fn convert_mutation(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> {
... | {
match def {
Definition::Fragment(f) => Err(HandlerError::unsupported_feature(
"Fragment definition",
format!("Fragment '{}', at position {}.", f.name, f.position),
)),
Definition::Operation(op) => match op {
OperationDefinitio... | identifier_body |
protocol_adapter.rs | decimal::{BigDecimal, FromPrimitive};
use graphql_parser::query::{
Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value,
};
use query_core::query_document::*;
/// Protocol adapter for GraphQL -> Query Document.
///
/// GraphQL is mapped as following:
/// - Every field of a `que... | (gql_doc: Document<String>, operation: Option<String>) -> crate::Result<Operation> {
let mut operations: Vec<Operation> = match operation {
Some(ref op) => gql_doc
.definitions
.into_iter()
.find(|def| Self::matches_operation(def, op))
... | convert | identifier_name |
protocol_adapter.rs | decimal::{BigDecimal, FromPrimitive};
use graphql_parser::query::{
Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value,
};
use query_core::query_document::*;
/// Protocol adapter for GraphQL -> Query Document.
///
/// GraphQL is mapped as following:
/// - Every field of a `que... | (
"categories".to_string(),
ArgumentValue::object([(
"create".to_string(),
ArgumentValue::list([
ArgumentValue::object([("id".to_string(), ArgumentValue::int(1))]),
ArgumentValue::object([... | let write = operation.into_write().unwrap();
let data_args = ArgumentValue::object([
("id".to_string(), ArgumentValue::int(1)), | random_line_split |
resource.py | (code):
"""
Maps a L{CODE} constant to a HTTP code.
"""
if code == 103:
return http.NOT_FOUND
return http.INTERNAL_SERVER_ERROR
def _writeJSONErrorResponse(f, request):
"""
Serializes a L{Failure} to JSON and writes it to the C{request}
@param f: The L{Failure} to serialize.
... | deferreds.append(getInfo(server)) | conditional_block | |
resource.py | Dict
from bdm.error import BloodyError, PaypalError
from bdm.constants import CODE
from valve.source.a2s import ServerQuerier, NoResponseError
from valve.steam.id import SteamID as ValveSteamID
def steamidTo64(steamid):
|
def _writeJSONResponse(result, request, code=CODE.SUCCESS, status=http.OK):
"""
Serializes C{result} to JSON and writes it to C{request}.
@param result: The content to be serialized and written to the request.
@type result: An object accepted by json.dumps.
@param request: The request object t... | return ValveSteamID.from_text(steamid).as_64() | identifier_body |
resource.py | Dict
from bdm.error import BloodyError, PaypalError
from bdm.constants import CODE
from valve.source.a2s import ServerQuerier, NoResponseError
from valve.steam.id import SteamID as ValveSteamID
def steamidTo64(steamid):
return ValveSteamID.from_text(steamid).as_64()
def _writeJSONResponse(result, request, co... |
elif response == 'VERIFIED':
return True
else:
raise PaypalError('Unrecognized verification response: %s', (response,))
data = request.content.read()
params = '?cmd=_notify-validate&' + data
d = getPage(paypalURL+params, method='POST')
... |
def _cb(response):
if response == 'INVALID':
raise PaypalError(
'IPN data invalid. data: %s', (data,)) | random_line_split |
resource.py | Dict
from bdm.error import BloodyError, PaypalError
from bdm.constants import CODE
from valve.source.a2s import ServerQuerier, NoResponseError
from valve.steam.id import SteamID as ValveSteamID
def steamidTo64(steamid):
return ValveSteamID.from_text(steamid).as_64()
def _writeJSONResponse(result, request, co... | (self, request):
if not request.postpath:
return "maybe sam dox"
name = request.postpath[0]
content = json.loads(request.content.read())
if not content:
return 'No JSON provided'
if name == u'servers':
return self.serverStats(content)
... | render_POST | identifier_name |
__init__.py | Distance function - frobenius, nuclear, mahalanobis (just form of mahalanobis), or
:param decay: decaying learning rate and radius - exponential or linear
:param seed: Random seed
"""
np.random.seed(seed = seed)
if xdim is None or ydim is None:
xdim = int(np.sqrt(5 *... | conditional_block | ||
__init__.py | , mahalanobis (just form of mahalanobis), or
:param decay: decaying learning rate and radius - exponential or linear
:param seed: Random seed
"""
np.random.seed(seed = seed)
if xdim is None or ydim is None:
xdim = int(np.sqrt(5 * np.sqrt(data.shape[0])))
y... | return 0.0 | random_line_split | |
__init__.py | :
"""
Matrix SOM
Initialize weight matrix
For epoch <- 1 to N do
Choose input matrix observation randomly - i
For k <- 1 to n_node do
compute d(input matrix i, weight matrix k)
end
Best Matching Unit = winning node = node with the smallest distance
For... | kohonen | identifier_name | |
__init__.py | Learning rate: ⍺(t) = ⍺_0 * exp(-t / ƛ)
"""
def __init__(
self, data, xdim, ydim, topo = "rectangular", neighbor = "gaussian",
dist = "frobenius", decay = "exponential", seed = None
):
"""
:param data: 3d array. processed data set for Online SOM Detector
... | """
Matrix SOM
Initialize weight matrix
For epoch <- 1 to N do
Choose input matrix observation randomly - i
For k <- 1 to n_node do
compute d(input matrix i, weight matrix k)
end
Best Matching Unit = winning node = node with the smallest distance
For k <- ... | identifier_body | |
local_audio_visualizer.js | window.requestAnimationFrame = requestAnimationFrame;
})();
window.onload = function () {
var element = document.getElementById("waves");
dropAndLoad(element, init, "ArrayBuffer");
};
// Reusable dropAndLoad function: it reads a local file dropped on a
// `dropElement` in the DOM in the specified `readFormat`
/... | random_line_split | ||
local_audio_visualizer.js | (0); // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
}
// Once the file is loaded, we start getting our hands dirty.
function init(arrayBuffer) {
// document.getElementById('instructions').innerHTML = 'Loading ...'
// Create a new `audioContext` and its `analyser`
win... |
var url =
"https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3";
playerElement = document.querySelector("#player");
function Player(url) {
this.ac = new (window.AudioContext || webkitAudioContext)();
this.url = url;
this.mute = false;
// this.el = el;
this.button = document.getE... | {
console.log(source);
if (!source.stop) source.stop = source.noteOff;
source.stop(0);
} | identifier_body |
local_audio_visualizer.js | console.log(source);
if (!source.stop) source.stop = source.noteOff;
source.stop(0);
}
var url =
"https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3";
playerElement = document.querySelector("#player");
function Player(url) {
this.ac = new (window.AudioContext || webkitAudioContext)... | {
this.button.classList.add("fa-play");
this.button.classList.remove("fa-pause");
} | conditional_block | |
local_audio_visualizer.js | .start(0); // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
}
// Once the file is loaded, we start getting our hands dirty.
function init(arrayBuffer) {
// document.getElementById('instructions').innerHTML = 'Loading ...'
// Create a new `audioContext` and its `analyser`... | (url) {
this.ac = new (window.AudioContext || webkitAudioContext)();
this.url = url;
this.mute = false;
// this.el = el;
this.button = document.getElementById("play_button");
this.volume_btn = document.getElementById("change_vol");
this.mute_btn = document.getElementById("vol_img");
this.rewind = docume... | Player | identifier_name |
parser.rs | "-g" | "-G" | "-h" | "-k" | "-L" | "-N"
| "-O" | "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => {
Self::UnaryOp(UnaryOperator::FiletestOp(s))
}
_ => Self::Literal(s),
},
None => Self::Literal(s... | /// as a literal
///
fn lparen(&mut self) -> ParseResult<()> {
// Look ahead up to 3 tokens to determine if the lparen is being used
// as a grouping operator or should be treated as a literal string
let peek3: Vec<Symbol> = self
.tokens
.clone()
... | random_line_split | |
parser.rs | "-g" | "-G" | "-h" | "-k" | "-L" | "-N"
| "-O" | "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => {
Self::UnaryOp(UnaryOperator::FiletestOp(s))
}
_ => Self::Literal(s),
},
None => Self::Literal(s... | thesized expression.
///
/// test has no reserved keywords, so "(" will be interpreted as a literal
/// in certain cases:
///
/// * when found at the end of the token stream
/// * when followed by a binary operator that is not _itself_ interpreted
/// as a literal
///
fn lparen(&mu... | oken();
match symbol {
Symbol::LParen => self.lparen()?,
Symbol::Bang => self.bang()?,
Symbol::UnaryOp(_) => self.uop(symbol),
Symbol::None => self.stack.push(symbol),
literal => self.literal(literal)?,
}
Ok(())
}
/// Parse a ... | identifier_body |
parser.rs | "-g" | "-G" | "-h" | "-k" | "-L" | "-N"
| "-O" | "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => {
Self::UnaryOp(UnaryOperator::FiletestOp(s))
}
_ => Self::Literal(s),
},
None => Self::Literal(s... | let symbol = self.next_token();
match symbol {
Symbol::LParen => self.lparen()?,
Symbol::Bang => self.bang()?,
Symbol::UnaryOp(_) => self.uop(symbol),
Symbol::None => self.stack.push(symbol),
literal => self.literal(literal)?,
}
... | {
| identifier_name |
builder.go | (hostRootMount string) BuilderOption {
return func(b *builder) error {
log.Infof("Host root filesystem will be remapped to %s", hostRootMount)
b.pathMapper = &pathMapper{
hostMountPath: hostRootMount,
}
return nil
}
}
// WithDocker configures using docker
func WithDocker() BuilderOption {
return func(b *... | WithHostRootMount | identifier_name | |
builder.go | b.dockerClient = cli
return nil
}
}
// WithAudit configures using audit checks
func WithAudit() BuilderOption {
return func(b *builder) error {
cli, err := newAuditClient()
if err == nil {
b.auditClient = cli
}
return err
}
}
// WithAuditClient configures using specific audit client
func WithAuditCl... | return func(b *builder) error { | random_line_split | |
builder.go |
pathMapper *pathMapper
etcGroupPath string
nodeLabels map[string]string
suiteMatcher SuiteMatcher
ruleMatcher RuleMatcher
dockerClient env.DockerClient
auditClient env.AuditClient
kubeClient env.KubeClient
isLeaderFunc func() bool
status *status
}
func (b *builder) Close() error {
if b.dockerCli... | {
if b.isLeaderFunc != nil {
return b.isLeaderFunc()
}
return true
} | identifier_body | |
builder.go | rule.ID)
return false, nil
}
case compliance.KubernetesNodeScope:
if config.IsKubernetes() {
return b.isKubernetesNodeEligible(rule.HostSelector)
}
log.Infof("rule %s skipped - not running on a Kubernetes node", rule.ID)
return false, nil
}
return true, nil
}
func (b *builder) isKubernetesNodeElig... | {
flagValues := parseProcessCmdLine(mp.Cmdline)
return flagValues[flag], nil
} | conditional_block | |
base_function.py | 路径名
print("file name", file_name)
# 文件名
title = file_name.split("/")[-1]
print(type(title), title)
isolate1 = Isolate('isolate', cases, rate = abnormal_rate)
np_array = isolate1.merge_arrays()
table_name = np_array[1, 0]
db = connectdb()
if not query_table(db, table_name):
cr... |
def save_xgboost_class(model):
"""
xgboost 模型持久化,存储在models目录下,使用model.name作为文件名,同时持久化模型名称 | random_line_split | |
base_function.py | # with open(file_path, 'r') as file:
# lines = file.read().splitlines()
# for line in lines:
# if line is None or line == "":
# continue
# elif line not in sv.xgboost_model_dict.keys():
# sv.xgboost_model_dict[line] = load_xgboost_class(line)
#... | print("xgboost_name", data_name)
return 1
elif model_kind == 'LSTM':
# 多进程训练模型
if redis_conn.sismember("lstm_name", data_name) and force != 1:
print("存在000000000", data_name)
return 0
else:
print("训练过程0000000")
print("类型", type(d... | identifier_body | |
base_function.py | return:
"""
length = len(arrays)
if length < 200:
print("测试集大小:", length)
return "测试集数据小于200,请重新传入大于200条数据的测试集"
elif length < 256:
print("测试集大小:", length)
return arrays
indexs = np.linspace(0, length - 1, size)
indexs = np.array(indexs, dtype = int)
res_arr = ... | lete(np_array, 0, axis = 1)
# # 获 | identifier_name | |
base_function.py | :int, 要求均匀分为的份额,一般为256,用户可以自己设置,第一行为标签
:return:
"""
length = len(arrays)
if length < 200:
print("测试集大小:", length)
return "测试集数据小于200,请重新传入大于200条数据的测试集"
elif length < 256:
print("测试集大小:", length)
return arrays
indexs = np.linspace(0, length - 1, size)
indexs = ... | # 数据集列表存储表名(redis存储),断电就清空
redis_conn = get_redis_connection("default")
redis_conn.sadd('data_set_name', title)
# sv.data_set.append(title)
# 存储数据集表名(磁盘存储),断电可恢复
save_dataset_name_to_file(title)
# 存储文件与UUID对应关系到file2uuid表中
insert_file2uuid(title, table_name)
... | np_array[1:]):
| conditional_block |
logger.go | io-go/v6/pkg/set"
"github.com/minio/minio/cmd/logger/message/log"
)
var (
// HighwayHash key for logging in anonymous mode
magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// HighwayHash hasher for lo... | (f func(string, error, bool) string) {
errorFmtFunc = f
}
// Remove any duplicates and return unique entries.
func uniqueEntries(paths []string) []string {
m := make(set.StringSet)
for _, p := range paths {
if !m.Contains(p) {
m.Add(p)
}
}
return m.ToSlice()
}
// SetDeploymentID -- Deployment Id from the ... | RegisterUIError | identifier_name |
logger.go | -go/v6/pkg/set"
"github.com/minio/minio/cmd/logger/message/log"
)
var (
// HighwayHash key for logging in anonymous mode
magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// HighwayHash hasher for logg... |
// EnableAnonymous - turns anonymous flag
// to avoid printing sensitive information.
func EnableAnonymous() {
anonFlag = true
}
// IsJSON - returns true if jsonFlag is true
func IsJSON() bool {
return jsonFlag
}
// IsQuiet - returns true if quietFlag is true
func IsQuiet() bool {
return quietFlag
}
// Register... | {
jsonFlag = true
quietFlag = true
} | identifier_body |
logger.go | io-go/v6/pkg/set"
"github.com/minio/minio/cmd/logger/message/log"
)
var (
// HighwayHash key for logging in anonymous mode
magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// HighwayHash hasher for lo... |
// Add trim string "{GOROOT}/src/" into trimStrings
trimStrings = []string{filepath.Join(runtime.GOROOT(), "src") + string(filepath.Separator)}
// Add all possible path from GOPATH=path1:path2...:pathN
// as "{path#}/src/" into trimStrings
for _, goPathString := range goPathList {
trimStrings = append(trimStri... | defaultgoRootList = strings.Split(build.Default.GOROOT, pathSeperator) | random_line_split |
logger.go | -go/v6/pkg/set"
"github.com/minio/minio/cmd/logger/message/log"
)
var (
// HighwayHash key for logging in anonymous mode
magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// HighwayHash hasher for logg... |
}
}
traceLevel++
// Read stack trace information from PC
pc, file, lineNumber, ok = runtime.Caller(traceLevel)
}
return trace
}
// Return the highway hash of the passed string
func hashString(input string) string {
defer loggerHighwayHasher.Reset()
loggerHighwayHasher.Write([]byte(input))
checksum := ... | {
return trace
} | conditional_block |
select.go | }
if k+1 < i && scases[lockorder[k]].c.sortkey() < scases[lockorder[k+1]].c.sortkey() {
k++
}
if c.sortkey() < scases[lockorder[k]].c.sortkey() {
lockorder[j] = lockorder[k]
j = k
continue
}
break
}
lockorder[j] = o
}
if debugSelect {
for i := 0; i+1 < len(lockorder); i++ {
i... | print("syncsend: cas0=", cas0, " c=", c, "\n")
}
g | conditional_block | |
select.go | var lastc *hchan
for sg := gp.waiting; sg != nil; sg = sg.waitlink {
if sg.c != lastc && lastc != nil {
// As soon as we unlock the channel, fields in
// any sudog with that channel may change,
// including c and waitlink. Since multiple
// sudogs may have the same channel, we unlock
// only after we... | // There are unlocked sudogs that point into gp's stack. Stack
// copying must lock the channels of those sudogs.
// Set activeStackChans here instead of before we try parking
// because we could self-deadlock in stack growth on a
// channel lock.
gp.activeStackChans = true
// Mark that it's safe for stack shrink... | identifier_body | |
select.go | // only after we've passed the last instance
// of a channel.
unlock(&lastc.lock)
}
lastc = sg.c
}
if lastc != nil {
unlock(&lastc.lock)
}
return true
}
func block() {
gopark(nil, nil, waitReasonSelectNoCases, traceEvGoStop, 1) // forever
}
// selectgo implements the select statement.
//
// cas0 p... | s0 *scase, order0 *uint16, pc0 *uintptr, nsends, nrecvs int, block bool) (int, bool) {
if debugSelect {
print("select: cas0=", cas0, "\n")
}
// NOTE: In order to maintain a lean stack size, the number of scases
// is capped at 65536.
cas1 := (*[1 << 16]scase)(unsafe.Pointer(cas0))
order1 := (*[1 << 17]uint16)(... | ectgo(ca | identifier_name |
select.go | on gp.waiting where copystack can find it.
sg.elem = cas.elem
sg.releasetime = 0
if t0 != 0 {
sg.releasetime = -1
}
sg.c = c
// Construct waiting list in lock order.
*nextp = sg
nextp = &sg.waitlink
if casi < nsends {
c.sendq.enqueue(sg)
} else {
c.recvq.enqueue(sg)
}
}
// wait for s... | y := sgp.next
if x != nil { | random_line_split | |
main.go | direction direction
paintedPoints []*point
}
func (r *paintingRobot) run() {
wg := sync.WaitGroup{}
wg.Add(1)
go r.brain.execute()
go func() {
r.brain.inChannel <- 1
readingColor := true
robotLoop: for {
var scannedColor int
select {
... |
// Rotates the direction robot is facing - 0 for CW rotation and 1 for CCW rotation.
func (r *paintingRobot) changeDirection(input int) {
if input == 1 {
if r.direction == up {
r.direction = left
} else {
r.direction -= 1
}
} else {
if r.direction == lef... | {
fmt.Println(fmt.Sprintf("robot paints [%d,%d] to color %d", r.position.x, r.position.y, color))
for _, p := range r.paintedPoints {
if p.x == r.position.x && p.y == r.position.y {
p.color = color
fmt.Println("just repainted, # of painted tiles: ", len(r.paintedPoints))
... | identifier_body |
main.go |
direction direction
paintedPoints []*point
}
func (r *paintingRobot) run() {
wg := sync.WaitGroup{}
wg.Add(1)
go r.brain.execute()
go func() {
r.brain.inChannel <- 1
readingColor := true
robotLoop: for {
var scannedColor int
select {
... | () (int, int, point) {
xMin, xMax, yMin, yMax := 0, 0, 0, 0
for _, p := range r.paintedPoints {
if p.x > xMax {
xMax = p.x
}
if p.x < xMin {
xMin = p.x
}
if p.y > yMax {
yMax = p.y
}
if p.y < yMin {
yMin = p.... | getGridInfo | identifier_name |
main.go |
direction direction
paintedPoints []*point
}
func (r *paintingRobot) run() {
wg := sync.WaitGroup{}
wg.Add(1)
go r.brain.execute()
go func() {
r.brain.inChannel <- 1
readingColor := true
robotLoop: for {
var scannedColor int
select {
... | readingColor = !readingColor
case <-r.brain.done:
wg.Done()
break robotLoop
}
}
}()
wg.Wait()
}
// Gives the tile a color based on input (0 - black, 1 - white).
// In order to keep track of unique painted tiles we keep record in s... | random_line_split | |
main.go |
direction direction
paintedPoints []*point
}
func (r *paintingRobot) run() {
wg := sync.WaitGroup{}
wg.Add(1)
go r.brain.execute()
go func() {
r.brain.inChannel <- 1
readingColor := true
robotLoop: for {
var scannedColor int
select {
... | else {
r.direction += 1
}
}
}
// Moves the robot by 1 distance point in the direction it is currently facing.
func (r *paintingRobot) move() {
posX, posY := r.position.x, r.position.y
switch r.direction {
case up:
posY -= 1
case right:
posX += 1
case down:
... | {
r.direction = up
} | conditional_block |
crud.ts | each, clone, map, filter as arr_filter, reduce, find,
values, Dictionary } from 'lodash';
import * as q from 'q';
import { v4 } from 'node-uuid';
const ID_MAP: SDict = { id: 'id' };
const ID_FIELDS = [ 'id', 'updated_by', 'created_by' ];
type RequestHandler = (req: Request, res: Response, next?: Function) => vo... | } else {
query = model.findAll(build_query(prop_remap, req.params | .then(tag(part))
.then(resolve));
}); | random_line_split |
crud.ts | each, clone, map, filter as arr_filter, reduce, find,
values, Dictionary } from 'lodash';
import * as q from 'q';
import { v4 } from 'node-uuid';
const ID_MAP: SDict = { id: 'id' };
const ID_FIELDS = [ 'id', 'updated_by', 'created_by' ];
type RequestHandler = (req: Request, res: Response, next?: Function) => vo... | (model: any): RequestHandler {
return (req, res) => error_handler(res, model.update(
populate_uuids(populate_dates(req.body)),
build_query(ID_MAP, req.params)
).then(response_handler(res)));
}
/**
* NOTE this will always do a soft-delete unless "purge=true" is passed as a
* query paramter alo... | update | identifier_name |
crud.ts | , clone, map, filter as arr_filter, reduce, find,
values, Dictionary } from 'lodash';
import * as q from 'q';
import { v4 } from 'node-uuid';
const ID_MAP: SDict = { id: 'id' };
const ID_FIELDS = [ 'id', 'updated_by', 'created_by' ];
type RequestHandler = (req: Request, res: Response, next?: Function) => void
ty... |
}));
}
return Promise.all(checks).then(() => q.when({})
.then(stamp_meta('instead', instead))
.then(tag(part))
.then(resolve));
});
} else {
... | {
model.findOne(build_query(prop_remap, req.params, {
where: { user_id }
})).then(row => {
instead.includes_me = !!row;
resolve();
... | conditional_block |
crud.ts | , clone, map, filter as arr_filter, reduce, find,
values, Dictionary } from 'lodash';
import * as q from 'q';
import { v4 } from 'node-uuid';
const ID_MAP: SDict = { id: 'id' };
const ID_FIELDS = [ 'id', 'updated_by', 'created_by' ];
type RequestHandler = (req: Request, res: Response, next?: Function) => void
ty... |
function build_query(prop_remap: SDict, params: SDict, extras: Object = {}): QueryOptions {
var query = <QueryOptions>clone(extras);
query.where = merge(generate_where(prop_remap, params), query.where);
query.raw = true;
return query;
}
function stamp_meta<V, H>(label: string, val: V): (holder: H) =>... | {
return reduce(schema, (prop_remap, lookup: string, field: string) => {
if (params[lookup]) {
prop_remap[field] = params[lookup];
}
return prop_remap;
}, {});
} | identifier_body |
cpu_time.rs | current() -> io::Result<LinuxStyleCpuTime> {
imp::current()
}
}
pub use std::io::Result;
pub use imp::cpu_time;
/// A struct to monitor process cpu usage
#[derive(Clone, Copy)]
pub struct ProcessStat {
current_time: Instant,
cpu_time: Duration,
}
impl ProcessStat {
pub fn cur_proc_stat() ->... | {
let (kernel_time, user_time) = unsafe {
let process = GetCurrentProcess();
let mut create_time = mem::zeroed();
let mut exit_time = mem::zeroed();
let mut kernel_time = mem::zeroed();
let mut user_time = mem::zeroed();
let ret = GetProce... | identifier_body | |
cpu_time.rs | pub softirq: u64,
pub steal: u64,
pub guest: u64,
pub guest_nice: u64,
}
impl LinuxStyleCpuTime {
pub fn total(&self) -> u64 {
// Note: guest(_nice) is not counted, since it is already in user.
// See https://unix.stackexchange.com/questions/178045/proc-stat-is-guest-counted-into-user-... | () -> io::Result<std::time::Duration> {
let mut time = unsafe { std::mem::zeroed() };
if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut time) } == 0 {
let sec = time.ru_utime.tv_sec as u64 + time.ru_stime.tv_sec as u64;
let nsec = (time.ru_utime.tv_usec as u32 + time.ru_stime.... | cpu_time | identifier_name |
cpu_time.rs | fn current() -> io::Result<LinuxStyleCpuTime> {
imp::current()
}
}
pub use std::io::Result;
pub use imp::cpu_time;
/// A struct to monitor process cpu usage
#[derive(Clone, Copy)]
pub struct ProcessStat {
current_time: Instant,
cpu_time: Duration,
}
impl ProcessStat {
pub fn cur_proc_stat()... | random_line_split | ||
cpu_time.rs | pub softirq: u64,
pub steal: u64,
pub guest: u64,
pub guest_nice: u64,
}
impl LinuxStyleCpuTime {
pub fn total(&self) -> u64 {
// Note: guest(_nice) is not counted, since it is already in user.
// See https://unix.stackexchange.com/questions/178045/proc-stat-is-guest-counted-into-user-... | else {
Ok(0.0)
}
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
mod imp {
use std::{fs::File, io, io::Read, time::Duration};
pub fn current() -> io::Result<super::LinuxStyleCpuTime> {
let mut state = String::new();
File::open("/proc/stat")?.read_to_string(... | {
let cpu_time = new_time
.checked_sub(old_time)
.map(|dur| dur.as_secs_f64())
.unwrap_or(0.0);
Ok(cpu_time / real_time)
} | conditional_block |
esv.py | , 27, 14, 17, 14, 15],
[21],
[17, 10, 10, 11],
[16, 13, 12, 13, 15, 16, 20],
[15, 13, 19],
[17, 20, 19],
[18, 15, 20],
[15, 23],
[21, 13, 10, 14, 11, 15, 14, 23, 17, 12, 17, 14, 9, 21],
[14, 17, 18, 6],
[25, 23, 17, 25, 48, 34, 29, 34, 38, 42, 30, 50, 58, 36, 39, 28, 27, 35,
... | """
Fetch biblical text (in ESV translation) corresponding to the provided
Passage object. Returns tuple of (passage_text, truncated), where
'truncated' is a boolean indicating whether passage was shortened to comply
with API conditions.
Parameters:
'passage' is any object that returns a string ... | identifier_body | |
esv.py | 21, 28, 18, 16, 18, 22, 13, 30, 5, 28, 7, 47, 39, 46, 64, 34],
[22, 22, 66, 22, 22],
[28, 10, 27, 17, 17, 14, 27, 18, 11, 22, 25, 28, 23, 23, 8, 63, 24, 32,
14, 49, 32, 31, 49, 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38,
28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35],
[21, 49, 30... | chapter = c + 1
last_verses[book, chapter] = last_verse
total_verses += last_verse - \
len(missing_verses.get((book, chapter), [])) | conditional_block | |
esv.py | , 12, 25, 11, 31, 13],
[27, 32, 39, 12, 25, 23, 29, 18, 13, 19, 27, 31, 39, 33, 37, 23, 29, 33,
43, 26, 22, 51, 39, 25],
[53, 46, 28, 34, 18, 38, 51, 66, 28, 29, 43, 33, 34, 31, 34, 34, 24, 46,
21, 43, 29, 53],
[18, 25, 27, 44, 27, 33, 20, 29, 37, 36, 21, 21, 25, 29, 38, 20, 41, 37,
... | 31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176,7, 8, 9, 4, 8, 5, 6,
5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 13, 10, 7, 12, 15,
21, 10, 20, 14, 9, 6],
[33, 22, 35, 27, 23, 35, 27, 36, 18, 32, 31, 28, 25, 35, 33, 33, 28, 24,
29, 30, 31, 29, 35, 34, 28, 28, 27, 28, 27,... | 16, 15, 5, 23, 11, 13, 12, 9, 9, 5, 8, 28, 22, 35, 45, 48, 43, 13, | random_line_split |
esv.py | 27, 17, 21, 36, 26, 21, 26, 18, 32, 33, 31, 15, 38,
28, 23, 29, 49, 26, 20, 27, 31, 25, 24, 23, 35],
[21, 49, 30, 37, 31, 28, 28, 27, 27, 21, 45, 13],
[11, 23, 5, 19, 15, 11, 16, 14, 17, 15, 12, 14, 16, 9],
[20, 32, 21],
[15, 16, 15, 13, 27, 14, 17, 14, 15],
[21],
[17, 10, 10, 11],
... | get_passage_text | identifier_name | |
codegen.go |
// Generate declarations from module to be used together with encoding/asn1.
//
// Feature support status:
// - [x] ModuleIdentifier
// - [x] TagDefault (except AUTOMATIC)
// - [ ] ExtensibilityImplied
// - [.] ModuleBody -- see moduleContext.generateDeclarations.
func (gen declCodeGen) Generate(module ModuleDefiniti... | {
for _, existing := range ctx.requiredModules {
if existing == module {
return
}
}
ctx.requiredModules = append(ctx.requiredModules, module)
} | identifier_body | |
codegen.go | moduleName = goast.NewIdent(gen.Params.Package)
}
ast := &goast.File{
Name: moduleName,
Decls: ctx.generateDeclarations(module),
}
if len(ctx.errors) != 0 {
msg := "errors generating Go AST from module: \n"
for _, err := range ctx.errors {
msg += " " + err.Error() + "\n"
}
return errors.New(msg)
... | case IntegerType:
// TODO: generate consts
switch ctx.params.IntegerRepr {
case IntegerReprInt64:
return goast.NewIdent("int64") // TODO signed, unsigned, range constraints
case IntegerReprBigInt:
ctx.requireModule("math/big")
return &goast.StarExpr{X: goast.NewIdent("big.Int")}
default:
ctx.appe... | random_line_split | |
codegen.go |
}
ctx.requiredModules = append(ctx.requiredModules, module)
}
// Generate declarations from module to be used together with encoding/asn1.
//
// Feature support status:
// - [x] ModuleIdentifier
// - [x] TagDefault (except AUTOMATIC)
// - [ ] ExtensibilityImplied
// - [.] ModuleBody -- see moduleContext.generateDec... | {
return
} | conditional_block | |
codegen.go | : fmt.Sprintf("\"%v\"", moduleName)}
specs := []goast.Spec{&goast.ImportSpec{Path: modulePath}}
importDecls = append(importDecls, &goast.GenDecl{Tok: gotoken.IMPORT, Specs: specs})
}
ast.Decls = append(importDecls, ast.Decls...)
return goprint.Fprint(writer, gotoken.NewFileSet(), ast)
}
func goifyName(name stri... | taggedChoiceTypeAlternative | identifier_name | |
family_structs.go | ID: util.RandomID(),
PersonID: f.model.PersonID,
Latitude: city.Latitude,
Longitude: city.Longitude,
Country: city.Country,
City: city.City,
EventType: name,
Year: year,
}
f.events = append(f.events, event)
return event
}
func (f *Person) createMirrorEvent(event models.Event) {
event.... | }
}
return
}
/*
MarriageYears will return the person's marriage years
*/
func (f Person) MarriageYears() []int {
return f.marriageYears
}
/*
DivorceYears returns the person's divorce years
*/
func (f Person) DivorceYears() []int {
return f.divorceYears
}
/*
Generation is what the name implies, and represented ... | m[spouse] = append(m[spouse], child)
} | random_line_split |
family_structs.go |
err = event.Save()
if err != nil {
return
}
}
return
}
/*
Dies will appropriately set the Person as dead at given year
*/
func (f *Person) Dies(year int) {
f.deathYear = year
f.createEvent("DEATH", year)
}
/*
Born will set the person's birth year and create the birth event
*/
func (f *Person) Born(year ... | {
return true
} | conditional_block | |
family_structs.go | : util.RandomID(),
PersonID: f.model.PersonID,
Latitude: city.Latitude,
Longitude: city.Longitude,
Country: city.Country,
City: city.City,
EventType: name,
Year: year,
}
f.events = append(f.events, event)
return event
}
func (f *Person) createMirrorEvent(event models.Event) {
event.Ev... | () bool {
return f.deathYear != -1
}
/*
IsMarried returns if the person is married or not
*/
func (f Person) IsMarried() bool {
return f.married
}
/*
IsStraight returns if the person is straight or not
*/
func (f Person) IsStraight() bool {
return f.straight
}
/*
Gender will return the person's gender
*/
func (f ... | IsDead | identifier_name |
family_structs.go | : util.RandomID(),
PersonID: f.model.PersonID,
Latitude: city.Latitude,
Longitude: city.Longitude,
Country: city.Country,
City: city.City,
EventType: name,
Year: year,
}
f.events = append(f.events, event)
return event
}
func (f *Person) createMirrorEvent(event models.Event) {
event.Ev... |
/*
Spouses returns a slice of the person's spouses in
chronological order
*/
func (f Person) Spouses() []*Person {
return f.spouses
}
/*
CurrSpouse will return the person's current spouse,
and return an error if person isn't married
*/
func (f Person) CurrSpouse() (spouse *Person, err error) {
if !f.married {
re... | {
return f.deathYear
} | identifier_body |
medicalbillregistersummary.component.ts | ',
dateA11yLabel: 'DD-MM-YYYY',
monthYearA11yLabel: 'MMMM YYYY',
},
}
@Component({
selector: 'app-medicalbillregistersummary',
templateUrl: './medicalbillregistersummary.component.html',
styleUrls: ['./medicalbillregistersummary.component.less'],
providers: [
{ provide: DateAdapter, useClass: Mome... |
onSubmit(form: NgForm) {
debugger;
| {
debugger;
this.backdrop = 'none';
this.cancelblock = 'none';
//this.MFromDate = '';
//this.MToDate = '';
this.MedicalBillRegisterTable = false;
this.MedicalBillSummaryTable = false;
this.MBS_label = false;
} | identifier_body |
medicalbillregistersummary.component.ts | ',
dateA11yLabel: 'DD-MM-YYYY',
monthYearA11yLabel: 'MMMM YYYY',
},
}
@Component({
selector: 'app-medicalbillregistersummary',
templateUrl: './medicalbillregistersummary.component.html',
styleUrls: ['./medicalbillregistersummary.component.less'],
providers: [
{ provide: DateAdapter, useClass: Mome... | () {
var totDiscntAmt1 = this.commonService.data.getSummaryDet.map(t => t.Damt).reduce((acc, value) => acc + value, 0);
totDiscntAmt1 = parseFloat(totDiscntAmt1.toFixed(2));
return totDiscntAmt1;
}
getGSTAmount1() {
var totGSTAmt1 = this.commonService.data.getSummaryDet.map(t => t.Gamt).reduce((acc... | getDiscountAmount1 | identifier_name |
medicalbillregistersummary.component.ts | ',
dateA11yLabel: 'DD-MM-YYYY',
monthYearA11yLabel: 'MMMM YYYY',
},
}
@Component({
selector: 'app-medicalbillregistersummary',
templateUrl: './medicalbillregistersummary.component.html',
styleUrls: ['./medicalbillregistersummary.component.less'],
providers: [
{ provide: DateAdapter, useClass: Mome... | changeValueTotal(id, element, property: string) {
var resTotal = (element.Quantity * element.Rate) + element.GSTValue - element.DiscountAmount;
resTotal = parseFloat(resTotal.toFixed(2));
element.TotalCost = resTotal;
}
getTotalProdVal() {
var totProdVal = this.commonService.data.getRegisterDeta... | M_ToDat;
| random_line_split |
medicalbillregistersummary.component.ts | (public commonService: CommonService<BillingPharmacy>) { }
MedicalBillRegisterTable: boolean = false;
MedicalBillSummaryTable: boolean = false;
MBS_label: boolean = false;
date = new FormControl(new Date());
ngOnInit() {
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterVa... | {
debugger;
var res = ((data.getRegisterDetail[i].Quantity * data.getRegisterDetail[i].Rate) + data.getRegisterDetail[i].GSTValue) - data.getRegisterDetail[i].DiscountAmount;
data.getRegisterDetail[i].TotalCost = res;
} | conditional_block | |
cargo_workspace.rs | ra_arena::{Arena, Idx};
use ra_cargo_watch::run_cargo;
use ra_db::Edition;
use rustc_hash::FxHashMap;
use serde::Deserialize;
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
/// workspace. It pretty closely mirrors `cargo metadata` output.
///
/// Note that internally, rust analyzer uses a dif... | }
}
#[derive(Debug, Clone, Default)]
pub struct ExternResources {
out_dirs: FxHashMap<PackageId, PathBuf>,
proc_dylib_paths: FxHashMap<PackageId, PathBuf>,
}
pub fn load_extern_resources(cargo_toml: &Path, cargo_features: &CargoFeatures) -> ExternResources {
let mut args: Vec<String> = vec![
"... | .copied()
}
pub fn workspace_root(&self) -> &Path {
&self.workspace_root | random_line_split |
cargo_workspace.rs | ra_arena::{Arena, Idx};
use ra_cargo_watch::run_cargo;
use ra_db::Edition;
use rustc_hash::FxHashMap;
use serde::Deserialize;
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
/// workspace. It pretty closely mirrors `cargo metadata` output.
///
/// Note that internally, rust analyzer uses a dif... | {
/// Do not activate the `default` feature.
pub no_default_features: bool,
/// Activate all available features
pub all_features: bool,
/// List of features to activate.
/// This will be ignored if `cargo_all_features` is true.
pub features: Vec<String>,
/// Runs cargo check on launc... | CargoFeatures | identifier_name |
SIMulator_functions.py | (x, opt):
return np.clip(np.cos(x), 0, 1)
def cos_wave_envelope(x, h, opt):
period_in_pixels = opt.w / (opt.k2)
p = period_in_pixels
f = 1 / p
# h = 2*pi*opt.k2*(h-0.5)+10
h = h*opt.w - opt.w/2 + 10
window = np.where(np.abs(x - h) <= period_in_pixels/4, 1, 0)
maxval = np.max(window *... | cos_wave | identifier_name | |
SIMulator_functions.py | 512 - 1, padding * int(crop_factor_x * 912)
)
y = np.linspace(
0, padding * crop_factor_y * 512 - 1, padding * int(crop_factor_y * 1140)
)
[X, Y] = np.meshgrid(x, y)
else:
x = np.linspace(0, w - 1, w)
y = np.linspace(0, w - 1, w)
X, Y = np.meshgri... | N = opt.Nspeckles
I = np.zeros((dim, dim))
randx = np.random.choice(
list(range(dim)) * np.ceil(N / dim).astype("int"), size=N, replace=False
)
randy = np.random.choice(
list(range(dim)) * np.ceil(N / dim).astype("int"), size=N, replace=False
)
for i in range(N):
x = ran... | identifier_body | |
SIMulator_functions.py | 2dmax = np.max([np.abs(OTF2d)])
OTF2d = OTF2d / OTF2dmax
OTF2dc = np.abs(fftshift(OTF2d))
return (yy0, OTF2dc)
def conv2(x, y, mode="same"):
# Make it equivalent to Matlab's conv2 function
# https://stackoverflow.com/questions/3731093/is-there-a-python-equivalent-of-matlabs-conv2-function
ret... | random_line_split | ||
SIMulator_functions.py |
crop_factor_x = dim[1] / 912 # 428
crop_factor_y = dim[0] / 1140 # 684
# data from dec 2022 acquired with DMD patterns with the below factors
# crop_factor_x = 1
# crop_factor_y = 1
# first version, december 2022
# wo = w / 2
# x = np.linspace... | dim = (dim, dim) | conditional_block | |
factory.go | 91:
signMode = signing.SignMode_SIGN_MODE_EIP_191
}
var accNum, accSeq uint64
if clientCtx.Offline {
if flagSet.Changed(flags.FlagAccountNumber) && flagSet.Changed(flags.FlagSequence) {
accNum = clientCtx.Viper.GetUint64(flags.FlagAccountNumber)
accSeq = clientCtx.Viper.GetUint64(flags.FlagSequence)
} e... | (fp sdk.AccAddress) Factory {
f.feePayer = fp
return f
}
// WithPreprocessTxHook returns a copy of the Factory with an updated preprocess tx function,
// allows for preprocessing of transaction data using the TxBuilder.
func (f Factory) WithPreprocessTxHook(preprocessFn client.PreprocessTxFn) Factory {
f.preprocess... | WithFeePayer | identifier_name |
factory.go | 1:
signMode = signing.SignMode_SIGN_MODE_EIP_191
}
var accNum, accSeq uint64
if clientCtx.Offline {
if flagSet.Changed(flags.FlagAccountNumber) && flagSet.Changed(flags.FlagSequence) {
accNum = clientCtx.Viper.GetUint64(flags.FlagAccountNumber)
accSeq = clientCtx.Viper.GetUint64(flags.FlagSequence)
} el... |
// WithFeePayer returns a copy of the Factory with an updated fee granter.
func (f Factory) WithFeePayer(fp sdk.AccAddress) Factory {
f.feePayer = fp
return f
}
// WithPreprocessTxHook returns a copy of the Factory with an updated preprocess tx function,
// allows for preprocessing of transaction data using the Tx... | {
f.feeGranter = fg
return f
} | identifier_body |
factory.go | feePayer sdk.AccAddress
gasPrices sdk.DecCoins
extOptions []*codectypes.Any
signMode signing.SignMode
simulateAndExecute bool
preprocessTxHook client.PreprocessTxFn
}
// NewFactoryCLI creates a new Factory.
func NewFactoryCLI(clientCtx client.Context, flagSet *pflag.FlagSet... | feeGranter sdk.AccAddress | random_line_split | |
factory.go | AndExecute(sim bool) Factory {
f.simulateAndExecute = sim
return f
}
// SignMode returns the sign mode configured in the Factory
func (f Factory) SignMode() signing.SignMode {
return f.signMode
}
// WithSignMode returns a copy of the Factory with an updated sign mode value.
func (f Factory) WithSignMode(mode signi... | {
fc = fc.WithSequence(seq)
} | conditional_block | |
mgclarge.go | Iter {
f := treapFilter(mask, match)
return treapIter{f, root.treap.findMaximal(f)}
}
// mutate allows one to mutate the span without removing it from the treap via a
// callback. The span's base and size are allowed to change as long as the span
// remains in the same order relative to its predecessor and successor... | rotateRight | identifier_name | |
mgclarge.go |
// pred returns the predecessor of t in the treap subject to the criteria
// specified by the filter f. Returns nil if no such predecessor exists.
func (t *treapNode) pred(f treapIterFilter) *treapNode {
if t.left != nil && f.matches(t.left.types) {
// The node has a left subtree which contains at least one matchi... | {
if t == nil || !f.matches(t.types) {
return nil
}
for t != nil {
if t.right != nil && f.matches(t.right.types) {
t = t.right
} else if f.matches(t.span.treapFilter()) {
break
} else if t.left != nil && f.matches(t.left.types) {
t = t.left
} else {
println("runtime: f=", f)
throw("failed to... | identifier_body | |
mgclarge.go |
// over the treap. Each different flag is represented by a bit
// in the type, and types may be combined together by a bitwise
// or operation.
//
// Note that only 5 bits are available for treapIterType, do not
// use the 3 higher-order bits. This constraint is to allow for
// expansion into a treapIterFilter, which ... | {
p.left = nil
} | conditional_block | |
mgclarge.go | ap rebalancing inside of fn
// is strictly forbidden, as that may cause treap node metadata to go
// out-of-sync.
func (root *mTreap) mutate(i treapIter, fn func(span *mspan)) {
s := i.span()
// Save some state about the span for later inspection.
hpages := s.hugePages()
scavenged := s.scavenged
// Call the mutato... | y.parent = x
y.left = b
if b != nil {
b.parent = y
} | random_line_split | |
variables.go | elletier/go-toml"
)
const (
bootTimeoutSecondsDefault = 60
bootRetrySecondsDefault = 1
defaultConfDirValue = "./res"
envKeyConfigUrl = "EDGEX_CONFIGURATION_PROVIDER"
envKeyUseRegistry = "EDGEX_USE_REGISTRY"
envKeyStartupDuration = "EDGEX_STARTUP_DURATION"
envKeyStartupInterval = "EDGEX_STARTU... |
// convertToType attempts to convert the string value to the specified type of the old value
func (_ *Variables) convertToType(oldValue interface{}, value string) (newValue interface{}, err error) {
switch oldValue.(type) {
case []string:
newValue = parseCommaSeparatedSlice(value)
case []interface{}:
newValue ... | {
url := os.Getenv(envKeyConfigUrl)
if len(url) > 0 {
logEnvironmentOverride(e.lc, "Configuration Provider Information", envKeyConfigUrl, url)
if err := configProviderInfo.PopulateFromUrl(url); err != nil {
return types.ServiceConfig{}, err
}
}
return configProviderInfo, nil
} | identifier_body |
variables.go | elletier/go-toml"
)
const (
bootTimeoutSecondsDefault = 60
bootRetrySecondsDefault = 1
defaultConfDirValue = "./res"
envKeyConfigUrl = "EDGEX_CONFIGURATION_PROVIDER"
envKeyUseRegistry = "EDGEX_USE_REGISTRY"
envKeyStartupDuration = "EDGEX_STARTUP_DURATION"
envKeyStartupInterval = "EDGEX_STARTU... |
// The toml.Tree API keys() only return to top level keys, rather that paths.
// It is also missing a GetPaths so have to spin our own
paths := e.buildPaths(configTree.ToMap())
// Now that we have all the paths in the config tree, we need to create map of corresponding override names that
// could match override... | {
return 0, err
} | conditional_block |
variables.go | /pelletier/go-toml"
)
const (
bootTimeoutSecondsDefault = 60
bootRetrySecondsDefault = 1
defaultConfDirValue = "./res"
envKeyConfigUrl = "EDGEX_CONFIGURATION_PROVIDER"
envKeyUseRegistry = "EDGEX_USE_REGISTRY"
envKeyStartupDuration = "EDGEX_STARTUP_DURATION"
envKeyStartupInterval = "EDGEX_STAR... | }
return names
}
func (_ *Variables) getOverrideNameFor(path string) string {
// "." & "-" are the only special character allowed in TOML path not allowed in environment variable Name
override := strings.ReplaceAll(path, tomlPathSeparator, envNameSeparator)
override = strings.ReplaceAll(override, tomlNameSeparat... | random_line_split | |
variables.go | elletier/go-toml"
)
const (
bootTimeoutSecondsDefault = 60
bootRetrySecondsDefault = 1
defaultConfDirValue = "./res"
envKeyConfigUrl = "EDGEX_CONFIGURATION_PROVIDER"
envKeyUseRegistry = "EDGEX_USE_REGISTRY"
envKeyStartupDuration = "EDGEX_STARTUP_DURATION"
envKeyStartupInterval = "EDGEX_STARTU... | (serviceConfig interface{}) (int, error) {
var overrideCount = 0
contents, err := toml.Marshal(reflect.ValueOf(serviceConfig).Elem().Interface())
if err != nil {
return 0, err
}
configTree, err := toml.LoadBytes(contents)
if err != nil {
return 0, err
}
// The toml.Tree API keys() only return to top leve... | OverrideConfiguration | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.